blob: 95b9918bca6a5b94d24abafb6a3be16b575ec5f3 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
38
39#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070055#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070056#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070057// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
58
Mathias Agopian65ab4712010-07-14 17:59:35 -070059// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070060
Eric Laurentde070132010-07-13 04:45:46 -070061
Mathias Agopian65ab4712010-07-14 17:59:35 -070062namespace android {
63
64static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
65static const char* kHardwareLockedString = "Hardware lock is taken\n";
66
67//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
68static const float MAX_GAIN = 4096.0f;
69static const float MAX_GAIN_INT = 0x1000;
70
71// retry counts for buffer fill timeout
72// 50 * ~20msecs = 1 second
73static const int8_t kMaxTrackRetries = 50;
74static const int8_t kMaxTrackStartupRetries = 50;
75// allow less retry attempts on direct output thread.
76// direct outputs can be a scarce resource in audio hardware and should
77// be released as quickly as possible.
78static const int8_t kMaxTrackRetriesDirect = 2;
79
80static const int kDumpLockRetries = 50;
81static const int kDumpLockSleep = 20000;
82
83static const nsecs_t kWarningThrottle = seconds(5);
84
Eric Laurent7c7f10b2011-06-17 21:29:58 -070085// RecordThread loop sleep time upon application overrun or audio HAL read error
86static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
89
90static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070091 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
92 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
93 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
94 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070095}
96
97static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070098 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
99 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
100 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
101 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102}
103
Gloria Wang9ee159b2011-02-24 14:51:45 -0800104// To collect the amplifier usage
105static void addBatteryData(uint32_t params) {
106 sp<IBinder> binder =
107 defaultServiceManager()->getService(String16("media.player"));
108 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
109 if (service.get() == NULL) {
110 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
111 return;
112 }
113
114 service->addBatteryData(params);
115}
116
Dima Zavin799a70e2011-04-18 16:57:27 -0700117static int load_audio_interface(const char *if_name, const hw_module_t **mod,
118 audio_hw_device_t **dev)
119{
120 int rc;
121
122 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
123 if (rc)
124 goto out;
125
126 rc = audio_hw_device_open(*mod, dev);
127 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
128 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
129 if (rc)
130 goto out;
131
132 return 0;
133
134out:
135 *mod = NULL;
136 *dev = NULL;
137 return rc;
138}
139
140static const char *audio_interfaces[] = {
141 "primary",
142 "a2dp",
143 "usb",
144};
145#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
146
Mathias Agopian65ab4712010-07-14 17:59:35 -0700147// ----------------------------------------------------------------------------
148
149AudioFlinger::AudioFlinger()
150 : BnAudioFlinger(),
Dima Zavin799a70e2011-04-18 16:57:27 -0700151 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700152{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700153}
154
155void AudioFlinger::onFirstRef()
156{
Dima Zavin799a70e2011-04-18 16:57:27 -0700157 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700158
Eric Laurent93575202011-01-18 18:39:02 -0800159 Mutex::Autolock _l(mLock);
160
Dima Zavin799a70e2011-04-18 16:57:27 -0700161 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700162 mHardwareStatus = AUDIO_HW_IDLE;
163
Dima Zavin799a70e2011-04-18 16:57:27 -0700164 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
165 const hw_module_t *mod;
166 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700167
Dima Zavin799a70e2011-04-18 16:57:27 -0700168 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
169 if (rc)
170 continue;
171
172 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
173 mod->name, mod->id);
174 mAudioHwDevs.push(dev);
175
176 if (!mPrimaryHardwareDev) {
177 mPrimaryHardwareDev = dev;
178 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700179 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700180 }
181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700182
183 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700184
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
186 LOGE("Primary audio interface not found");
187 return;
188 }
189
190 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
191 audio_hw_device_t *dev = mAudioHwDevs[i];
192
193 mHardwareStatus = AUDIO_HW_INIT;
194 rc = dev->init_check(dev);
195 if (rc == 0) {
196 AutoMutex lock(mHardwareLock);
197
198 mMode = AUDIO_MODE_NORMAL;
199 mHardwareStatus = AUDIO_HW_SET_MODE;
200 dev->set_mode(dev, mMode);
201 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
202 dev->set_master_volume(dev, 1.0f);
203 mHardwareStatus = AUDIO_HW_IDLE;
204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700206}
207
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700208status_t AudioFlinger::initCheck() const
209{
210 Mutex::Autolock _l(mLock);
211 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
212 return NO_INIT;
213 return NO_ERROR;
214}
215
Mathias Agopian65ab4712010-07-14 17:59:35 -0700216AudioFlinger::~AudioFlinger()
217{
Dima Zavin799a70e2011-04-18 16:57:27 -0700218 int num_devs = mAudioHwDevs.size();
219
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 while (!mRecordThreads.isEmpty()) {
221 // closeInput() will remove first entry from mRecordThreads
222 closeInput(mRecordThreads.keyAt(0));
223 }
224 while (!mPlaybackThreads.isEmpty()) {
225 // closeOutput() will remove first entry from mPlaybackThreads
226 closeOutput(mPlaybackThreads.keyAt(0));
227 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700228
229 for (int i = 0; i < num_devs; i++) {
230 audio_hw_device_t *dev = mAudioHwDevs[i];
231 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700234}
235
Dima Zavin799a70e2011-04-18 16:57:27 -0700236audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
237{
238 /* first matching HW device is returned */
239 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
240 audio_hw_device_t *dev = mAudioHwDevs[i];
241 if ((dev->get_supported_devices(dev) & devices) == devices)
242 return dev;
243 }
244 return NULL;
245}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246
247status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
248{
249 const size_t SIZE = 256;
250 char buffer[SIZE];
251 String8 result;
252
253 result.append("Clients:\n");
254 for (size_t i = 0; i < mClients.size(); ++i) {
255 wp<Client> wClient = mClients.valueAt(i);
256 if (wClient != 0) {
257 sp<Client> client = wClient.promote();
258 if (client != 0) {
259 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
260 result.append(buffer);
261 }
262 }
263 }
264 write(fd, result.string(), result.size());
265 return NO_ERROR;
266}
267
268
269status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
270{
271 const size_t SIZE = 256;
272 char buffer[SIZE];
273 String8 result;
274 int hardwareStatus = mHardwareStatus;
275
276 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
277 result.append(buffer);
278 write(fd, result.string(), result.size());
279 return NO_ERROR;
280}
281
282status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287 snprintf(buffer, SIZE, "Permission Denial: "
288 "can't dump AudioFlinger from pid=%d, uid=%d\n",
289 IPCThreadState::self()->getCallingPid(),
290 IPCThreadState::self()->getCallingUid());
291 result.append(buffer);
292 write(fd, result.string(), result.size());
293 return NO_ERROR;
294}
295
296static bool tryLock(Mutex& mutex)
297{
298 bool locked = false;
299 for (int i = 0; i < kDumpLockRetries; ++i) {
300 if (mutex.tryLock() == NO_ERROR) {
301 locked = true;
302 break;
303 }
304 usleep(kDumpLockSleep);
305 }
306 return locked;
307}
308
309status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
310{
311 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
312 dumpPermissionDenial(fd, args);
313 } else {
314 // get state of hardware lock
315 bool hardwareLocked = tryLock(mHardwareLock);
316 if (!hardwareLocked) {
317 String8 result(kHardwareLockedString);
318 write(fd, result.string(), result.size());
319 } else {
320 mHardwareLock.unlock();
321 }
322
323 bool locked = tryLock(mLock);
324
325 // failed to lock - AudioFlinger is probably deadlocked
326 if (!locked) {
327 String8 result(kDeadlockedString);
328 write(fd, result.string(), result.size());
329 }
330
331 dumpClients(fd, args);
332 dumpInternals(fd, args);
333
334 // dump playback threads
335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
336 mPlaybackThreads.valueAt(i)->dump(fd, args);
337 }
338
339 // dump record threads
340 for (size_t i = 0; i < mRecordThreads.size(); i++) {
341 mRecordThreads.valueAt(i)->dump(fd, args);
342 }
343
Dima Zavin799a70e2011-04-18 16:57:27 -0700344 // dump all hardware devs
345 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
346 audio_hw_device_t *dev = mAudioHwDevs[i];
347 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348 }
349 if (locked) mLock.unlock();
350 }
351 return NO_ERROR;
352}
353
354
355// IAudioFlinger interface
356
357
358sp<IAudioTrack> AudioFlinger::createTrack(
359 pid_t pid,
360 int streamType,
361 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700362 uint32_t format,
363 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364 int frameCount,
365 uint32_t flags,
366 const sp<IMemory>& sharedBuffer,
367 int output,
368 int *sessionId,
369 status_t *status)
370{
371 sp<PlaybackThread::Track> track;
372 sp<TrackHandle> trackHandle;
373 sp<Client> client;
374 wp<Client> wclient;
375 status_t lStatus;
376 int lSessionId;
377
Dima Zavinfce7a472011-04-19 22:30:36 -0700378 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379 LOGE("invalid stream type");
380 lStatus = BAD_VALUE;
381 goto Exit;
382 }
383
384 {
385 Mutex::Autolock _l(mLock);
386 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700387 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388 if (thread == NULL) {
389 LOGE("unknown output thread");
390 lStatus = BAD_VALUE;
391 goto Exit;
392 }
393
394 wclient = mClients.valueFor(pid);
395
396 if (wclient != NULL) {
397 client = wclient.promote();
398 } else {
399 client = new Client(this, pid);
400 mClients.add(pid, client);
401 }
402
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700404 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700406 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
407 if (mPlaybackThreads.keyAt(i) != output) {
408 // prevent same audio session on different output threads
409 uint32_t sessions = t->hasAudioSession(*sessionId);
410 if (sessions & PlaybackThread::TRACK_SESSION) {
411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
414 // check if an effect with same session ID is waiting for a track to be created
415 if (sessions & PlaybackThread::EFFECT_SESSION) {
416 effectThread = t.get();
417 }
Eric Laurentde070132010-07-13 04:45:46 -0700418 }
419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420 lSessionId = *sessionId;
421 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700422 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700423 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424 if (sessionId != NULL) {
425 *sessionId = lSessionId;
426 }
427 }
428 LOGV("createTrack() lSessionId: %d", lSessionId);
429
430 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700431 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700432
433 // move effect chain to this output thread if an effect on same session was waiting
434 // for a track to be created
435 if (lStatus == NO_ERROR && effectThread != NULL) {
436 Mutex::Autolock _dl(thread->mLock);
437 Mutex::Autolock _sl(effectThread->mLock);
438 moveEffectChain_l(lSessionId, effectThread, thread, true);
439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 }
441 if (lStatus == NO_ERROR) {
442 trackHandle = new TrackHandle(track);
443 } else {
444 // remove local strong reference to Client before deleting the Track so that the Client
445 // destructor is called by the TrackBase destructor with mLock held
446 client.clear();
447 track.clear();
448 }
449
450Exit:
451 if(status) {
452 *status = lStatus;
453 }
454 return trackHandle;
455}
456
457uint32_t AudioFlinger::sampleRate(int output) const
458{
459 Mutex::Autolock _l(mLock);
460 PlaybackThread *thread = checkPlaybackThread_l(output);
461 if (thread == NULL) {
462 LOGW("sampleRate() unknown thread %d", output);
463 return 0;
464 }
465 return thread->sampleRate();
466}
467
468int AudioFlinger::channelCount(int output) const
469{
470 Mutex::Autolock _l(mLock);
471 PlaybackThread *thread = checkPlaybackThread_l(output);
472 if (thread == NULL) {
473 LOGW("channelCount() unknown thread %d", output);
474 return 0;
475 }
476 return thread->channelCount();
477}
478
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700479uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480{
481 Mutex::Autolock _l(mLock);
482 PlaybackThread *thread = checkPlaybackThread_l(output);
483 if (thread == NULL) {
484 LOGW("format() unknown thread %d", output);
485 return 0;
486 }
487 return thread->format();
488}
489
490size_t AudioFlinger::frameCount(int output) const
491{
492 Mutex::Autolock _l(mLock);
493 PlaybackThread *thread = checkPlaybackThread_l(output);
494 if (thread == NULL) {
495 LOGW("frameCount() unknown thread %d", output);
496 return 0;
497 }
498 return thread->frameCount();
499}
500
501uint32_t AudioFlinger::latency(int output) const
502{
503 Mutex::Autolock _l(mLock);
504 PlaybackThread *thread = checkPlaybackThread_l(output);
505 if (thread == NULL) {
506 LOGW("latency() unknown thread %d", output);
507 return 0;
508 }
509 return thread->latency();
510}
511
512status_t AudioFlinger::setMasterVolume(float value)
513{
514 // check calling permissions
515 if (!settingsAllowed()) {
516 return PERMISSION_DENIED;
517 }
518
519 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800520 { // scope for the lock
521 AutoMutex lock(mHardwareLock);
522 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700523 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800524 value = 1.0f;
525 }
526 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700528
Eric Laurent93575202011-01-18 18:39:02 -0800529 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 mMasterVolume = value;
531 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
532 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
533
534 return NO_ERROR;
535}
536
537status_t AudioFlinger::setMode(int mode)
538{
539 status_t ret;
540
541 // check calling permissions
542 if (!settingsAllowed()) {
543 return PERMISSION_DENIED;
544 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700545 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 LOGW("Illegal value: setMode(%d)", mode);
547 return BAD_VALUE;
548 }
549
550 { // scope for the lock
551 AutoMutex lock(mHardwareLock);
552 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700553 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 mHardwareStatus = AUDIO_HW_IDLE;
555 }
556
557 if (NO_ERROR == ret) {
558 Mutex::Autolock _l(mLock);
559 mMode = mode;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
561 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 }
563
564 return ret;
565}
566
567status_t AudioFlinger::setMicMute(bool state)
568{
569 // check calling permissions
570 if (!settingsAllowed()) {
571 return PERMISSION_DENIED;
572 }
573
574 AutoMutex lock(mHardwareLock);
575 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700576 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 mHardwareStatus = AUDIO_HW_IDLE;
578 return ret;
579}
580
581bool AudioFlinger::getMicMute() const
582{
Dima Zavinfce7a472011-04-19 22:30:36 -0700583 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700585 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
587 return state;
588}
589
590status_t AudioFlinger::setMasterMute(bool muted)
591{
592 // check calling permissions
593 if (!settingsAllowed()) {
594 return PERMISSION_DENIED;
595 }
596
Eric Laurent93575202011-01-18 18:39:02 -0800597 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 mMasterMute = muted;
599 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
600 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
601
602 return NO_ERROR;
603}
604
605float AudioFlinger::masterVolume() const
606{
607 return mMasterVolume;
608}
609
610bool AudioFlinger::masterMute() const
611{
612 return mMasterMute;
613}
614
615status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
616{
617 // check calling permissions
618 if (!settingsAllowed()) {
619 return PERMISSION_DENIED;
620 }
621
Dima Zavinfce7a472011-04-19 22:30:36 -0700622 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 return BAD_VALUE;
624 }
625
626 AutoMutex lock(mLock);
627 PlaybackThread *thread = NULL;
628 if (output) {
629 thread = checkPlaybackThread_l(output);
630 if (thread == NULL) {
631 return BAD_VALUE;
632 }
633 }
634
635 mStreamTypes[stream].volume = value;
636
637 if (thread == NULL) {
638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
639 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
640 }
641 } else {
642 thread->setStreamVolume(stream, value);
643 }
644
645 return NO_ERROR;
646}
647
648status_t AudioFlinger::setStreamMute(int stream, bool muted)
649{
650 // check calling permissions
651 if (!settingsAllowed()) {
652 return PERMISSION_DENIED;
653 }
654
Dima Zavinfce7a472011-04-19 22:30:36 -0700655 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
656 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657 return BAD_VALUE;
658 }
659
Eric Laurent93575202011-01-18 18:39:02 -0800660 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 mStreamTypes[stream].mute = muted;
662 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
663 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
664
665 return NO_ERROR;
666}
667
668float AudioFlinger::streamVolume(int stream, int output) const
669{
Dima Zavinfce7a472011-04-19 22:30:36 -0700670 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700671 return 0.0f;
672 }
673
674 AutoMutex lock(mLock);
675 float volume;
676 if (output) {
677 PlaybackThread *thread = checkPlaybackThread_l(output);
678 if (thread == NULL) {
679 return 0.0f;
680 }
681 volume = thread->streamVolume(stream);
682 } else {
683 volume = mStreamTypes[stream].volume;
684 }
685
686 return volume;
687}
688
689bool AudioFlinger::streamMute(int stream) const
690{
Dima Zavinfce7a472011-04-19 22:30:36 -0700691 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 return true;
693 }
694
695 return mStreamTypes[stream].mute;
696}
697
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
699{
700 status_t result;
701
702 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
703 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
704 // check calling permissions
705 if (!settingsAllowed()) {
706 return PERMISSION_DENIED;
707 }
708
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 // ioHandle == 0 means the parameters are global to the audio hardware interface
710 if (ioHandle == 0) {
711 AutoMutex lock(mHardwareLock);
712 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700713 status_t final_result = NO_ERROR;
714 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
715 audio_hw_device_t *dev = mAudioHwDevs[i];
716 result = dev->set_parameters(dev, keyValuePairs.string());
717 final_result = result ?: final_result;
718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700720 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 }
722
723 // hold a strong ref on thread in case closeOutput() or closeInput() is called
724 // and the thread is exited once the lock is released
725 sp<ThreadBase> thread;
726 {
727 Mutex::Autolock _l(mLock);
728 thread = checkPlaybackThread_l(ioHandle);
729 if (thread == NULL) {
730 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700731 } else if (thread.get() == primaryPlaybackThread_l()) {
732 // indicate output device change to all input threads for pre processing
733 AudioParameter param = AudioParameter(keyValuePairs);
734 int value;
735 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
736 for (size_t i = 0; i < mRecordThreads.size(); i++) {
737 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
738 }
739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 }
741 }
742 if (thread != NULL) {
743 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744 return result;
745 }
746 return BAD_VALUE;
747}
748
749String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
750{
751// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
752// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
753
754 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700755 String8 out_s8;
756
Dima Zavin799a70e2011-04-18 16:57:27 -0700757 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
758 audio_hw_device_t *dev = mAudioHwDevs[i];
759 char *s = dev->get_parameters(dev, keys.string());
760 out_s8 += String8(s);
761 free(s);
762 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700763 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 }
765
766 Mutex::Autolock _l(mLock);
767
768 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
769 if (playbackThread != NULL) {
770 return playbackThread->getParameters(keys);
771 }
772 RecordThread *recordThread = checkRecordThread_l(ioHandle);
773 if (recordThread != NULL) {
774 return recordThread->getParameters(keys);
775 }
776 return String8("");
777}
778
779size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
780{
Dima Zavin799a70e2011-04-18 16:57:27 -0700781 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782}
783
784unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
785{
786 if (ioHandle == 0) {
787 return 0;
788 }
789
790 Mutex::Autolock _l(mLock);
791
792 RecordThread *recordThread = checkRecordThread_l(ioHandle);
793 if (recordThread != NULL) {
794 return recordThread->getInputFramesLost();
795 }
796 return 0;
797}
798
799status_t AudioFlinger::setVoiceVolume(float value)
800{
801 // check calling permissions
802 if (!settingsAllowed()) {
803 return PERMISSION_DENIED;
804 }
805
806 AutoMutex lock(mHardwareLock);
807 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700808 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 mHardwareStatus = AUDIO_HW_IDLE;
810
811 return ret;
812}
813
814status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
815{
816 status_t status;
817
818 Mutex::Autolock _l(mLock);
819
820 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
821 if (playbackThread != NULL) {
822 return playbackThread->getRenderPosition(halFrames, dspFrames);
823 }
824
825 return BAD_VALUE;
826}
827
828void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
829{
830
831 Mutex::Autolock _l(mLock);
832
833 int pid = IPCThreadState::self()->getCallingPid();
834 if (mNotificationClients.indexOfKey(pid) < 0) {
835 sp<NotificationClient> notificationClient = new NotificationClient(this,
836 client,
837 pid);
838 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
839
840 mNotificationClients.add(pid, notificationClient);
841
842 sp<IBinder> binder = client->asBinder();
843 binder->linkToDeath(notificationClient);
844
845 // the config change is always sent from playback or record threads to avoid deadlock
846 // with AudioSystem::gLock
847 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
848 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
849 }
850
851 for (size_t i = 0; i < mRecordThreads.size(); i++) {
852 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
853 }
854 }
855}
856
857void AudioFlinger::removeNotificationClient(pid_t pid)
858{
859 Mutex::Autolock _l(mLock);
860
861 int index = mNotificationClients.indexOfKey(pid);
862 if (index >= 0) {
863 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
864 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 mNotificationClients.removeItem(pid);
866 }
867}
868
869// audioConfigChanged_l() must be called with AudioFlinger::mLock held
870void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
871{
872 size_t size = mNotificationClients.size();
873 for (size_t i = 0; i < size; i++) {
874 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
875 }
876}
877
878// removeClient_l() must be called with AudioFlinger::mLock held
879void AudioFlinger::removeClient_l(pid_t pid)
880{
881 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
882 mClients.removeItem(pid);
883}
884
885
886// ----------------------------------------------------------------------------
887
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700888AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 : Thread(false),
890 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700891 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
892 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700894 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895}
896
897AudioFlinger::ThreadBase::~ThreadBase()
898{
899 mParamCond.broadcast();
900 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700901 // do not lock the mutex in destructor
902 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903}
904
905void AudioFlinger::ThreadBase::exit()
906{
907 // keep a strong ref on ourself so that we wont get
908 // destroyed in the middle of requestExitAndWait()
909 sp <ThreadBase> strongMe = this;
910
911 LOGV("ThreadBase::exit");
912 {
913 AutoMutex lock(&mLock);
914 mExiting = true;
915 requestExit();
916 mWaitWorkCV.signal();
917 }
918 requestExitAndWait();
919}
920
921uint32_t AudioFlinger::ThreadBase::sampleRate() const
922{
923 return mSampleRate;
924}
925
926int AudioFlinger::ThreadBase::channelCount() const
927{
928 return (int)mChannelCount;
929}
930
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700931uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932{
933 return mFormat;
934}
935
936size_t AudioFlinger::ThreadBase::frameCount() const
937{
938 return mFrameCount;
939}
940
941status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
942{
943 status_t status;
944
945 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
946 Mutex::Autolock _l(mLock);
947
948 mNewParameters.add(keyValuePairs);
949 mWaitWorkCV.signal();
950 // wait condition with timeout in case the thread loop has exited
951 // before the request could be processed
952 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
953 status = mParamStatus;
954 mWaitWorkCV.signal();
955 } else {
956 status = TIMED_OUT;
957 }
958 return status;
959}
960
961void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
962{
963 Mutex::Autolock _l(mLock);
964 sendConfigEvent_l(event, param);
965}
966
967// sendConfigEvent_l() must be called with ThreadBase::mLock held
968void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
969{
970 ConfigEvent *configEvent = new ConfigEvent();
971 configEvent->mEvent = event;
972 configEvent->mParam = param;
973 mConfigEvents.add(configEvent);
974 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
975 mWaitWorkCV.signal();
976}
977
978void AudioFlinger::ThreadBase::processConfigEvents()
979{
980 mLock.lock();
981 while(!mConfigEvents.isEmpty()) {
982 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
983 ConfigEvent *configEvent = mConfigEvents[0];
984 mConfigEvents.removeAt(0);
985 // release mLock before locking AudioFlinger mLock: lock order is always
986 // AudioFlinger then ThreadBase to avoid cross deadlock
987 mLock.unlock();
988 mAudioFlinger->mLock.lock();
989 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
990 mAudioFlinger->mLock.unlock();
991 delete configEvent;
992 mLock.lock();
993 }
994 mLock.unlock();
995}
996
997status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
998{
999 const size_t SIZE = 256;
1000 char buffer[SIZE];
1001 String8 result;
1002
1003 bool locked = tryLock(mLock);
1004 if (!locked) {
1005 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1006 write(fd, buffer, strlen(buffer));
1007 }
1008
1009 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1010 result.append(buffer);
1011 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1012 result.append(buffer);
1013 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1014 result.append(buffer);
1015 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1016 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001017 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1018 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1020 result.append(buffer);
1021 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1022 result.append(buffer);
1023
1024 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1025 result.append(buffer);
1026 result.append(" Index Command");
1027 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1028 snprintf(buffer, SIZE, "\n %02d ", i);
1029 result.append(buffer);
1030 result.append(mNewParameters[i]);
1031 }
1032
1033 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1034 result.append(buffer);
1035 snprintf(buffer, SIZE, " Index event param\n");
1036 result.append(buffer);
1037 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1038 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1039 result.append(buffer);
1040 }
1041 result.append("\n");
1042
1043 write(fd, result.string(), result.size());
1044
1045 if (locked) {
1046 mLock.unlock();
1047 }
1048 return NO_ERROR;
1049}
1050
Eric Laurent1d2bff02011-07-24 17:49:51 -07001051status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1052{
1053 const size_t SIZE = 256;
1054 char buffer[SIZE];
1055 String8 result;
1056
1057 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1058 write(fd, buffer, strlen(buffer));
1059
1060 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1061 sp<EffectChain> chain = mEffectChains[i];
1062 if (chain != 0) {
1063 chain->dump(fd, args);
1064 }
1065 }
1066 return NO_ERROR;
1067}
1068
Eric Laurentfeb0db62011-07-22 09:04:31 -07001069void AudioFlinger::ThreadBase::acquireWakeLock()
1070{
1071 Mutex::Autolock _l(mLock);
1072 acquireWakeLock_l();
1073}
1074
1075void AudioFlinger::ThreadBase::acquireWakeLock_l()
1076{
1077 if (mPowerManager == 0) {
1078 // use checkService() to avoid blocking if power service is not up yet
1079 sp<IBinder> binder =
1080 defaultServiceManager()->checkService(String16("power"));
1081 if (binder == 0) {
1082 LOGW("Thread %s cannot connect to the power manager service", mName);
1083 } else {
1084 mPowerManager = interface_cast<IPowerManager>(binder);
1085 binder->linkToDeath(mDeathRecipient);
1086 }
1087 }
1088 if (mPowerManager != 0) {
1089 sp<IBinder> binder = new BBinder();
1090 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1091 binder,
1092 String16(mName));
1093 if (status == NO_ERROR) {
1094 mWakeLockToken = binder;
1095 }
1096 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1097 }
1098}
1099
1100void AudioFlinger::ThreadBase::releaseWakeLock()
1101{
1102 Mutex::Autolock _l(mLock);
1103 releaseWakeLock();
1104}
1105
1106void AudioFlinger::ThreadBase::releaseWakeLock_l()
1107{
1108 if (mWakeLockToken != 0) {
1109 LOGV("releaseWakeLock_l() %s", mName);
1110 if (mPowerManager != 0) {
1111 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1112 }
1113 mWakeLockToken.clear();
1114 }
1115}
1116
1117void AudioFlinger::ThreadBase::clearPowerManager()
1118{
1119 Mutex::Autolock _l(mLock);
1120 releaseWakeLock_l();
1121 mPowerManager.clear();
1122}
1123
1124void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1125{
1126 sp<ThreadBase> thread = mThread.promote();
1127 if (thread != 0) {
1128 thread->clearPowerManager();
1129 }
1130 LOGW("power manager service died !!!");
1131}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001132
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133// ----------------------------------------------------------------------------
1134
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001135AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1136 AudioStreamOut* output,
1137 int id,
1138 uint32_t device)
1139 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001141 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001142{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001143 snprintf(mName, kNameLength, "AudioOut_%d", id);
1144
Mathias Agopian65ab4712010-07-14 17:59:35 -07001145 readOutputParameters();
1146
1147 mMasterVolume = mAudioFlinger->masterVolume();
1148 mMasterMute = mAudioFlinger->masterMute();
1149
Dima Zavinfce7a472011-04-19 22:30:36 -07001150 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001151 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1152 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1153 }
1154}
1155
1156AudioFlinger::PlaybackThread::~PlaybackThread()
1157{
1158 delete [] mMixBuffer;
1159}
1160
1161status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1162{
1163 dumpInternals(fd, args);
1164 dumpTracks(fd, args);
1165 dumpEffectChains(fd, args);
1166 return NO_ERROR;
1167}
1168
1169status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1170{
1171 const size_t SIZE = 256;
1172 char buffer[SIZE];
1173 String8 result;
1174
1175 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1176 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001177 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 for (size_t i = 0; i < mTracks.size(); ++i) {
1179 sp<Track> track = mTracks[i];
1180 if (track != 0) {
1181 track->dump(buffer, SIZE);
1182 result.append(buffer);
1183 }
1184 }
1185
1186 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1187 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001188 result.append(" Name Clien Typ Fmt Chn mask Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1190 wp<Track> wTrack = mActiveTracks[i];
1191 if (wTrack != 0) {
1192 sp<Track> track = wTrack.promote();
1193 if (track != 0) {
1194 track->dump(buffer, SIZE);
1195 result.append(buffer);
1196 }
1197 }
1198 }
1199 write(fd, result.string(), result.size());
1200 return NO_ERROR;
1201}
1202
Mathias Agopian65ab4712010-07-14 17:59:35 -07001203status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1204{
1205 const size_t SIZE = 256;
1206 char buffer[SIZE];
1207 String8 result;
1208
1209 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1210 result.append(buffer);
1211 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1212 result.append(buffer);
1213 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1214 result.append(buffer);
1215 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1216 result.append(buffer);
1217 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1218 result.append(buffer);
1219 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1220 result.append(buffer);
1221 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1222 result.append(buffer);
1223 write(fd, result.string(), result.size());
1224
1225 dumpBase(fd, args);
1226
1227 return NO_ERROR;
1228}
1229
1230// Thread virtuals
1231status_t AudioFlinger::PlaybackThread::readyToRun()
1232{
1233 if (mSampleRate == 0) {
1234 LOGE("No working audio driver found.");
1235 return NO_INIT;
1236 }
1237 LOGI("AudioFlinger's thread %p ready to run", this);
1238 return NO_ERROR;
1239}
1240
1241void AudioFlinger::PlaybackThread::onFirstRef()
1242{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001243 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244}
1245
1246// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1247sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1248 const sp<AudioFlinger::Client>& client,
1249 int streamType,
1250 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001251 uint32_t format,
1252 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001253 int frameCount,
1254 const sp<IMemory>& sharedBuffer,
1255 int sessionId,
1256 status_t *status)
1257{
1258 sp<Track> track;
1259 status_t lStatus;
1260
1261 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001262 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1263 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1264 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1265 "for output %p with format %d",
1266 sampleRate, format, channelMask, mOutput, mFormat);
1267 lStatus = BAD_VALUE;
1268 goto Exit;
1269 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001270 }
1271 } else {
1272 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1273 if (sampleRate > mSampleRate*2) {
1274 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1275 lStatus = BAD_VALUE;
1276 goto Exit;
1277 }
1278 }
1279
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001280 lStatus = initCheck();
1281 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001282 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 goto Exit;
1284 }
1285
1286 { // scope for mLock
1287 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001288
1289 // all tracks in same audio session must share the same routing strategy otherwise
1290 // conflicts will happen when tracks are moved from one output to another by audio policy
1291 // manager
1292 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001293 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001294 for (size_t i = 0; i < mTracks.size(); ++i) {
1295 sp<Track> t = mTracks[i];
1296 if (t != 0) {
1297 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001298 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001299 lStatus = BAD_VALUE;
1300 goto Exit;
1301 }
1302 }
1303 }
1304
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001306 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001307 if (track->getCblk() == NULL || track->name() < 0) {
1308 lStatus = NO_MEMORY;
1309 goto Exit;
1310 }
1311 mTracks.add(track);
1312
1313 sp<EffectChain> chain = getEffectChain_l(sessionId);
1314 if (chain != 0) {
1315 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1316 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001317 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001318 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001319 }
1320 }
1321 lStatus = NO_ERROR;
1322
1323Exit:
1324 if(status) {
1325 *status = lStatus;
1326 }
1327 return track;
1328}
1329
1330uint32_t AudioFlinger::PlaybackThread::latency() const
1331{
1332 if (mOutput) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001333 return mOutput->stream->get_latency(mOutput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001334 }
1335 else {
1336 return 0;
1337 }
1338}
1339
1340status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1341{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001342 mMasterVolume = value;
1343 return NO_ERROR;
1344}
1345
1346status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1347{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001348 mMasterMute = muted;
1349 return NO_ERROR;
1350}
1351
1352float AudioFlinger::PlaybackThread::masterVolume() const
1353{
1354 return mMasterVolume;
1355}
1356
1357bool AudioFlinger::PlaybackThread::masterMute() const
1358{
1359 return mMasterMute;
1360}
1361
1362status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1363{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001364 mStreamTypes[stream].volume = value;
1365 return NO_ERROR;
1366}
1367
1368status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1369{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001370 mStreamTypes[stream].mute = muted;
1371 return NO_ERROR;
1372}
1373
1374float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1375{
1376 return mStreamTypes[stream].volume;
1377}
1378
1379bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1380{
1381 return mStreamTypes[stream].mute;
1382}
1383
Mathias Agopian65ab4712010-07-14 17:59:35 -07001384// addTrack_l() must be called with ThreadBase::mLock held
1385status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1386{
1387 status_t status = ALREADY_EXISTS;
1388
1389 // set retry count for buffer fill
1390 track->mRetryCount = kMaxTrackStartupRetries;
1391 if (mActiveTracks.indexOf(track) < 0) {
1392 // the track is newly added, make sure it fills up all its
1393 // buffers before playing. This is to ensure the client will
1394 // effectively get the latency it requested.
1395 track->mFillingUpStatus = Track::FS_FILLING;
1396 track->mResetDone = false;
1397 mActiveTracks.add(track);
1398 if (track->mainBuffer() != mMixBuffer) {
1399 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1400 if (chain != 0) {
1401 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001402 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403 }
1404 }
1405
1406 status = NO_ERROR;
1407 }
1408
1409 LOGV("mWaitWorkCV.broadcast");
1410 mWaitWorkCV.broadcast();
1411
1412 return status;
1413}
1414
1415// destroyTrack_l() must be called with ThreadBase::mLock held
1416void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1417{
1418 track->mState = TrackBase::TERMINATED;
1419 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001420 removeTrack_l(track);
1421 }
1422}
1423
1424void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1425{
1426 mTracks.remove(track);
1427 deleteTrackName_l(track->name());
1428 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1429 if (chain != 0) {
1430 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 }
1432}
1433
1434String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1435{
Dima Zavinfce7a472011-04-19 22:30:36 -07001436 String8 out_s8;
1437 char *s;
1438
Dima Zavin799a70e2011-04-18 16:57:27 -07001439 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001440 out_s8 = String8(s);
1441 free(s);
1442 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443}
1444
1445// destroyTrack_l() must be called with AudioFlinger::mLock held
1446void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1447 AudioSystem::OutputDescriptor desc;
1448 void *param2 = 0;
1449
1450 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1451
1452 switch (event) {
1453 case AudioSystem::OUTPUT_OPENED:
1454 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001455 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456 desc.samplingRate = mSampleRate;
1457 desc.format = mFormat;
1458 desc.frameCount = mFrameCount;
1459 desc.latency = latency();
1460 param2 = &desc;
1461 break;
1462
1463 case AudioSystem::STREAM_CONFIG_CHANGED:
1464 param2 = &param;
1465 case AudioSystem::OUTPUT_CLOSED:
1466 default:
1467 break;
1468 }
1469 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1470}
1471
1472void AudioFlinger::PlaybackThread::readOutputParameters()
1473{
Dima Zavin799a70e2011-04-18 16:57:27 -07001474 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001475 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1476 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001477 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1478 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1479 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001480
1481 // FIXME - Current mixer implementation only supports stereo output: Always
1482 // Allocate a stereo buffer even if HW output is mono.
1483 if (mMixBuffer != NULL) delete[] mMixBuffer;
1484 mMixBuffer = new int16_t[mFrameCount * 2];
1485 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1486
Eric Laurentde070132010-07-13 04:45:46 -07001487 // force reconfiguration of effect chains and engines to take new buffer size and audio
1488 // parameters into account
1489 // Note that mLock is not held when readOutputParameters() is called from the constructor
1490 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1491 // matter.
1492 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1493 Vector< sp<EffectChain> > effectChains = mEffectChains;
1494 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001495 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001496 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497}
1498
1499status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1500{
1501 if (halFrames == 0 || dspFrames == 0) {
1502 return BAD_VALUE;
1503 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001504 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001505 return INVALID_OPERATION;
1506 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001507 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508
Dima Zavin799a70e2011-04-18 16:57:27 -07001509 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001510}
1511
Eric Laurent39e94f82010-07-28 01:32:47 -07001512uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001513{
1514 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001515 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001516 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001517 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518 }
1519
1520 for (size_t i = 0; i < mTracks.size(); ++i) {
1521 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001522 if (sessionId == track->sessionId() &&
1523 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001524 result |= TRACK_SESSION;
1525 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526 }
1527 }
1528
Eric Laurent39e94f82010-07-28 01:32:47 -07001529 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001530}
1531
Eric Laurentde070132010-07-13 04:45:46 -07001532uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1533{
Dima Zavinfce7a472011-04-19 22:30:36 -07001534 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001535 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001536 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1537 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001538 }
1539 for (size_t i = 0; i < mTracks.size(); i++) {
1540 sp<Track> track = mTracks[i];
1541 if (sessionId == track->sessionId() &&
1542 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001543 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001544 }
1545 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001546 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001547}
1548
Mathias Agopian65ab4712010-07-14 17:59:35 -07001549
1550// ----------------------------------------------------------------------------
1551
Dima Zavin799a70e2011-04-18 16:57:27 -07001552AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001553 : PlaybackThread(audioFlinger, output, id, device),
1554 mAudioMixer(0)
1555{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001556 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001557 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1558
1559 // FIXME - Current mixer implementation only supports stereo output
1560 if (mChannelCount == 1) {
1561 LOGE("Invalid audio hardware channel count");
1562 }
1563}
1564
1565AudioFlinger::MixerThread::~MixerThread()
1566{
1567 delete mAudioMixer;
1568}
1569
1570bool AudioFlinger::MixerThread::threadLoop()
1571{
1572 Vector< sp<Track> > tracksToRemove;
1573 uint32_t mixerStatus = MIXER_IDLE;
1574 nsecs_t standbyTime = systemTime();
1575 size_t mixBufferSize = mFrameCount * mFrameSize;
1576 // FIXME: Relaxed timing because of a certain device that can't meet latency
1577 // Should be reduced to 2x after the vendor fixes the driver issue
1578 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1579 nsecs_t lastWarning = 0;
1580 bool longStandbyExit = false;
1581 uint32_t activeSleepTime = activeSleepTimeUs();
1582 uint32_t idleSleepTime = idleSleepTimeUs();
1583 uint32_t sleepTime = idleSleepTime;
1584 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001585#ifdef DEBUG_CPU_USAGE
1586 ThreadCpuUsage cpu;
1587 const CentralTendencyStatistics& stats = cpu.statistics();
1588#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589
Eric Laurentfeb0db62011-07-22 09:04:31 -07001590 acquireWakeLock();
1591
Mathias Agopian65ab4712010-07-14 17:59:35 -07001592 while (!exitPending())
1593 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001594#ifdef DEBUG_CPU_USAGE
1595 cpu.sampleAndEnable();
1596 unsigned n = stats.n();
1597 // cpu.elapsed() is expensive, so don't call it every loop
1598 if ((n & 127) == 1) {
1599 long long elapsed = cpu.elapsed();
1600 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1601 double perLoop = elapsed / (double) n;
1602 double perLoop100 = perLoop * 0.01;
1603 double mean = stats.mean();
1604 double stddev = stats.stddev();
1605 double minimum = stats.minimum();
1606 double maximum = stats.maximum();
1607 cpu.resetStatistics();
1608 LOGI("CPU usage over past %.1f secs (%u mixer loops at %.1f mean ms per loop):\n us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f",
1609 elapsed * .000000001, n, perLoop * .000001,
1610 mean * .001,
1611 stddev * .001,
1612 minimum * .001,
1613 maximum * .001,
1614 mean / perLoop100,
1615 stddev / perLoop100,
1616 minimum / perLoop100,
1617 maximum / perLoop100);
1618 }
1619 }
1620#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621 processConfigEvents();
1622
1623 mixerStatus = MIXER_IDLE;
1624 { // scope for mLock
1625
1626 Mutex::Autolock _l(mLock);
1627
1628 if (checkForNewParameters_l()) {
1629 mixBufferSize = mFrameCount * mFrameSize;
1630 // FIXME: Relaxed timing because of a certain device that can't meet latency
1631 // Should be reduced to 2x after the vendor fixes the driver issue
1632 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1633 activeSleepTime = activeSleepTimeUs();
1634 idleSleepTime = idleSleepTimeUs();
1635 }
1636
1637 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1638
1639 // put audio hardware into standby after short delay
1640 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1641 mSuspended) {
1642 if (!mStandby) {
1643 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001644 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001645 mStandby = true;
1646 mBytesWritten = 0;
1647 }
1648
1649 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1650 // we're about to wait, flush the binder command buffer
1651 IPCThreadState::self()->flushCommands();
1652
1653 if (exitPending()) break;
1654
Eric Laurentfeb0db62011-07-22 09:04:31 -07001655 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001656 // wait until we have something to do...
1657 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1658 mWaitWorkCV.wait(mLock);
1659 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001660 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001661
1662 if (mMasterMute == false) {
1663 char value[PROPERTY_VALUE_MAX];
1664 property_get("ro.audio.silent", value, "0");
1665 if (atoi(value)) {
1666 LOGD("Silence is golden");
1667 setMasterMute(true);
1668 }
1669 }
1670
1671 standbyTime = systemTime() + kStandbyTimeInNsecs;
1672 sleepTime = idleSleepTime;
1673 continue;
1674 }
1675 }
1676
1677 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1678
1679 // prevent any changes in effect chain list and in each effect chain
1680 // during mixing and effect process as the audio buffers could be deleted
1681 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001682 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683 }
1684
1685 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1686 // mix buffers...
1687 mAudioMixer->process();
1688 sleepTime = 0;
1689 standbyTime = systemTime() + kStandbyTimeInNsecs;
1690 //TODO: delay standby when effects have a tail
1691 } else {
1692 // If no tracks are ready, sleep once for the duration of an output
1693 // buffer size, then write 0s to the output
1694 if (sleepTime == 0) {
1695 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1696 sleepTime = activeSleepTime;
1697 } else {
1698 sleepTime = idleSleepTime;
1699 }
1700 } else if (mBytesWritten != 0 ||
1701 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1702 memset (mMixBuffer, 0, mixBufferSize);
1703 sleepTime = 0;
1704 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1705 }
1706 // TODO add standby time extension fct of effect tail
1707 }
1708
1709 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001710 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 }
1712 // sleepTime == 0 means we must write to audio hardware
1713 if (sleepTime == 0) {
1714 for (size_t i = 0; i < effectChains.size(); i ++) {
1715 effectChains[i]->process_l();
1716 }
1717 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001718 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719 mLastWriteTime = systemTime();
1720 mInWrite = true;
1721 mBytesWritten += mixBufferSize;
1722
Dima Zavin799a70e2011-04-18 16:57:27 -07001723 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001724 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1725 mNumWrites++;
1726 mInWrite = false;
1727 nsecs_t now = systemTime();
1728 nsecs_t delta = now - mLastWriteTime;
1729 if (delta > maxPeriod) {
1730 mNumDelayedWrites++;
1731 if ((now - lastWarning) > kWarningThrottle) {
1732 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1733 ns2ms(delta), mNumDelayedWrites, this);
1734 lastWarning = now;
1735 }
1736 if (mStandby) {
1737 longStandbyExit = true;
1738 }
1739 }
1740 mStandby = false;
1741 } else {
1742 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001743 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001744 usleep(sleepTime);
1745 }
1746
1747 // finally let go of all our tracks, without the lock held
1748 // since we can't guarantee the destructors won't acquire that
1749 // same lock.
1750 tracksToRemove.clear();
1751
1752 // Effect chains will be actually deleted here if they were removed from
1753 // mEffectChains list during mixing or effects processing
1754 effectChains.clear();
1755 }
1756
1757 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001758 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 }
1760
Eric Laurentfeb0db62011-07-22 09:04:31 -07001761 releaseWakeLock();
1762
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763 LOGV("MixerThread %p exiting", this);
1764 return false;
1765}
1766
1767// prepareTracks_l() must be called with ThreadBase::mLock held
1768uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1769{
1770
1771 uint32_t mixerStatus = MIXER_IDLE;
1772 // find out which tracks need to be processed
1773 size_t count = activeTracks.size();
1774 size_t mixedTracks = 0;
1775 size_t tracksWithEffect = 0;
1776
1777 float masterVolume = mMasterVolume;
1778 bool masterMute = mMasterMute;
1779
Eric Laurent571d49c2010-08-11 05:20:11 -07001780 if (masterMute) {
1781 masterVolume = 0;
1782 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07001784 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07001786 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07001787 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001788 masterVolume = (float)((v + (1 << 23)) >> 24);
1789 chain.clear();
1790 }
1791
1792 for (size_t i=0 ; i<count ; i++) {
1793 sp<Track> t = activeTracks[i].promote();
1794 if (t == 0) continue;
1795
1796 Track* const track = t.get();
1797 audio_track_cblk_t* cblk = track->cblk();
1798
1799 // The first time a track is added we wait
1800 // for all its buffers to be filled before processing it
1801 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07001802 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803 !track->isPaused() && !track->isTerminated())
1804 {
1805 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1806
1807 mixedTracks++;
1808
1809 // track->mainBuffer() != mMixBuffer means there is an effect chain
1810 // connected to the track
1811 chain.clear();
1812 if (track->mainBuffer() != mMixBuffer) {
1813 chain = getEffectChain_l(track->sessionId());
1814 // Delegate volume control to effect in track effect chain if needed
1815 if (chain != 0) {
1816 tracksWithEffect++;
1817 } else {
1818 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1819 track->name(), track->sessionId());
1820 }
1821 }
1822
1823
1824 int param = AudioMixer::VOLUME;
1825 if (track->mFillingUpStatus == Track::FS_FILLED) {
1826 // no ramp for the first volume setting
1827 track->mFillingUpStatus = Track::FS_ACTIVE;
1828 if (track->mState == TrackBase::RESUMING) {
1829 track->mState = TrackBase::ACTIVE;
1830 param = AudioMixer::RAMP_VOLUME;
1831 }
Eric Laurent243f5f92011-02-28 16:52:51 -08001832 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 } else if (cblk->server != 0) {
1834 // If the track is stopped before the first frame was mixed,
1835 // do not apply ramp
1836 param = AudioMixer::RAMP_VOLUME;
1837 }
1838
1839 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07001840 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07001841 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001843 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 if (track->isPausing()) {
1845 track->setPaused();
1846 }
1847 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001848
Mathias Agopian65ab4712010-07-14 17:59:35 -07001849 // read original volumes with volume control
1850 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001851 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07001852 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1853 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001854
Eric Laurente0aed6d2010-09-10 17:44:44 -07001855 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07001857 // Delegate volume control to effect in track effect chain if needed
1858 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1859 // Do not ramp volume if volume is controlled by effect
1860 param = AudioMixer::VOLUME;
1861 track->mHasVolumeController = true;
1862 } else {
1863 // force no volume ramp when volume controller was just disabled or removed
1864 // from effect chain to avoid volume spike
1865 if (track->mHasVolumeController) {
1866 param = AudioMixer::VOLUME;
1867 }
1868 track->mHasVolumeController = false;
1869 }
1870
1871 // Convert volumes from 8.24 to 4.12 format
1872 int16_t left, right, aux;
1873 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1874 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1875 left = int16_t(v_clamped);
1876 v_clamped = (vr + (1 << 11)) >> 12;
1877 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1878 right = int16_t(v_clamped);
1879
1880 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1881 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001882
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 // XXX: these things DON'T need to be done each time
1884 mAudioMixer->setBufferProvider(track);
1885 mAudioMixer->enable(AudioMixer::MIXING);
1886
1887 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1888 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1889 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
1890 mAudioMixer->setParameter(
1891 AudioMixer::TRACK,
1892 AudioMixer::FORMAT, (void *)track->format());
1893 mAudioMixer->setParameter(
1894 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001895 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001896 mAudioMixer->setParameter(
1897 AudioMixer::RESAMPLE,
1898 AudioMixer::SAMPLE_RATE,
1899 (void *)(cblk->sampleRate));
1900 mAudioMixer->setParameter(
1901 AudioMixer::TRACK,
1902 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1903 mAudioMixer->setParameter(
1904 AudioMixer::TRACK,
1905 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
1906
1907 // reset retry count
1908 track->mRetryCount = kMaxTrackRetries;
1909 mixerStatus = MIXER_TRACKS_READY;
1910 } else {
1911 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
1912 if (track->isStopped()) {
1913 track->reset();
1914 }
1915 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1916 // We have consumed all the buffers of this track.
1917 // Remove it from the list of active tracks.
1918 tracksToRemove->add(track);
1919 } else {
1920 // No buffers for this track. Give it a few chances to
1921 // fill a buffer, then remove it from active list.
1922 if (--(track->mRetryCount) <= 0) {
1923 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
1924 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07001925 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07001926 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 } else if (mixerStatus != MIXER_TRACKS_READY) {
1928 mixerStatus = MIXER_TRACKS_ENABLED;
1929 }
1930 }
1931 mAudioMixer->disable(AudioMixer::MIXING);
1932 }
1933 }
1934
1935 // remove all the tracks that need to be...
1936 count = tracksToRemove->size();
1937 if (UNLIKELY(count)) {
1938 for (size_t i=0 ; i<count ; i++) {
1939 const sp<Track>& track = tracksToRemove->itemAt(i);
1940 mActiveTracks.remove(track);
1941 if (track->mainBuffer() != mMixBuffer) {
1942 chain = getEffectChain_l(track->sessionId());
1943 if (chain != 0) {
1944 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001945 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 }
1947 }
1948 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07001949 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950 }
1951 }
1952 }
1953
1954 // mix buffer must be cleared if all tracks are connected to an
1955 // effect chain as in this case the mixer will not write to
1956 // mix buffer and track effects will accumulate into it
1957 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1958 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1959 }
1960
1961 return mixerStatus;
1962}
1963
1964void AudioFlinger::MixerThread::invalidateTracks(int streamType)
1965{
Eric Laurentde070132010-07-13 04:45:46 -07001966 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1967 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001969
Mathias Agopian65ab4712010-07-14 17:59:35 -07001970 size_t size = mTracks.size();
1971 for (size_t i = 0; i < size; i++) {
1972 sp<Track> t = mTracks[i];
1973 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07001974 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001975 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976 }
1977 }
1978}
1979
1980
1981// getTrackName_l() must be called with ThreadBase::mLock held
1982int AudioFlinger::MixerThread::getTrackName_l()
1983{
1984 return mAudioMixer->getTrackName();
1985}
1986
1987// deleteTrackName_l() must be called with ThreadBase::mLock held
1988void AudioFlinger::MixerThread::deleteTrackName_l(int name)
1989{
1990 LOGV("remove track (%d) and delete from mixer", name);
1991 mAudioMixer->deleteTrackName(name);
1992}
1993
1994// checkForNewParameters_l() must be called with ThreadBase::mLock held
1995bool AudioFlinger::MixerThread::checkForNewParameters_l()
1996{
1997 bool reconfig = false;
1998
1999 while (!mNewParameters.isEmpty()) {
2000 status_t status = NO_ERROR;
2001 String8 keyValuePair = mNewParameters[0];
2002 AudioParameter param = AudioParameter(keyValuePair);
2003 int value;
2004
2005 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2006 reconfig = true;
2007 }
2008 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002009 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002010 status = BAD_VALUE;
2011 } else {
2012 reconfig = true;
2013 }
2014 }
2015 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002016 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 status = BAD_VALUE;
2018 } else {
2019 reconfig = true;
2020 }
2021 }
2022 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2023 // do not accept frame count changes if tracks are open as the track buffer
2024 // size depends on frame count and correct behavior would not be garantied
2025 // if frame count is changed after track creation
2026 if (!mTracks.isEmpty()) {
2027 status = INVALID_OPERATION;
2028 } else {
2029 reconfig = true;
2030 }
2031 }
2032 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002033 // when changing the audio output device, call addBatteryData to notify
2034 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002035 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002036 uint32_t params = 0;
2037 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002038 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002039 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2040 }
2041
2042 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002043 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002044 // check if any other device (except speaker) is on
2045 if (value & deviceWithoutSpeaker ) {
2046 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2047 }
2048
2049 if (params != 0) {
2050 addBatteryData(params);
2051 }
2052 }
2053
Mathias Agopian65ab4712010-07-14 17:59:35 -07002054 // forward device change to effects that have requested to be
2055 // aware of attached audio device.
2056 mDevice = (uint32_t)value;
2057 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002058 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002059 }
2060 }
2061
2062 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002063 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002064 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002065 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002066 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 mStandby = true;
2068 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002069 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002070 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 }
2072 if (status == NO_ERROR && reconfig) {
2073 delete mAudioMixer;
2074 readOutputParameters();
2075 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2076 for (size_t i = 0; i < mTracks.size() ; i++) {
2077 int name = getTrackName_l();
2078 if (name < 0) break;
2079 mTracks[i]->mName = name;
2080 // limit track sample rate to 2 x new output sample rate
2081 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2082 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2083 }
2084 }
2085 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2086 }
2087 }
2088
2089 mNewParameters.removeAt(0);
2090
2091 mParamStatus = status;
2092 mParamCond.signal();
2093 mWaitWorkCV.wait(mLock);
2094 }
2095 return reconfig;
2096}
2097
2098status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2099{
2100 const size_t SIZE = 256;
2101 char buffer[SIZE];
2102 String8 result;
2103
2104 PlaybackThread::dumpInternals(fd, args);
2105
2106 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2107 result.append(buffer);
2108 write(fd, result.string(), result.size());
2109 return NO_ERROR;
2110}
2111
2112uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2113{
Dima Zavin799a70e2011-04-18 16:57:27 -07002114 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002115}
2116
2117uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2118{
Eric Laurent60e18242010-07-29 06:50:24 -07002119 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120}
2121
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002122uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2123{
2124 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2125}
2126
Mathias Agopian65ab4712010-07-14 17:59:35 -07002127// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002128AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129 : PlaybackThread(audioFlinger, output, id, device)
2130{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002131 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132}
2133
2134AudioFlinger::DirectOutputThread::~DirectOutputThread()
2135{
2136}
2137
2138
2139static inline int16_t clamp16(int32_t sample)
2140{
2141 if ((sample>>15) ^ (sample>>31))
2142 sample = 0x7FFF ^ (sample>>31);
2143 return sample;
2144}
2145
2146static inline
2147int32_t mul(int16_t in, int16_t v)
2148{
2149#if defined(__arm__) && !defined(__thumb__)
2150 int32_t out;
2151 asm( "smulbb %[out], %[in], %[v] \n"
2152 : [out]"=r"(out)
2153 : [in]"%r"(in), [v]"r"(v)
2154 : );
2155 return out;
2156#else
2157 return in * int32_t(v);
2158#endif
2159}
2160
2161void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2162{
2163 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002164 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 return;
2166 }
2167
2168 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002169 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002170 size_t count = mFrameCount * mChannelCount;
2171 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2172 int16_t *dst = mMixBuffer + count-1;
2173 while(count--) {
2174 *dst-- = (int16_t)(*src--^0x80) << 8;
2175 }
2176 }
2177
2178 size_t frameCount = mFrameCount;
2179 int16_t *out = mMixBuffer;
2180 if (ramp) {
2181 if (mChannelCount == 1) {
2182 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2183 int32_t vlInc = d / (int32_t)frameCount;
2184 int32_t vl = ((int32_t)mLeftVolShort << 16);
2185 do {
2186 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2187 out++;
2188 vl += vlInc;
2189 } while (--frameCount);
2190
2191 } else {
2192 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2193 int32_t vlInc = d / (int32_t)frameCount;
2194 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2195 int32_t vrInc = d / (int32_t)frameCount;
2196 int32_t vl = ((int32_t)mLeftVolShort << 16);
2197 int32_t vr = ((int32_t)mRightVolShort << 16);
2198 do {
2199 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2200 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2201 out += 2;
2202 vl += vlInc;
2203 vr += vrInc;
2204 } while (--frameCount);
2205 }
2206 } else {
2207 if (mChannelCount == 1) {
2208 do {
2209 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2210 out++;
2211 } while (--frameCount);
2212 } else {
2213 do {
2214 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2215 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2216 out += 2;
2217 } while (--frameCount);
2218 }
2219 }
2220
2221 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002222 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 size_t count = mFrameCount * mChannelCount;
2224 int16_t *src = mMixBuffer;
2225 uint8_t *dst = (uint8_t *)mMixBuffer;
2226 while(count--) {
2227 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2228 }
2229 }
2230
2231 mLeftVolShort = leftVol;
2232 mRightVolShort = rightVol;
2233}
2234
2235bool AudioFlinger::DirectOutputThread::threadLoop()
2236{
2237 uint32_t mixerStatus = MIXER_IDLE;
2238 sp<Track> trackToRemove;
2239 sp<Track> activeTrack;
2240 nsecs_t standbyTime = systemTime();
2241 int8_t *curBuf;
2242 size_t mixBufferSize = mFrameCount*mFrameSize;
2243 uint32_t activeSleepTime = activeSleepTimeUs();
2244 uint32_t idleSleepTime = idleSleepTimeUs();
2245 uint32_t sleepTime = idleSleepTime;
2246 // use shorter standby delay as on normal output to release
2247 // hardware resources as soon as possible
2248 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2249
Eric Laurentfeb0db62011-07-22 09:04:31 -07002250 acquireWakeLock();
2251
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 while (!exitPending())
2253 {
2254 bool rampVolume;
2255 uint16_t leftVol;
2256 uint16_t rightVol;
2257 Vector< sp<EffectChain> > effectChains;
2258
2259 processConfigEvents();
2260
2261 mixerStatus = MIXER_IDLE;
2262
2263 { // scope for the mLock
2264
2265 Mutex::Autolock _l(mLock);
2266
2267 if (checkForNewParameters_l()) {
2268 mixBufferSize = mFrameCount*mFrameSize;
2269 activeSleepTime = activeSleepTimeUs();
2270 idleSleepTime = idleSleepTimeUs();
2271 standbyDelay = microseconds(activeSleepTime*2);
2272 }
2273
2274 // put audio hardware into standby after short delay
2275 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2276 mSuspended) {
2277 // wait until we have something to do...
2278 if (!mStandby) {
2279 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002280 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 mStandby = true;
2282 mBytesWritten = 0;
2283 }
2284
2285 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2286 // we're about to wait, flush the binder command buffer
2287 IPCThreadState::self()->flushCommands();
2288
2289 if (exitPending()) break;
2290
Eric Laurentfeb0db62011-07-22 09:04:31 -07002291 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002292 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2293 mWaitWorkCV.wait(mLock);
2294 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002295 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296
2297 if (mMasterMute == false) {
2298 char value[PROPERTY_VALUE_MAX];
2299 property_get("ro.audio.silent", value, "0");
2300 if (atoi(value)) {
2301 LOGD("Silence is golden");
2302 setMasterMute(true);
2303 }
2304 }
2305
2306 standbyTime = systemTime() + standbyDelay;
2307 sleepTime = idleSleepTime;
2308 continue;
2309 }
2310 }
2311
2312 effectChains = mEffectChains;
2313
2314 // find out which tracks need to be processed
2315 if (mActiveTracks.size() != 0) {
2316 sp<Track> t = mActiveTracks[0].promote();
2317 if (t == 0) continue;
2318
2319 Track* const track = t.get();
2320 audio_track_cblk_t* cblk = track->cblk();
2321
2322 // The first time a track is added we wait
2323 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002324 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002325 !track->isPaused() && !track->isTerminated())
2326 {
2327 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2328
2329 if (track->mFillingUpStatus == Track::FS_FILLED) {
2330 track->mFillingUpStatus = Track::FS_ACTIVE;
2331 mLeftVolFloat = mRightVolFloat = 0;
2332 mLeftVolShort = mRightVolShort = 0;
2333 if (track->mState == TrackBase::RESUMING) {
2334 track->mState = TrackBase::ACTIVE;
2335 rampVolume = true;
2336 }
2337 } else if (cblk->server != 0) {
2338 // If the track is stopped before the first frame was mixed,
2339 // do not apply ramp
2340 rampVolume = true;
2341 }
2342 // compute volume for this track
2343 float left, right;
2344 if (track->isMuted() || mMasterMute || track->isPausing() ||
2345 mStreamTypes[track->type()].mute) {
2346 left = right = 0;
2347 if (track->isPausing()) {
2348 track->setPaused();
2349 }
2350 } else {
2351 float typeVolume = mStreamTypes[track->type()].volume;
2352 float v = mMasterVolume * typeVolume;
2353 float v_clamped = v * cblk->volume[0];
2354 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2355 left = v_clamped/MAX_GAIN;
2356 v_clamped = v * cblk->volume[1];
2357 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2358 right = v_clamped/MAX_GAIN;
2359 }
2360
2361 if (left != mLeftVolFloat || right != mRightVolFloat) {
2362 mLeftVolFloat = left;
2363 mRightVolFloat = right;
2364
2365 // If audio HAL implements volume control,
2366 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002367 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002368 left = 1.0f;
2369 right = 1.0f;
2370 }
2371
2372 // Convert volumes from float to 8.24
2373 uint32_t vl = (uint32_t)(left * (1 << 24));
2374 uint32_t vr = (uint32_t)(right * (1 << 24));
2375
2376 // Delegate volume control to effect in track effect chain if needed
2377 // only one effect chain can be present on DirectOutputThread, so if
2378 // there is one, the track is connected to it
2379 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002380 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002381 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002382 rampVolume = false;
2383 }
2384 }
2385
2386 // Convert volumes from 8.24 to 4.12 format
2387 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2388 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2389 leftVol = (uint16_t)v_clamped;
2390 v_clamped = (vr + (1 << 11)) >> 12;
2391 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2392 rightVol = (uint16_t)v_clamped;
2393 } else {
2394 leftVol = mLeftVolShort;
2395 rightVol = mRightVolShort;
2396 rampVolume = false;
2397 }
2398
2399 // reset retry count
2400 track->mRetryCount = kMaxTrackRetriesDirect;
2401 activeTrack = t;
2402 mixerStatus = MIXER_TRACKS_READY;
2403 } else {
2404 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2405 if (track->isStopped()) {
2406 track->reset();
2407 }
2408 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2409 // We have consumed all the buffers of this track.
2410 // Remove it from the list of active tracks.
2411 trackToRemove = track;
2412 } else {
2413 // No buffers for this track. Give it a few chances to
2414 // fill a buffer, then remove it from active list.
2415 if (--(track->mRetryCount) <= 0) {
2416 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2417 trackToRemove = track;
2418 } else {
2419 mixerStatus = MIXER_TRACKS_ENABLED;
2420 }
2421 }
2422 }
2423 }
2424
2425 // remove all the tracks that need to be...
2426 if (UNLIKELY(trackToRemove != 0)) {
2427 mActiveTracks.remove(trackToRemove);
2428 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002429 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2430 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002431 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002434 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 }
2436 }
2437
Eric Laurentde070132010-07-13 04:45:46 -07002438 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002439 }
2440
2441 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2442 AudioBufferProvider::Buffer buffer;
2443 size_t frameCount = mFrameCount;
2444 curBuf = (int8_t *)mMixBuffer;
2445 // output audio to hardware
2446 while (frameCount) {
2447 buffer.frameCount = frameCount;
2448 activeTrack->getNextBuffer(&buffer);
2449 if (UNLIKELY(buffer.raw == 0)) {
2450 memset(curBuf, 0, frameCount * mFrameSize);
2451 break;
2452 }
2453 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2454 frameCount -= buffer.frameCount;
2455 curBuf += buffer.frameCount * mFrameSize;
2456 activeTrack->releaseBuffer(&buffer);
2457 }
2458 sleepTime = 0;
2459 standbyTime = systemTime() + standbyDelay;
2460 } else {
2461 if (sleepTime == 0) {
2462 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2463 sleepTime = activeSleepTime;
2464 } else {
2465 sleepTime = idleSleepTime;
2466 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002467 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2469 sleepTime = 0;
2470 }
2471 }
2472
2473 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002474 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002475 }
2476 // sleepTime == 0 means we must write to audio hardware
2477 if (sleepTime == 0) {
2478 if (mixerStatus == MIXER_TRACKS_READY) {
2479 applyVolume(leftVol, rightVol, rampVolume);
2480 }
2481 for (size_t i = 0; i < effectChains.size(); i ++) {
2482 effectChains[i]->process_l();
2483 }
Eric Laurentde070132010-07-13 04:45:46 -07002484 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002485
2486 mLastWriteTime = systemTime();
2487 mInWrite = true;
2488 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002489 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2491 mNumWrites++;
2492 mInWrite = false;
2493 mStandby = false;
2494 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002495 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002496 usleep(sleepTime);
2497 }
2498
2499 // finally let go of removed track, without the lock held
2500 // since we can't guarantee the destructors won't acquire that
2501 // same lock.
2502 trackToRemove.clear();
2503 activeTrack.clear();
2504
2505 // Effect chains will be actually deleted here if they were removed from
2506 // mEffectChains list during mixing or effects processing
2507 effectChains.clear();
2508 }
2509
2510 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002511 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002512 }
2513
Eric Laurentfeb0db62011-07-22 09:04:31 -07002514 releaseWakeLock();
2515
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 LOGV("DirectOutputThread %p exiting", this);
2517 return false;
2518}
2519
2520// getTrackName_l() must be called with ThreadBase::mLock held
2521int AudioFlinger::DirectOutputThread::getTrackName_l()
2522{
2523 return 0;
2524}
2525
2526// deleteTrackName_l() must be called with ThreadBase::mLock held
2527void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2528{
2529}
2530
2531// checkForNewParameters_l() must be called with ThreadBase::mLock held
2532bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2533{
2534 bool reconfig = false;
2535
2536 while (!mNewParameters.isEmpty()) {
2537 status_t status = NO_ERROR;
2538 String8 keyValuePair = mNewParameters[0];
2539 AudioParameter param = AudioParameter(keyValuePair);
2540 int value;
2541
2542 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2543 // do not accept frame count changes if tracks are open as the track buffer
2544 // size depends on frame count and correct behavior would not be garantied
2545 // if frame count is changed after track creation
2546 if (!mTracks.isEmpty()) {
2547 status = INVALID_OPERATION;
2548 } else {
2549 reconfig = true;
2550 }
2551 }
2552 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002553 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002554 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002555 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002556 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002557 mStandby = true;
2558 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002559 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002560 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002561 }
2562 if (status == NO_ERROR && reconfig) {
2563 readOutputParameters();
2564 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2565 }
2566 }
2567
2568 mNewParameters.removeAt(0);
2569
2570 mParamStatus = status;
2571 mParamCond.signal();
2572 mWaitWorkCV.wait(mLock);
2573 }
2574 return reconfig;
2575}
2576
2577uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2578{
2579 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002580 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002581 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002582 } else {
2583 time = 10000;
2584 }
2585 return time;
2586}
2587
2588uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2589{
2590 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002591 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002592 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002593 } else {
2594 time = 10000;
2595 }
2596 return time;
2597}
2598
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002599uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2600{
2601 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002602 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002603 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2604 } else {
2605 time = 10000;
2606 }
2607 return time;
2608}
2609
2610
Mathias Agopian65ab4712010-07-14 17:59:35 -07002611// ----------------------------------------------------------------------------
2612
2613AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2614 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2615{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002616 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 addOutputTrack(mainThread);
2618}
2619
2620AudioFlinger::DuplicatingThread::~DuplicatingThread()
2621{
2622 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2623 mOutputTracks[i]->destroy();
2624 }
2625 mOutputTracks.clear();
2626}
2627
2628bool AudioFlinger::DuplicatingThread::threadLoop()
2629{
2630 Vector< sp<Track> > tracksToRemove;
2631 uint32_t mixerStatus = MIXER_IDLE;
2632 nsecs_t standbyTime = systemTime();
2633 size_t mixBufferSize = mFrameCount*mFrameSize;
2634 SortedVector< sp<OutputTrack> > outputTracks;
2635 uint32_t writeFrames = 0;
2636 uint32_t activeSleepTime = activeSleepTimeUs();
2637 uint32_t idleSleepTime = idleSleepTimeUs();
2638 uint32_t sleepTime = idleSleepTime;
2639 Vector< sp<EffectChain> > effectChains;
2640
Eric Laurentfeb0db62011-07-22 09:04:31 -07002641 acquireWakeLock();
2642
Mathias Agopian65ab4712010-07-14 17:59:35 -07002643 while (!exitPending())
2644 {
2645 processConfigEvents();
2646
2647 mixerStatus = MIXER_IDLE;
2648 { // scope for the mLock
2649
2650 Mutex::Autolock _l(mLock);
2651
2652 if (checkForNewParameters_l()) {
2653 mixBufferSize = mFrameCount*mFrameSize;
2654 updateWaitTime();
2655 activeSleepTime = activeSleepTimeUs();
2656 idleSleepTime = idleSleepTimeUs();
2657 }
2658
2659 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2660
2661 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2662 outputTracks.add(mOutputTracks[i]);
2663 }
2664
2665 // put audio hardware into standby after short delay
2666 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2667 mSuspended) {
2668 if (!mStandby) {
2669 for (size_t i = 0; i < outputTracks.size(); i++) {
2670 outputTracks[i]->stop();
2671 }
2672 mStandby = true;
2673 mBytesWritten = 0;
2674 }
2675
2676 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2677 // we're about to wait, flush the binder command buffer
2678 IPCThreadState::self()->flushCommands();
2679 outputTracks.clear();
2680
2681 if (exitPending()) break;
2682
Eric Laurentfeb0db62011-07-22 09:04:31 -07002683 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002684 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2685 mWaitWorkCV.wait(mLock);
2686 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002687 acquireWakeLock_l();
2688
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 if (mMasterMute == false) {
2690 char value[PROPERTY_VALUE_MAX];
2691 property_get("ro.audio.silent", value, "0");
2692 if (atoi(value)) {
2693 LOGD("Silence is golden");
2694 setMasterMute(true);
2695 }
2696 }
2697
2698 standbyTime = systemTime() + kStandbyTimeInNsecs;
2699 sleepTime = idleSleepTime;
2700 continue;
2701 }
2702 }
2703
2704 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2705
2706 // prevent any changes in effect chain list and in each effect chain
2707 // during mixing and effect process as the audio buffers could be deleted
2708 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002709 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 }
2711
2712 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2713 // mix buffers...
2714 if (outputsReady(outputTracks)) {
2715 mAudioMixer->process();
2716 } else {
2717 memset(mMixBuffer, 0, mixBufferSize);
2718 }
2719 sleepTime = 0;
2720 writeFrames = mFrameCount;
2721 } else {
2722 if (sleepTime == 0) {
2723 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2724 sleepTime = activeSleepTime;
2725 } else {
2726 sleepTime = idleSleepTime;
2727 }
2728 } else if (mBytesWritten != 0) {
2729 // flush remaining overflow buffers in output tracks
2730 for (size_t i = 0; i < outputTracks.size(); i++) {
2731 if (outputTracks[i]->isActive()) {
2732 sleepTime = 0;
2733 writeFrames = 0;
2734 memset(mMixBuffer, 0, mixBufferSize);
2735 break;
2736 }
2737 }
2738 }
2739 }
2740
2741 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002742 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002743 }
2744 // sleepTime == 0 means we must write to audio hardware
2745 if (sleepTime == 0) {
2746 for (size_t i = 0; i < effectChains.size(); i ++) {
2747 effectChains[i]->process_l();
2748 }
2749 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002750 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751
2752 standbyTime = systemTime() + kStandbyTimeInNsecs;
2753 for (size_t i = 0; i < outputTracks.size(); i++) {
2754 outputTracks[i]->write(mMixBuffer, writeFrames);
2755 }
2756 mStandby = false;
2757 mBytesWritten += mixBufferSize;
2758 } else {
2759 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002760 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 usleep(sleepTime);
2762 }
2763
2764 // finally let go of all our tracks, without the lock held
2765 // since we can't guarantee the destructors won't acquire that
2766 // same lock.
2767 tracksToRemove.clear();
2768 outputTracks.clear();
2769
2770 // Effect chains will be actually deleted here if they were removed from
2771 // mEffectChains list during mixing or effects processing
2772 effectChains.clear();
2773 }
2774
Eric Laurentfeb0db62011-07-22 09:04:31 -07002775 releaseWakeLock();
2776
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 return false;
2778}
2779
2780void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2781{
2782 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2783 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2784 this,
2785 mSampleRate,
2786 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002787 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002788 frameCount);
2789 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002790 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002791 mOutputTracks.add(outputTrack);
2792 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2793 updateWaitTime();
2794 }
2795}
2796
2797void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2798{
2799 Mutex::Autolock _l(mLock);
2800 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2801 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2802 mOutputTracks[i]->destroy();
2803 mOutputTracks.removeAt(i);
2804 updateWaitTime();
2805 return;
2806 }
2807 }
2808 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2809}
2810
2811void AudioFlinger::DuplicatingThread::updateWaitTime()
2812{
2813 mWaitTimeMs = UINT_MAX;
2814 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2815 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2816 if (strong != NULL) {
2817 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2818 if (waitTimeMs < mWaitTimeMs) {
2819 mWaitTimeMs = waitTimeMs;
2820 }
2821 }
2822 }
2823}
2824
2825
2826bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2827{
2828 for (size_t i = 0; i < outputTracks.size(); i++) {
2829 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2830 if (thread == 0) {
2831 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2832 return false;
2833 }
2834 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2835 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2836 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2837 return false;
2838 }
2839 }
2840 return true;
2841}
2842
2843uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2844{
2845 return (mWaitTimeMs * 1000) / 2;
2846}
2847
2848// ----------------------------------------------------------------------------
2849
2850// TrackBase constructor must be called with AudioFlinger::mLock held
2851AudioFlinger::ThreadBase::TrackBase::TrackBase(
2852 const wp<ThreadBase>& thread,
2853 const sp<Client>& client,
2854 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002855 uint32_t format,
2856 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857 int frameCount,
2858 uint32_t flags,
2859 const sp<IMemory>& sharedBuffer,
2860 int sessionId)
2861 : RefBase(),
2862 mThread(thread),
2863 mClient(client),
2864 mCblk(0),
2865 mFrameCount(0),
2866 mState(IDLE),
2867 mClientTid(-1),
2868 mFormat(format),
2869 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2870 mSessionId(sessionId)
2871{
2872 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2873
2874 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
2875 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002876 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2878 if (sharedBuffer == 0) {
2879 size += bufferSize;
2880 }
2881
2882 if (client != NULL) {
2883 mCblkMemory = client->heap()->allocate(size);
2884 if (mCblkMemory != 0) {
2885 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2886 if (mCblk) { // construct the shared structure in-place.
2887 new(mCblk) audio_track_cblk_t();
2888 // clear all buffers
2889 mCblk->frameCount = frameCount;
2890 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002891 mChannelCount = channelCount;
2892 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893 if (sharedBuffer == 0) {
2894 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2895 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2896 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002897 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 mCblk->flags = CBLK_UNDERRUN_ON;
2899 } else {
2900 mBuffer = sharedBuffer->pointer();
2901 }
2902 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2903 }
2904 } else {
2905 LOGE("not enough memory for AudioTrack size=%u", size);
2906 client->heap()->dump("AudioTrack");
2907 return;
2908 }
2909 } else {
2910 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2911 if (mCblk) { // construct the shared structure in-place.
2912 new(mCblk) audio_track_cblk_t();
2913 // clear all buffers
2914 mCblk->frameCount = frameCount;
2915 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002916 mChannelCount = channelCount;
2917 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002918 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2919 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2920 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002921 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922 mCblk->flags = CBLK_UNDERRUN_ON;
2923 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2924 }
2925 }
2926}
2927
2928AudioFlinger::ThreadBase::TrackBase::~TrackBase()
2929{
2930 if (mCblk) {
2931 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2932 if (mClient == NULL) {
2933 delete mCblk;
2934 }
2935 }
2936 mCblkMemory.clear(); // and free the shared memory
2937 if (mClient != NULL) {
2938 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2939 mClient.clear();
2940 }
2941}
2942
2943void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2944{
2945 buffer->raw = 0;
2946 mFrameCount = buffer->frameCount;
2947 step();
2948 buffer->frameCount = 0;
2949}
2950
2951bool AudioFlinger::ThreadBase::TrackBase::step() {
2952 bool result;
2953 audio_track_cblk_t* cblk = this->cblk();
2954
2955 result = cblk->stepServer(mFrameCount);
2956 if (!result) {
2957 LOGV("stepServer failed acquiring cblk mutex");
2958 mFlags |= STEPSERVER_FAILED;
2959 }
2960 return result;
2961}
2962
2963void AudioFlinger::ThreadBase::TrackBase::reset() {
2964 audio_track_cblk_t* cblk = this->cblk();
2965
2966 cblk->user = 0;
2967 cblk->server = 0;
2968 cblk->userBase = 0;
2969 cblk->serverBase = 0;
2970 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
2971 LOGV("TrackBase::reset");
2972}
2973
2974sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
2975{
2976 return mCblkMemory;
2977}
2978
2979int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
2980 return (int)mCblk->sampleRate;
2981}
2982
2983int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002984 return (const int)mChannelCount;
2985}
2986
2987uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
2988 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002989}
2990
2991void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
2992 audio_track_cblk_t* cblk = this->cblk();
2993 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2994 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
2995
2996 // Check validity of returned pointer in case the track control block would have been corrupted.
2997 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2998 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
2999 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003000 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003001 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003002 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003 return 0;
3004 }
3005
3006 return bufferStart;
3007}
3008
3009// ----------------------------------------------------------------------------
3010
3011// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3012AudioFlinger::PlaybackThread::Track::Track(
3013 const wp<ThreadBase>& thread,
3014 const sp<Client>& client,
3015 int streamType,
3016 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003017 uint32_t format,
3018 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 int frameCount,
3020 const sp<IMemory>& sharedBuffer,
3021 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003022 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003023 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3024 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003025{
3026 if (mCblk != NULL) {
3027 sp<ThreadBase> baseThread = thread.promote();
3028 if (baseThread != 0) {
3029 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3030 mName = playbackThread->getTrackName_l();
3031 mMainBuffer = playbackThread->mixBuffer();
3032 }
3033 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3034 if (mName < 0) {
3035 LOGE("no more track names available");
3036 }
3037 mVolume[0] = 1.0f;
3038 mVolume[1] = 1.0f;
3039 mStreamType = streamType;
3040 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3041 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003042 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043 }
3044}
3045
3046AudioFlinger::PlaybackThread::Track::~Track()
3047{
3048 LOGV("PlaybackThread::Track destructor");
3049 sp<ThreadBase> thread = mThread.promote();
3050 if (thread != 0) {
3051 Mutex::Autolock _l(thread->mLock);
3052 mState = TERMINATED;
3053 }
3054}
3055
3056void AudioFlinger::PlaybackThread::Track::destroy()
3057{
3058 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3059 // by removing it from mTracks vector, so there is a risk that this Tracks's
3060 // desctructor is called. As the destructor needs to lock mLock,
3061 // we must acquire a strong reference on this Track before locking mLock
3062 // here so that the destructor is called only when exiting this function.
3063 // On the other hand, as long as Track::destroy() is only called by
3064 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3065 // this Track with its member mTrack.
3066 sp<Track> keep(this);
3067 { // scope for mLock
3068 sp<ThreadBase> thread = mThread.promote();
3069 if (thread != 0) {
3070 if (!isOutputTrack()) {
3071 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003072 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003073 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003074 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003075
3076 // to track the speaker usage
3077 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078 }
3079 AudioSystem::releaseOutput(thread->id());
3080 }
3081 Mutex::Autolock _l(thread->mLock);
3082 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3083 playbackThread->destroyTrack_l(this);
3084 }
3085 }
3086}
3087
3088void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3089{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003090 snprintf(buffer, size, " %05d %05d %03u %03u 0x%08x %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 mName - AudioMixer::TRACK0,
3092 (mClient == NULL) ? getpid() : mClient->pid(),
3093 mStreamType,
3094 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003095 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003096 mSessionId,
3097 mFrameCount,
3098 mState,
3099 mMute,
3100 mFillingUpStatus,
3101 mCblk->sampleRate,
3102 mCblk->volume[0],
3103 mCblk->volume[1],
3104 mCblk->server,
3105 mCblk->user,
3106 (int)mMainBuffer,
3107 (int)mAuxBuffer);
3108}
3109
3110status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3111{
3112 audio_track_cblk_t* cblk = this->cblk();
3113 uint32_t framesReady;
3114 uint32_t framesReq = buffer->frameCount;
3115
3116 // Check if last stepServer failed, try to step now
3117 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3118 if (!step()) goto getNextBuffer_exit;
3119 LOGV("stepServer recovered");
3120 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3121 }
3122
3123 framesReady = cblk->framesReady();
3124
3125 if (LIKELY(framesReady)) {
3126 uint32_t s = cblk->server;
3127 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3128
3129 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3130 if (framesReq > framesReady) {
3131 framesReq = framesReady;
3132 }
3133 if (s + framesReq > bufferEnd) {
3134 framesReq = bufferEnd - s;
3135 }
3136
3137 buffer->raw = getBuffer(s, framesReq);
3138 if (buffer->raw == 0) goto getNextBuffer_exit;
3139
3140 buffer->frameCount = framesReq;
3141 return NO_ERROR;
3142 }
3143
3144getNextBuffer_exit:
3145 buffer->raw = 0;
3146 buffer->frameCount = 0;
3147 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3148 return NOT_ENOUGH_DATA;
3149}
3150
3151bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003152 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153
3154 if (mCblk->framesReady() >= mCblk->frameCount ||
3155 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3156 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003157 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003158 return true;
3159 }
3160 return false;
3161}
3162
3163status_t AudioFlinger::PlaybackThread::Track::start()
3164{
3165 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003166 LOGV("start(%d), calling thread %d session %d",
3167 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003168 sp<ThreadBase> thread = mThread.promote();
3169 if (thread != 0) {
3170 Mutex::Autolock _l(thread->mLock);
3171 int state = mState;
3172 // here the track could be either new, or restarted
3173 // in both cases "unstop" the track
3174 if (mState == PAUSED) {
3175 mState = TrackBase::RESUMING;
3176 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3177 } else {
3178 mState = TrackBase::ACTIVE;
3179 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3180 }
3181
3182 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3183 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003184 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003185 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003186 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003188
3189 // to track the speaker usage
3190 if (status == NO_ERROR) {
3191 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 }
3194 if (status == NO_ERROR) {
3195 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3196 playbackThread->addTrack_l(this);
3197 } else {
3198 mState = state;
3199 }
3200 } else {
3201 status = BAD_VALUE;
3202 }
3203 return status;
3204}
3205
3206void AudioFlinger::PlaybackThread::Track::stop()
3207{
3208 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3209 sp<ThreadBase> thread = mThread.promote();
3210 if (thread != 0) {
3211 Mutex::Autolock _l(thread->mLock);
3212 int state = mState;
3213 if (mState > STOPPED) {
3214 mState = STOPPED;
3215 // If the track is not active (PAUSED and buffers full), flush buffers
3216 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3217 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3218 reset();
3219 }
3220 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3221 }
3222 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3223 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003224 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003225 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003226 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003227 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003228
3229 // to track the speaker usage
3230 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 }
3232 }
3233}
3234
3235void AudioFlinger::PlaybackThread::Track::pause()
3236{
3237 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3238 sp<ThreadBase> thread = mThread.promote();
3239 if (thread != 0) {
3240 Mutex::Autolock _l(thread->mLock);
3241 if (mState == ACTIVE || mState == RESUMING) {
3242 mState = PAUSING;
3243 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3244 if (!isOutputTrack()) {
3245 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003246 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003247 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003248 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003250
3251 // to track the speaker usage
3252 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 }
3254 }
3255 }
3256}
3257
3258void AudioFlinger::PlaybackThread::Track::flush()
3259{
3260 LOGV("flush(%d)", mName);
3261 sp<ThreadBase> thread = mThread.promote();
3262 if (thread != 0) {
3263 Mutex::Autolock _l(thread->mLock);
3264 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3265 return;
3266 }
3267 // No point remaining in PAUSED state after a flush => go to
3268 // STOPPED state
3269 mState = STOPPED;
3270
Eric Laurent38ccae22011-03-28 18:37:07 -07003271 // do not reset the track if it is still in the process of being stopped or paused.
3272 // this will be done by prepareTracks_l() when the track is stopped.
3273 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3274 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3275 reset();
3276 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003277 }
3278}
3279
3280void AudioFlinger::PlaybackThread::Track::reset()
3281{
3282 // Do not reset twice to avoid discarding data written just after a flush and before
3283 // the audioflinger thread detects the track is stopped.
3284 if (!mResetDone) {
3285 TrackBase::reset();
3286 // Force underrun condition to avoid false underrun callback until first data is
3287 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003288 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3289 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003290 mFillingUpStatus = FS_FILLING;
3291 mResetDone = true;
3292 }
3293}
3294
3295void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3296{
3297 mMute = muted;
3298}
3299
3300void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3301{
3302 mVolume[0] = left;
3303 mVolume[1] = right;
3304}
3305
3306status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3307{
3308 status_t status = DEAD_OBJECT;
3309 sp<ThreadBase> thread = mThread.promote();
3310 if (thread != 0) {
3311 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3312 status = playbackThread->attachAuxEffect(this, EffectId);
3313 }
3314 return status;
3315}
3316
3317void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3318{
3319 mAuxEffectId = EffectId;
3320 mAuxBuffer = buffer;
3321}
3322
3323// ----------------------------------------------------------------------------
3324
3325// RecordTrack constructor must be called with AudioFlinger::mLock held
3326AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3327 const wp<ThreadBase>& thread,
3328 const sp<Client>& client,
3329 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003330 uint32_t format,
3331 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 int frameCount,
3333 uint32_t flags,
3334 int sessionId)
3335 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003336 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003337 mOverflow(false)
3338{
3339 if (mCblk != NULL) {
3340 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003341 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003342 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003343 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003344 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003345 } else {
3346 mCblk->frameSize = sizeof(int8_t);
3347 }
3348 }
3349}
3350
3351AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3352{
3353 sp<ThreadBase> thread = mThread.promote();
3354 if (thread != 0) {
3355 AudioSystem::releaseInput(thread->id());
3356 }
3357}
3358
3359status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3360{
3361 audio_track_cblk_t* cblk = this->cblk();
3362 uint32_t framesAvail;
3363 uint32_t framesReq = buffer->frameCount;
3364
3365 // Check if last stepServer failed, try to step now
3366 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3367 if (!step()) goto getNextBuffer_exit;
3368 LOGV("stepServer recovered");
3369 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3370 }
3371
3372 framesAvail = cblk->framesAvailable_l();
3373
3374 if (LIKELY(framesAvail)) {
3375 uint32_t s = cblk->server;
3376 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3377
3378 if (framesReq > framesAvail) {
3379 framesReq = framesAvail;
3380 }
3381 if (s + framesReq > bufferEnd) {
3382 framesReq = bufferEnd - s;
3383 }
3384
3385 buffer->raw = getBuffer(s, framesReq);
3386 if (buffer->raw == 0) goto getNextBuffer_exit;
3387
3388 buffer->frameCount = framesReq;
3389 return NO_ERROR;
3390 }
3391
3392getNextBuffer_exit:
3393 buffer->raw = 0;
3394 buffer->frameCount = 0;
3395 return NOT_ENOUGH_DATA;
3396}
3397
3398status_t AudioFlinger::RecordThread::RecordTrack::start()
3399{
3400 sp<ThreadBase> thread = mThread.promote();
3401 if (thread != 0) {
3402 RecordThread *recordThread = (RecordThread *)thread.get();
3403 return recordThread->start(this);
3404 } else {
3405 return BAD_VALUE;
3406 }
3407}
3408
3409void AudioFlinger::RecordThread::RecordTrack::stop()
3410{
3411 sp<ThreadBase> thread = mThread.promote();
3412 if (thread != 0) {
3413 RecordThread *recordThread = (RecordThread *)thread.get();
3414 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003415 TrackBase::reset();
3416 // Force overerrun condition to avoid false overrun callback until first data is
3417 // read from buffer
3418 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003419 }
3420}
3421
3422void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3423{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003424 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 (mClient == NULL) ? getpid() : mClient->pid(),
3426 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003427 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003428 mSessionId,
3429 mFrameCount,
3430 mState,
3431 mCblk->sampleRate,
3432 mCblk->server,
3433 mCblk->user);
3434}
3435
3436
3437// ----------------------------------------------------------------------------
3438
3439AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3440 const wp<ThreadBase>& thread,
3441 DuplicatingThread *sourceThread,
3442 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003443 uint32_t format,
3444 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003445 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003446 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 mActive(false), mSourceThread(sourceThread)
3448{
3449
3450 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3451 if (mCblk != NULL) {
3452 mCblk->flags |= CBLK_DIRECTION_OUT;
3453 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3454 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3455 mOutBuffer.frameCount = 0;
3456 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003457 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3458 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3459 mCblk, mBuffer, mCblk->buffers,
3460 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003461 } else {
3462 LOGW("Error creating output track on thread %p", playbackThread);
3463 }
3464}
3465
3466AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3467{
3468 clearBufferQueue();
3469}
3470
3471status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3472{
3473 status_t status = Track::start();
3474 if (status != NO_ERROR) {
3475 return status;
3476 }
3477
3478 mActive = true;
3479 mRetryCount = 127;
3480 return status;
3481}
3482
3483void AudioFlinger::PlaybackThread::OutputTrack::stop()
3484{
3485 Track::stop();
3486 clearBufferQueue();
3487 mOutBuffer.frameCount = 0;
3488 mActive = false;
3489}
3490
3491bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3492{
3493 Buffer *pInBuffer;
3494 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003495 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003496 bool outputBufferFull = false;
3497 inBuffer.frameCount = frames;
3498 inBuffer.i16 = data;
3499
3500 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3501
3502 if (!mActive && frames != 0) {
3503 start();
3504 sp<ThreadBase> thread = mThread.promote();
3505 if (thread != 0) {
3506 MixerThread *mixerThread = (MixerThread *)thread.get();
3507 if (mCblk->frameCount > frames){
3508 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3509 uint32_t startFrames = (mCblk->frameCount - frames);
3510 pInBuffer = new Buffer;
3511 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3512 pInBuffer->frameCount = startFrames;
3513 pInBuffer->i16 = pInBuffer->mBuffer;
3514 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3515 mBufferQueue.add(pInBuffer);
3516 } else {
3517 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3518 }
3519 }
3520 }
3521 }
3522
3523 while (waitTimeLeftMs) {
3524 // First write pending buffers, then new data
3525 if (mBufferQueue.size()) {
3526 pInBuffer = mBufferQueue.itemAt(0);
3527 } else {
3528 pInBuffer = &inBuffer;
3529 }
3530
3531 if (pInBuffer->frameCount == 0) {
3532 break;
3533 }
3534
3535 if (mOutBuffer.frameCount == 0) {
3536 mOutBuffer.frameCount = pInBuffer->frameCount;
3537 nsecs_t startTime = systemTime();
3538 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3539 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3540 outputBufferFull = true;
3541 break;
3542 }
3543 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3544 if (waitTimeLeftMs >= waitTimeMs) {
3545 waitTimeLeftMs -= waitTimeMs;
3546 } else {
3547 waitTimeLeftMs = 0;
3548 }
3549 }
3550
3551 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3552 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3553 mCblk->stepUser(outFrames);
3554 pInBuffer->frameCount -= outFrames;
3555 pInBuffer->i16 += outFrames * channelCount;
3556 mOutBuffer.frameCount -= outFrames;
3557 mOutBuffer.i16 += outFrames * channelCount;
3558
3559 if (pInBuffer->frameCount == 0) {
3560 if (mBufferQueue.size()) {
3561 mBufferQueue.removeAt(0);
3562 delete [] pInBuffer->mBuffer;
3563 delete pInBuffer;
3564 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3565 } else {
3566 break;
3567 }
3568 }
3569 }
3570
3571 // If we could not write all frames, allocate a buffer and queue it for next time.
3572 if (inBuffer.frameCount) {
3573 sp<ThreadBase> thread = mThread.promote();
3574 if (thread != 0 && !thread->standby()) {
3575 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3576 pInBuffer = new Buffer;
3577 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3578 pInBuffer->frameCount = inBuffer.frameCount;
3579 pInBuffer->i16 = pInBuffer->mBuffer;
3580 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3581 mBufferQueue.add(pInBuffer);
3582 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3583 } else {
3584 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3585 }
3586 }
3587 }
3588
3589 // Calling write() with a 0 length buffer, means that no more data will be written:
3590 // If no more buffers are pending, fill output track buffer to make sure it is started
3591 // by output mixer.
3592 if (frames == 0 && mBufferQueue.size() == 0) {
3593 if (mCblk->user < mCblk->frameCount) {
3594 frames = mCblk->frameCount - mCblk->user;
3595 pInBuffer = new Buffer;
3596 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3597 pInBuffer->frameCount = frames;
3598 pInBuffer->i16 = pInBuffer->mBuffer;
3599 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3600 mBufferQueue.add(pInBuffer);
3601 } else if (mActive) {
3602 stop();
3603 }
3604 }
3605
3606 return outputBufferFull;
3607}
3608
3609status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3610{
3611 int active;
3612 status_t result;
3613 audio_track_cblk_t* cblk = mCblk;
3614 uint32_t framesReq = buffer->frameCount;
3615
3616// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3617 buffer->frameCount = 0;
3618
3619 uint32_t framesAvail = cblk->framesAvailable();
3620
3621
3622 if (framesAvail == 0) {
3623 Mutex::Autolock _l(cblk->lock);
3624 goto start_loop_here;
3625 while (framesAvail == 0) {
3626 active = mActive;
3627 if (UNLIKELY(!active)) {
3628 LOGV("Not active and NO_MORE_BUFFERS");
3629 return AudioTrack::NO_MORE_BUFFERS;
3630 }
3631 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3632 if (result != NO_ERROR) {
3633 return AudioTrack::NO_MORE_BUFFERS;
3634 }
3635 // read the server count again
3636 start_loop_here:
3637 framesAvail = cblk->framesAvailable_l();
3638 }
3639 }
3640
3641// if (framesAvail < framesReq) {
3642// return AudioTrack::NO_MORE_BUFFERS;
3643// }
3644
3645 if (framesReq > framesAvail) {
3646 framesReq = framesAvail;
3647 }
3648
3649 uint32_t u = cblk->user;
3650 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3651
3652 if (u + framesReq > bufferEnd) {
3653 framesReq = bufferEnd - u;
3654 }
3655
3656 buffer->frameCount = framesReq;
3657 buffer->raw = (void *)cblk->buffer(u);
3658 return NO_ERROR;
3659}
3660
3661
3662void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3663{
3664 size_t size = mBufferQueue.size();
3665 Buffer *pBuffer;
3666
3667 for (size_t i = 0; i < size; i++) {
3668 pBuffer = mBufferQueue.itemAt(i);
3669 delete [] pBuffer->mBuffer;
3670 delete pBuffer;
3671 }
3672 mBufferQueue.clear();
3673}
3674
3675// ----------------------------------------------------------------------------
3676
3677AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3678 : RefBase(),
3679 mAudioFlinger(audioFlinger),
3680 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3681 mPid(pid)
3682{
3683 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3684}
3685
3686// Client destructor must be called with AudioFlinger::mLock held
3687AudioFlinger::Client::~Client()
3688{
3689 mAudioFlinger->removeClient_l(mPid);
3690}
3691
3692const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3693{
3694 return mMemoryDealer;
3695}
3696
3697// ----------------------------------------------------------------------------
3698
3699AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3700 const sp<IAudioFlingerClient>& client,
3701 pid_t pid)
3702 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3703{
3704}
3705
3706AudioFlinger::NotificationClient::~NotificationClient()
3707{
3708 mClient.clear();
3709}
3710
3711void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3712{
3713 sp<NotificationClient> keep(this);
3714 {
3715 mAudioFlinger->removeNotificationClient(mPid);
3716 }
3717}
3718
3719// ----------------------------------------------------------------------------
3720
3721AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3722 : BnAudioTrack(),
3723 mTrack(track)
3724{
3725}
3726
3727AudioFlinger::TrackHandle::~TrackHandle() {
3728 // just stop the track on deletion, associated resources
3729 // will be freed from the main thread once all pending buffers have
3730 // been played. Unless it's not in the active track list, in which
3731 // case we free everything now...
3732 mTrack->destroy();
3733}
3734
3735status_t AudioFlinger::TrackHandle::start() {
3736 return mTrack->start();
3737}
3738
3739void AudioFlinger::TrackHandle::stop() {
3740 mTrack->stop();
3741}
3742
3743void AudioFlinger::TrackHandle::flush() {
3744 mTrack->flush();
3745}
3746
3747void AudioFlinger::TrackHandle::mute(bool e) {
3748 mTrack->mute(e);
3749}
3750
3751void AudioFlinger::TrackHandle::pause() {
3752 mTrack->pause();
3753}
3754
3755void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3756 mTrack->setVolume(left, right);
3757}
3758
3759sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3760 return mTrack->getCblk();
3761}
3762
3763status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3764{
3765 return mTrack->attachAuxEffect(EffectId);
3766}
3767
3768status_t AudioFlinger::TrackHandle::onTransact(
3769 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3770{
3771 return BnAudioTrack::onTransact(code, data, reply, flags);
3772}
3773
3774// ----------------------------------------------------------------------------
3775
3776sp<IAudioRecord> AudioFlinger::openRecord(
3777 pid_t pid,
3778 int input,
3779 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003780 uint32_t format,
3781 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003782 int frameCount,
3783 uint32_t flags,
3784 int *sessionId,
3785 status_t *status)
3786{
3787 sp<RecordThread::RecordTrack> recordTrack;
3788 sp<RecordHandle> recordHandle;
3789 sp<Client> client;
3790 wp<Client> wclient;
3791 status_t lStatus;
3792 RecordThread *thread;
3793 size_t inFrameCount;
3794 int lSessionId;
3795
3796 // check calling permissions
3797 if (!recordingAllowed()) {
3798 lStatus = PERMISSION_DENIED;
3799 goto Exit;
3800 }
3801
3802 // add client to list
3803 { // scope for mLock
3804 Mutex::Autolock _l(mLock);
3805 thread = checkRecordThread_l(input);
3806 if (thread == NULL) {
3807 lStatus = BAD_VALUE;
3808 goto Exit;
3809 }
3810
3811 wclient = mClients.valueFor(pid);
3812 if (wclient != NULL) {
3813 client = wclient.promote();
3814 } else {
3815 client = new Client(this, pid);
3816 mClients.add(pid, client);
3817 }
3818
3819 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07003820 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003821 lSessionId = *sessionId;
3822 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003823 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003824 if (sessionId != NULL) {
3825 *sessionId = lSessionId;
3826 }
3827 }
3828 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003829 recordTrack = thread->createRecordTrack_l(client,
3830 sampleRate,
3831 format,
3832 channelMask,
3833 frameCount,
3834 flags,
3835 lSessionId,
3836 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003838 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3840 // destructor is called by the TrackBase destructor with mLock held
3841 client.clear();
3842 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843 goto Exit;
3844 }
3845
3846 // return to handle to client
3847 recordHandle = new RecordHandle(recordTrack);
3848 lStatus = NO_ERROR;
3849
3850Exit:
3851 if (status) {
3852 *status = lStatus;
3853 }
3854 return recordHandle;
3855}
3856
3857// ----------------------------------------------------------------------------
3858
3859AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3860 : BnAudioRecord(),
3861 mRecordTrack(recordTrack)
3862{
3863}
3864
3865AudioFlinger::RecordHandle::~RecordHandle() {
3866 stop();
3867}
3868
3869status_t AudioFlinger::RecordHandle::start() {
3870 LOGV("RecordHandle::start()");
3871 return mRecordTrack->start();
3872}
3873
3874void AudioFlinger::RecordHandle::stop() {
3875 LOGV("RecordHandle::stop()");
3876 mRecordTrack->stop();
3877}
3878
3879sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3880 return mRecordTrack->getCblk();
3881}
3882
3883status_t AudioFlinger::RecordHandle::onTransact(
3884 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3885{
3886 return BnAudioRecord::onTransact(code, data, reply, flags);
3887}
3888
3889// ----------------------------------------------------------------------------
3890
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003891AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
3892 AudioStreamIn *input,
3893 uint32_t sampleRate,
3894 uint32_t channels,
3895 int id,
3896 uint32_t device) :
3897 ThreadBase(audioFlinger, id, device),
3898 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003899{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003900 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07003901
3902 snprintf(mName, kNameLength, "AudioIn_%d", id);
3903
Dima Zavinfce7a472011-04-19 22:30:36 -07003904 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 mReqSampleRate = sampleRate;
3906 readInputParameters();
3907}
3908
3909
3910AudioFlinger::RecordThread::~RecordThread()
3911{
3912 delete[] mRsmpInBuffer;
3913 if (mResampler != 0) {
3914 delete mResampler;
3915 delete[] mRsmpOutBuffer;
3916 }
3917}
3918
3919void AudioFlinger::RecordThread::onFirstRef()
3920{
Eric Laurentfeb0db62011-07-22 09:04:31 -07003921 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003922}
3923
3924bool AudioFlinger::RecordThread::threadLoop()
3925{
3926 AudioBufferProvider::Buffer buffer;
3927 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003928 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929
Eric Laurent44d98482010-09-30 16:12:31 -07003930 nsecs_t lastWarning = 0;
3931
Eric Laurentfeb0db62011-07-22 09:04:31 -07003932 acquireWakeLock();
3933
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934 // start recording
3935 while (!exitPending()) {
3936
3937 processConfigEvents();
3938
3939 { // scope for mLock
3940 Mutex::Autolock _l(mLock);
3941 checkForNewParameters_l();
3942 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3943 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003944 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945 mStandby = true;
3946 }
3947
3948 if (exitPending()) break;
3949
Eric Laurentfeb0db62011-07-22 09:04:31 -07003950 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 LOGV("RecordThread: loop stopping");
3952 // go to sleep
3953 mWaitWorkCV.wait(mLock);
3954 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07003955 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 continue;
3957 }
3958 if (mActiveTrack != 0) {
3959 if (mActiveTrack->mState == TrackBase::PAUSING) {
3960 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003961 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962 mStandby = true;
3963 }
3964 mActiveTrack.clear();
3965 mStartStopCond.broadcast();
3966 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3967 if (mReqChannelCount != mActiveTrack->channelCount()) {
3968 mActiveTrack.clear();
3969 mStartStopCond.broadcast();
3970 } else if (mBytesRead != 0) {
3971 // record start succeeds only if first read from audio input
3972 // succeeds
3973 if (mBytesRead > 0) {
3974 mActiveTrack->mState = TrackBase::ACTIVE;
3975 } else {
3976 mActiveTrack.clear();
3977 }
3978 mStartStopCond.broadcast();
3979 }
3980 mStandby = false;
3981 }
3982 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003983 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 }
3985
3986 if (mActiveTrack != 0) {
3987 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3988 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003989 unlockEffectChains(effectChains);
3990 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991 continue;
3992 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003993 for (size_t i = 0; i < effectChains.size(); i ++) {
3994 effectChains[i]->process_l();
3995 }
3996 // enable changes in effect chain
3997 unlockEffectChains(effectChains);
3998
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999 buffer.frameCount = mFrameCount;
4000 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4001 size_t framesOut = buffer.frameCount;
4002 if (mResampler == 0) {
4003 // no resampling
4004 while (framesOut) {
4005 size_t framesIn = mFrameCount - mRsmpInIndex;
4006 if (framesIn) {
4007 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4008 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4009 if (framesIn > framesOut)
4010 framesIn = framesOut;
4011 mRsmpInIndex += framesIn;
4012 framesOut -= framesIn;
4013 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004014 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 memcpy(dst, src, framesIn * mFrameSize);
4016 } else {
4017 int16_t *src16 = (int16_t *)src;
4018 int16_t *dst16 = (int16_t *)dst;
4019 if (mChannelCount == 1) {
4020 while (framesIn--) {
4021 *dst16++ = *src16;
4022 *dst16++ = *src16++;
4023 }
4024 } else {
4025 while (framesIn--) {
4026 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4027 src16 += 2;
4028 }
4029 }
4030 }
4031 }
4032 if (framesOut && mFrameCount == mRsmpInIndex) {
4033 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004034 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004035 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036 framesOut = 0;
4037 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004038 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 mRsmpInIndex = 0;
4040 }
4041 if (mBytesRead < 0) {
4042 LOGE("Error reading audio input");
4043 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4044 // Force input into standby so that it tries to
4045 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004046 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004047 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004048 }
4049 mRsmpInIndex = mFrameCount;
4050 framesOut = 0;
4051 buffer.frameCount = 0;
4052 }
4053 }
4054 }
4055 } else {
4056 // resampling
4057
4058 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4059 // alter output frame count as if we were expecting stereo samples
4060 if (mChannelCount == 1 && mReqChannelCount == 1) {
4061 framesOut >>= 1;
4062 }
4063 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4064 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4065 // are 32 bit aligned which should be always true.
4066 if (mChannelCount == 2 && mReqChannelCount == 1) {
4067 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4068 // the resampler always outputs stereo samples: do post stereo to mono conversion
4069 int16_t *src = (int16_t *)mRsmpOutBuffer;
4070 int16_t *dst = buffer.i16;
4071 while (framesOut--) {
4072 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4073 src += 2;
4074 }
4075 } else {
4076 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4077 }
4078
4079 }
4080 mActiveTrack->releaseBuffer(&buffer);
4081 mActiveTrack->overflow();
4082 }
4083 // client isn't retrieving buffers fast enough
4084 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004085 if (!mActiveTrack->setOverflow()) {
4086 nsecs_t now = systemTime();
4087 if ((now - lastWarning) > kWarningThrottle) {
4088 LOGW("RecordThread: buffer overflow");
4089 lastWarning = now;
4090 }
4091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092 // Release the processor for a while before asking for a new buffer.
4093 // This will give the application more chance to read from the buffer and
4094 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004095 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004097 } else {
4098 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004099 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004100 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004101 }
4102
4103 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004104 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004105 }
4106 mActiveTrack.clear();
4107
4108 mStartStopCond.broadcast();
4109
Eric Laurentfeb0db62011-07-22 09:04:31 -07004110 releaseWakeLock();
4111
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 LOGV("RecordThread %p exiting", this);
4113 return false;
4114}
4115
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004116
4117sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4118 const sp<AudioFlinger::Client>& client,
4119 uint32_t sampleRate,
4120 int format,
4121 int channelMask,
4122 int frameCount,
4123 uint32_t flags,
4124 int sessionId,
4125 status_t *status)
4126{
4127 sp<RecordTrack> track;
4128 status_t lStatus;
4129
4130 lStatus = initCheck();
4131 if (lStatus != NO_ERROR) {
4132 LOGE("Audio driver not initialized.");
4133 goto Exit;
4134 }
4135
4136 { // scope for mLock
4137 Mutex::Autolock _l(mLock);
4138
4139 track = new RecordTrack(this, client, sampleRate,
4140 format, channelMask, frameCount, flags, sessionId);
4141
4142 if (track->getCblk() == NULL) {
4143 lStatus = NO_MEMORY;
4144 goto Exit;
4145 }
4146
4147 mTrack = track.get();
4148
4149 }
4150 lStatus = NO_ERROR;
4151
4152Exit:
4153 if (status) {
4154 *status = lStatus;
4155 }
4156 return track;
4157}
4158
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4160{
4161 LOGV("RecordThread::start");
4162 sp <ThreadBase> strongMe = this;
4163 status_t status = NO_ERROR;
4164 {
4165 AutoMutex lock(&mLock);
4166 if (mActiveTrack != 0) {
4167 if (recordTrack != mActiveTrack.get()) {
4168 status = -EBUSY;
4169 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4170 mActiveTrack->mState = TrackBase::ACTIVE;
4171 }
4172 return status;
4173 }
4174
4175 recordTrack->mState = TrackBase::IDLE;
4176 mActiveTrack = recordTrack;
4177 mLock.unlock();
4178 status_t status = AudioSystem::startInput(mId);
4179 mLock.lock();
4180 if (status != NO_ERROR) {
4181 mActiveTrack.clear();
4182 return status;
4183 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004184 mRsmpInIndex = mFrameCount;
4185 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004186 if (mResampler != NULL) {
4187 mResampler->reset();
4188 }
4189 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 // signal thread to start
4191 LOGV("Signal record thread");
4192 mWaitWorkCV.signal();
4193 // do not wait for mStartStopCond if exiting
4194 if (mExiting) {
4195 mActiveTrack.clear();
4196 status = INVALID_OPERATION;
4197 goto startError;
4198 }
4199 mStartStopCond.wait(mLock);
4200 if (mActiveTrack == 0) {
4201 LOGV("Record failed to start");
4202 status = BAD_VALUE;
4203 goto startError;
4204 }
4205 LOGV("Record started OK");
4206 return status;
4207 }
4208startError:
4209 AudioSystem::stopInput(mId);
4210 return status;
4211}
4212
4213void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4214 LOGV("RecordThread::stop");
4215 sp <ThreadBase> strongMe = this;
4216 {
4217 AutoMutex lock(&mLock);
4218 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4219 mActiveTrack->mState = TrackBase::PAUSING;
4220 // do not wait for mStartStopCond if exiting
4221 if (mExiting) {
4222 return;
4223 }
4224 mStartStopCond.wait(mLock);
4225 // if we have been restarted, recordTrack == mActiveTrack.get() here
4226 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4227 mLock.unlock();
4228 AudioSystem::stopInput(mId);
4229 mLock.lock();
4230 LOGV("Record stopped OK");
4231 }
4232 }
4233 }
4234}
4235
4236status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4237{
4238 const size_t SIZE = 256;
4239 char buffer[SIZE];
4240 String8 result;
4241 pid_t pid = 0;
4242
4243 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4244 result.append(buffer);
4245
4246 if (mActiveTrack != 0) {
4247 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004248 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249 mActiveTrack->dump(buffer, SIZE);
4250 result.append(buffer);
4251
4252 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4253 result.append(buffer);
4254 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4255 result.append(buffer);
4256 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4257 result.append(buffer);
4258 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4259 result.append(buffer);
4260 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4261 result.append(buffer);
4262
4263
4264 } else {
4265 result.append("No record client\n");
4266 }
4267 write(fd, result.string(), result.size());
4268
4269 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004270 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004271
4272 return NO_ERROR;
4273}
4274
4275status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4276{
4277 size_t framesReq = buffer->frameCount;
4278 size_t framesReady = mFrameCount - mRsmpInIndex;
4279 int channelCount;
4280
4281 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004282 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 if (mBytesRead < 0) {
4284 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4285 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4286 // Force input into standby so that it tries to
4287 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004288 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004289 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 }
4291 buffer->raw = 0;
4292 buffer->frameCount = 0;
4293 return NOT_ENOUGH_DATA;
4294 }
4295 mRsmpInIndex = 0;
4296 framesReady = mFrameCount;
4297 }
4298
4299 if (framesReq > framesReady) {
4300 framesReq = framesReady;
4301 }
4302
4303 if (mChannelCount == 1 && mReqChannelCount == 2) {
4304 channelCount = 1;
4305 } else {
4306 channelCount = 2;
4307 }
4308 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4309 buffer->frameCount = framesReq;
4310 return NO_ERROR;
4311}
4312
4313void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4314{
4315 mRsmpInIndex += buffer->frameCount;
4316 buffer->frameCount = 0;
4317}
4318
4319bool AudioFlinger::RecordThread::checkForNewParameters_l()
4320{
4321 bool reconfig = false;
4322
4323 while (!mNewParameters.isEmpty()) {
4324 status_t status = NO_ERROR;
4325 String8 keyValuePair = mNewParameters[0];
4326 AudioParameter param = AudioParameter(keyValuePair);
4327 int value;
4328 int reqFormat = mFormat;
4329 int reqSamplingRate = mReqSampleRate;
4330 int reqChannelCount = mReqChannelCount;
4331
4332 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4333 reqSamplingRate = value;
4334 reconfig = true;
4335 }
4336 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4337 reqFormat = value;
4338 reconfig = true;
4339 }
4340 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004341 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004342 reconfig = true;
4343 }
4344 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4345 // do not accept frame count changes if tracks are open as the track buffer
4346 // size depends on frame count and correct behavior would not be garantied
4347 // if frame count is changed after track creation
4348 if (mActiveTrack != 0) {
4349 status = INVALID_OPERATION;
4350 } else {
4351 reconfig = true;
4352 }
4353 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004354 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4355 // forward device change to effects that have requested to be
4356 // aware of attached audio device.
4357 for (size_t i = 0; i < mEffectChains.size(); i++) {
4358 mEffectChains[i]->setDevice_l(value);
4359 }
4360 // store input device and output device but do not forward output device to audio HAL.
4361 // Note that status is ignored by the caller for output device
4362 // (see AudioFlinger::setParameters()
4363 if (value & AUDIO_DEVICE_OUT_ALL) {
4364 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4365 status = BAD_VALUE;
4366 } else {
4367 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4368 }
4369 mDevice |= (uint32_t)value;
4370 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004371 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004372 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004374 mInput->stream->common.standby(&mInput->stream->common);
4375 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376 }
4377 if (reconfig) {
4378 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004379 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004380 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004381 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4382 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004383 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384 status = NO_ERROR;
4385 }
4386 if (status == NO_ERROR) {
4387 readInputParameters();
4388 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4389 }
4390 }
4391 }
4392
4393 mNewParameters.removeAt(0);
4394
4395 mParamStatus = status;
4396 mParamCond.signal();
4397 mWaitWorkCV.wait(mLock);
4398 }
4399 return reconfig;
4400}
4401
4402String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4403{
Dima Zavinfce7a472011-04-19 22:30:36 -07004404 char *s;
4405 String8 out_s8;
4406
Dima Zavin799a70e2011-04-18 16:57:27 -07004407 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004408 out_s8 = String8(s);
4409 free(s);
4410 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411}
4412
4413void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4414 AudioSystem::OutputDescriptor desc;
4415 void *param2 = 0;
4416
4417 switch (event) {
4418 case AudioSystem::INPUT_OPENED:
4419 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004420 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421 desc.samplingRate = mSampleRate;
4422 desc.format = mFormat;
4423 desc.frameCount = mFrameCount;
4424 desc.latency = 0;
4425 param2 = &desc;
4426 break;
4427
4428 case AudioSystem::INPUT_CLOSED:
4429 default:
4430 break;
4431 }
4432 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4433}
4434
4435void AudioFlinger::RecordThread::readInputParameters()
4436{
4437 if (mRsmpInBuffer) delete mRsmpInBuffer;
4438 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4439 if (mResampler) delete mResampler;
4440 mResampler = 0;
4441
Dima Zavin799a70e2011-04-18 16:57:27 -07004442 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004443 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4444 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004445 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4446 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4447 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004448 mFrameCount = mInputBytes / mFrameSize;
4449 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4450
4451 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4452 {
4453 int channelCount;
4454 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4455 // stereo to mono post process as the resampler always outputs stereo.
4456 if (mChannelCount == 1 && mReqChannelCount == 2) {
4457 channelCount = 1;
4458 } else {
4459 channelCount = 2;
4460 }
4461 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4462 mResampler->setSampleRate(mSampleRate);
4463 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4464 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4465
4466 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4467 if (mChannelCount == 1 && mReqChannelCount == 1) {
4468 mFrameCount >>= 1;
4469 }
4470
4471 }
4472 mRsmpInIndex = mFrameCount;
4473}
4474
4475unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4476{
Dima Zavin799a70e2011-04-18 16:57:27 -07004477 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478}
4479
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004480uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4481{
4482 Mutex::Autolock _l(mLock);
4483 uint32_t result = 0;
4484 if (getEffectChain_l(sessionId) != 0) {
4485 result = EFFECT_SESSION;
4486 }
4487
4488 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4489 result |= TRACK_SESSION;
4490 }
4491
4492 return result;
4493}
4494
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495// ----------------------------------------------------------------------------
4496
4497int AudioFlinger::openOutput(uint32_t *pDevices,
4498 uint32_t *pSamplingRate,
4499 uint32_t *pFormat,
4500 uint32_t *pChannels,
4501 uint32_t *pLatencyMs,
4502 uint32_t flags)
4503{
4504 status_t status;
4505 PlaybackThread *thread = NULL;
4506 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4507 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4508 uint32_t format = pFormat ? *pFormat : 0;
4509 uint32_t channels = pChannels ? *pChannels : 0;
4510 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004511 audio_stream_out_t *outStream;
4512 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004513
4514 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4515 pDevices ? *pDevices : 0,
4516 samplingRate,
4517 format,
4518 channels,
4519 flags);
4520
4521 if (pDevices == NULL || *pDevices == 0) {
4522 return 0;
4523 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004524
Mathias Agopian65ab4712010-07-14 17:59:35 -07004525 Mutex::Autolock _l(mLock);
4526
Dima Zavin799a70e2011-04-18 16:57:27 -07004527 outHwDev = findSuitableHwDev_l(*pDevices);
4528 if (outHwDev == NULL)
4529 return 0;
4530
4531 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4532 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004534 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004535 samplingRate,
4536 format,
4537 channels,
4538 status);
4539
4540 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004541 if (outStream != NULL) {
4542 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004543 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004544
Dima Zavinfce7a472011-04-19 22:30:36 -07004545 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4546 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4547 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004548 thread = new DirectOutputThread(this, output, id, *pDevices);
4549 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4550 } else {
4551 thread = new MixerThread(this, output, id, *pDevices);
4552 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 }
4554 mPlaybackThreads.add(id, thread);
4555
4556 if (pSamplingRate) *pSamplingRate = samplingRate;
4557 if (pFormat) *pFormat = format;
4558 if (pChannels) *pChannels = channels;
4559 if (pLatencyMs) *pLatencyMs = thread->latency();
4560
4561 // notify client processes of the new output creation
4562 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4563 return id;
4564 }
4565
4566 return 0;
4567}
4568
4569int AudioFlinger::openDuplicateOutput(int output1, int output2)
4570{
4571 Mutex::Autolock _l(mLock);
4572 MixerThread *thread1 = checkMixerThread_l(output1);
4573 MixerThread *thread2 = checkMixerThread_l(output2);
4574
4575 if (thread1 == NULL || thread2 == NULL) {
4576 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4577 return 0;
4578 }
4579
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004580 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004581 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4582 thread->addOutputTrack(thread2);
4583 mPlaybackThreads.add(id, thread);
4584 // notify client processes of the new output creation
4585 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4586 return id;
4587}
4588
4589status_t AudioFlinger::closeOutput(int output)
4590{
4591 // keep strong reference on the playback thread so that
4592 // it is not destroyed while exit() is executed
4593 sp <PlaybackThread> thread;
4594 {
4595 Mutex::Autolock _l(mLock);
4596 thread = checkPlaybackThread_l(output);
4597 if (thread == NULL) {
4598 return BAD_VALUE;
4599 }
4600
4601 LOGV("closeOutput() %d", output);
4602
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004603 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004604 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004605 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4607 dupThread->removeOutputTrack((MixerThread *)thread.get());
4608 }
4609 }
4610 }
4611 void *param2 = 0;
4612 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4613 mPlaybackThreads.removeItem(output);
4614 }
4615 thread->exit();
4616
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004617 if (thread->type() != ThreadBase::DUPLICATING) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004618 AudioStreamOut *out = thread->getOutput();
4619 out->hwDev->close_output_stream(out->hwDev, out->stream);
4620 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 }
4622 return NO_ERROR;
4623}
4624
4625status_t AudioFlinger::suspendOutput(int output)
4626{
4627 Mutex::Autolock _l(mLock);
4628 PlaybackThread *thread = checkPlaybackThread_l(output);
4629
4630 if (thread == NULL) {
4631 return BAD_VALUE;
4632 }
4633
4634 LOGV("suspendOutput() %d", output);
4635 thread->suspend();
4636
4637 return NO_ERROR;
4638}
4639
4640status_t AudioFlinger::restoreOutput(int output)
4641{
4642 Mutex::Autolock _l(mLock);
4643 PlaybackThread *thread = checkPlaybackThread_l(output);
4644
4645 if (thread == NULL) {
4646 return BAD_VALUE;
4647 }
4648
4649 LOGV("restoreOutput() %d", output);
4650
4651 thread->restore();
4652
4653 return NO_ERROR;
4654}
4655
4656int AudioFlinger::openInput(uint32_t *pDevices,
4657 uint32_t *pSamplingRate,
4658 uint32_t *pFormat,
4659 uint32_t *pChannels,
4660 uint32_t acoustics)
4661{
4662 status_t status;
4663 RecordThread *thread = NULL;
4664 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4665 uint32_t format = pFormat ? *pFormat : 0;
4666 uint32_t channels = pChannels ? *pChannels : 0;
4667 uint32_t reqSamplingRate = samplingRate;
4668 uint32_t reqFormat = format;
4669 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004670 audio_stream_in_t *inStream;
4671 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004672
4673 if (pDevices == NULL || *pDevices == 0) {
4674 return 0;
4675 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004676
Mathias Agopian65ab4712010-07-14 17:59:35 -07004677 Mutex::Autolock _l(mLock);
4678
Dima Zavin799a70e2011-04-18 16:57:27 -07004679 inHwDev = findSuitableHwDev_l(*pDevices);
4680 if (inHwDev == NULL)
4681 return 0;
4682
4683 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4684 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004685 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004686 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004687 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004688 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004689 samplingRate,
4690 format,
4691 channels,
4692 acoustics,
4693 status);
4694
4695 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4696 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4697 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07004698 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004699 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004700 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004701 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004702 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07004703 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4704 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004705 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004706 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004707 }
4708
Dima Zavin799a70e2011-04-18 16:57:27 -07004709 if (inStream != NULL) {
4710 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4711
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004712 int id = nextUniqueId();
4713 // Start record thread
4714 // RecorThread require both input and output device indication to forward to audio
4715 // pre processing modules
4716 uint32_t device = (*pDevices) | primaryOutputDevice_l();
4717 thread = new RecordThread(this,
4718 input,
4719 reqSamplingRate,
4720 reqChannels,
4721 id,
4722 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 mRecordThreads.add(id, thread);
4724 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4725 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4726 if (pFormat) *pFormat = format;
4727 if (pChannels) *pChannels = reqChannels;
4728
Dima Zavin799a70e2011-04-18 16:57:27 -07004729 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004730
4731 // notify client processes of the new input creation
4732 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4733 return id;
4734 }
4735
4736 return 0;
4737}
4738
4739status_t AudioFlinger::closeInput(int input)
4740{
4741 // keep strong reference on the record thread so that
4742 // it is not destroyed while exit() is executed
4743 sp <RecordThread> thread;
4744 {
4745 Mutex::Autolock _l(mLock);
4746 thread = checkRecordThread_l(input);
4747 if (thread == NULL) {
4748 return BAD_VALUE;
4749 }
4750
4751 LOGV("closeInput() %d", input);
4752 void *param2 = 0;
4753 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4754 mRecordThreads.removeItem(input);
4755 }
4756 thread->exit();
4757
Dima Zavin799a70e2011-04-18 16:57:27 -07004758 AudioStreamIn *in = thread->getInput();
4759 in->hwDev->close_input_stream(in->hwDev, in->stream);
4760 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761
4762 return NO_ERROR;
4763}
4764
4765status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4766{
4767 Mutex::Autolock _l(mLock);
4768 MixerThread *dstThread = checkMixerThread_l(output);
4769 if (dstThread == NULL) {
4770 LOGW("setStreamOutput() bad output id %d", output);
4771 return BAD_VALUE;
4772 }
4773
4774 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4775 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4776
4777 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4778 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4779 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004780 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004781 MixerThread *srcThread = (MixerThread *)thread;
4782 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783 }
Eric Laurentde070132010-07-13 04:45:46 -07004784 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004785
4786 return NO_ERROR;
4787}
4788
4789
4790int AudioFlinger::newAudioSessionId()
4791{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004792 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004793}
4794
4795// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4796AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4797{
4798 PlaybackThread *thread = NULL;
4799 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4800 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4801 }
4802 return thread;
4803}
4804
4805// checkMixerThread_l() must be called with AudioFlinger::mLock held
4806AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4807{
4808 PlaybackThread *thread = checkPlaybackThread_l(output);
4809 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004810 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811 thread = NULL;
4812 }
4813 }
4814 return (MixerThread *)thread;
4815}
4816
4817// checkRecordThread_l() must be called with AudioFlinger::mLock held
4818AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4819{
4820 RecordThread *thread = NULL;
4821 if (mRecordThreads.indexOfKey(input) >= 0) {
4822 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4823 }
4824 return thread;
4825}
4826
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004827uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004828{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004829 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004830}
4831
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004832AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
4833{
4834 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4835 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4836 if (thread->getOutput()->hwDev == mPrimaryHardwareDev) {
4837 return thread;
4838 }
4839 }
4840 return NULL;
4841}
4842
4843uint32_t AudioFlinger::primaryOutputDevice_l()
4844{
4845 PlaybackThread *thread = primaryPlaybackThread_l();
4846
4847 if (thread == NULL) {
4848 return 0;
4849 }
4850
4851 return thread->device();
4852}
4853
4854
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855// ----------------------------------------------------------------------------
4856// Effect management
4857// ----------------------------------------------------------------------------
4858
4859
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4861{
4862 Mutex::Autolock _l(mLock);
4863 return EffectQueryNumberEffects(numEffects);
4864}
4865
4866status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4867{
4868 Mutex::Autolock _l(mLock);
4869 return EffectQueryEffect(index, descriptor);
4870}
4871
4872status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4873{
4874 Mutex::Autolock _l(mLock);
4875 return EffectGetDescriptor(pUuid, descriptor);
4876}
4877
4878
4879// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4880static const effect_uuid_t VISUALIZATION_UUID_ =
4881 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4882
4883sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4884 effect_descriptor_t *pDesc,
4885 const sp<IEffectClient>& effectClient,
4886 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004887 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004888 int sessionId,
4889 status_t *status,
4890 int *id,
4891 int *enabled)
4892{
4893 status_t lStatus = NO_ERROR;
4894 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895 effect_descriptor_t desc;
4896 sp<Client> client;
4897 wp<Client> wclient;
4898
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004899 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
4900 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004901
4902 if (pDesc == NULL) {
4903 lStatus = BAD_VALUE;
4904 goto Exit;
4905 }
4906
Eric Laurent84e9a102010-09-23 16:10:16 -07004907 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07004908 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004909 lStatus = PERMISSION_DENIED;
4910 goto Exit;
4911 }
4912
Dima Zavinfce7a472011-04-19 22:30:36 -07004913 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07004914 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07004915 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004916 lStatus = PERMISSION_DENIED;
4917 goto Exit;
4918 }
4919
4920 // check recording permission for visualizer
4921 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4922 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4923 !recordingAllowed()) {
4924 lStatus = PERMISSION_DENIED;
4925 goto Exit;
4926 }
4927
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004928 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004929 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004930 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07004931 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07004932 lStatus = BAD_VALUE;
4933 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07004934 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004935 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004936 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07004937 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004938 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07004939 }
4940 }
4941
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 {
4943 Mutex::Autolock _l(mLock);
4944
Mathias Agopian65ab4712010-07-14 17:59:35 -07004945
4946 if (!EffectIsNullUuid(&pDesc->uuid)) {
4947 // if uuid is specified, request effect descriptor
4948 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4949 if (lStatus < 0) {
4950 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4951 goto Exit;
4952 }
4953 } else {
4954 // if uuid is not specified, look for an available implementation
4955 // of the required type in effect factory
4956 if (EffectIsNullUuid(&pDesc->type)) {
4957 LOGW("createEffect() no effect type");
4958 lStatus = BAD_VALUE;
4959 goto Exit;
4960 }
4961 uint32_t numEffects = 0;
4962 effect_descriptor_t d;
4963 bool found = false;
4964
4965 lStatus = EffectQueryNumberEffects(&numEffects);
4966 if (lStatus < 0) {
4967 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4968 goto Exit;
4969 }
4970 for (uint32_t i = 0; i < numEffects; i++) {
4971 lStatus = EffectQueryEffect(i, &desc);
4972 if (lStatus < 0) {
4973 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4974 continue;
4975 }
4976 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4977 // If matching type found save effect descriptor. If the session is
4978 // 0 and the effect is not auxiliary, continue enumeration in case
4979 // an auxiliary version of this effect type is available
4980 found = true;
4981 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07004982 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004983 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4984 break;
4985 }
4986 }
4987 }
4988 if (!found) {
4989 lStatus = BAD_VALUE;
4990 LOGW("createEffect() effect not found");
4991 goto Exit;
4992 }
4993 // For same effect type, chose auxiliary version over insert version if
4994 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07004995 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004996 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4997 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4998 }
4999 }
5000
5001 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005002 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005003 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5004 lStatus = INVALID_OPERATION;
5005 goto Exit;
5006 }
5007
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 // return effect descriptor
5009 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5010
5011 // If output is not specified try to find a matching audio session ID in one of the
5012 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005013 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5014 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005015 // Note: io is never 0 when creating an effect on an input
5016 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005017 // look for the thread where the specified audio session is present
5018 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5019 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005020 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005021 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005022 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005024 if (io == 0) {
5025 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5026 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5027 io = mRecordThreads.keyAt(i);
5028 break;
5029 }
5030 }
5031 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005032 // If no output thread contains the requested session ID, default to
5033 // first output. The effect chain will be moved to the correct output
5034 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005035 if (io == 0 && mPlaybackThreads.size()) {
5036 io = mPlaybackThreads.keyAt(0);
5037 }
5038 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5039 }
5040 ThreadBase *thread = checkRecordThread_l(io);
5041 if (thread == NULL) {
5042 thread = checkPlaybackThread_l(io);
5043 if (thread == NULL) {
5044 LOGE("createEffect() unknown output thread");
5045 lStatus = BAD_VALUE;
5046 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005047 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005048 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005049
Mathias Agopian65ab4712010-07-14 17:59:35 -07005050 wclient = mClients.valueFor(pid);
5051
5052 if (wclient != NULL) {
5053 client = wclient.promote();
5054 } else {
5055 client = new Client(this, pid);
5056 mClients.add(pid, client);
5057 }
5058
5059 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07005060 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5061 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 if (handle != 0 && id != NULL) {
5063 *id = handle->id();
5064 }
5065 }
5066
5067Exit:
5068 if(status) {
5069 *status = lStatus;
5070 }
5071 return handle;
5072}
5073
Eric Laurentde070132010-07-13 04:45:46 -07005074status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
5075{
5076 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
5077 session, srcOutput, dstOutput);
5078 Mutex::Autolock _l(mLock);
5079 if (srcOutput == dstOutput) {
5080 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5081 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 }
Eric Laurentde070132010-07-13 04:45:46 -07005083 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5084 if (srcThread == NULL) {
5085 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5086 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005087 }
Eric Laurentde070132010-07-13 04:45:46 -07005088 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5089 if (dstThread == NULL) {
5090 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5091 return BAD_VALUE;
5092 }
5093
5094 Mutex::Autolock _dl(dstThread->mLock);
5095 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07005096 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005097
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098 return NO_ERROR;
5099}
5100
Eric Laurentde070132010-07-13 04:45:46 -07005101// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
5102status_t AudioFlinger::moveEffectChain_l(int session,
5103 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005104 AudioFlinger::PlaybackThread *dstThread,
5105 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005106{
5107 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
5108 session, srcThread, dstThread);
5109
5110 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
5111 if (chain == 0) {
5112 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
5113 session, srcThread);
5114 return INVALID_OPERATION;
5115 }
5116
Eric Laurent39e94f82010-07-28 01:32:47 -07005117 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005118 // so that a new chain is created with correct parameters when first effect is added. This is
5119 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
5120 // removed.
5121 srcThread->removeEffectChain_l(chain);
5122
5123 // transfer all effects one by one so that new effect chain is created on new thread with
5124 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005125 int dstOutput = dstThread->id();
5126 sp<EffectChain> dstChain;
5127 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07005128 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5129 while (effect != 0) {
5130 srcThread->removeEffect_l(effect);
5131 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07005132 // if the move request is not received from audio policy manager, the effect must be
5133 // re-registered with the new strategy and output
5134 if (dstChain == 0) {
5135 dstChain = effect->chain().promote();
5136 if (dstChain == 0) {
5137 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5138 srcThread->addEffect_l(effect);
5139 return NO_INIT;
5140 }
5141 strategy = dstChain->strategy();
5142 }
5143 if (reRegister) {
5144 AudioSystem::unregisterEffect(effect->id());
5145 AudioSystem::registerEffect(&effect->desc(),
5146 dstOutput,
5147 strategy,
5148 session,
5149 effect->id());
5150 }
Eric Laurentde070132010-07-13 04:45:46 -07005151 effect = chain->getEffectFromId_l(0);
5152 }
5153
5154 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005155}
5156
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005157
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005159sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005160 const sp<AudioFlinger::Client>& client,
5161 const sp<IEffectClient>& effectClient,
5162 int32_t priority,
5163 int sessionId,
5164 effect_descriptor_t *desc,
5165 int *enabled,
5166 status_t *status
5167 )
5168{
5169 sp<EffectModule> effect;
5170 sp<EffectHandle> handle;
5171 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005173 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 bool effectCreated = false;
5175 bool effectRegistered = false;
5176
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005177 lStatus = initCheck();
5178 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005179 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180 goto Exit;
5181 }
5182
5183 // Do not allow effects with session ID 0 on direct output or duplicating threads
5184 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005185 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005186 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5187 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 lStatus = BAD_VALUE;
5189 goto Exit;
5190 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005191 // Only Pre processor effects are allowed on input threads and only on input threads
5192 if ((mType == RECORD &&
5193 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5194 (mType != RECORD &&
5195 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5196 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5197 desc->name, desc->flags, mType);
5198 lStatus = BAD_VALUE;
5199 goto Exit;
5200 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005201
5202 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5203
5204 { // scope for mLock
5205 Mutex::Autolock _l(mLock);
5206
5207 // check for existing effect chain with the requested audio session
5208 chain = getEffectChain_l(sessionId);
5209 if (chain == 0) {
5210 // create a new chain for this session
5211 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5212 chain = new EffectChain(this, sessionId);
5213 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005214 chain->setStrategy(getStrategyForSession_l(sessionId));
5215 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005217 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005218 }
5219
5220 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5221
5222 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005223 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005224 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005225 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005226 if (lStatus != NO_ERROR) {
5227 goto Exit;
5228 }
5229 effectRegistered = true;
5230 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005231 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005232 lStatus = effect->status();
5233 if (lStatus != NO_ERROR) {
5234 goto Exit;
5235 }
Eric Laurentcab11242010-07-15 12:50:15 -07005236 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005237 if (lStatus != NO_ERROR) {
5238 goto Exit;
5239 }
5240 effectCreated = true;
5241
5242 effect->setDevice(mDevice);
5243 effect->setMode(mAudioFlinger->getMode());
5244 }
5245 // create effect handle and connect it to effect module
5246 handle = new EffectHandle(effect, client, effectClient, priority);
5247 lStatus = effect->addHandle(handle);
5248 if (enabled) {
5249 *enabled = (int)effect->isEnabled();
5250 }
5251 }
5252
5253Exit:
5254 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005255 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005256 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005257 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005258 }
5259 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005260 AudioSystem::unregisterEffect(effect->id());
5261 }
5262 if (chainCreated) {
5263 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005264 }
5265 handle.clear();
5266 }
5267
5268 if(status) {
5269 *status = lStatus;
5270 }
5271 return handle;
5272}
5273
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005274sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5275{
5276 sp<EffectModule> effect;
5277
5278 sp<EffectChain> chain = getEffectChain_l(sessionId);
5279 if (chain != 0) {
5280 effect = chain->getEffectFromId_l(effectId);
5281 }
5282 return effect;
5283}
5284
Eric Laurentde070132010-07-13 04:45:46 -07005285// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5286// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005287status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005288{
5289 // check for existing effect chain with the requested audio session
5290 int sessionId = effect->sessionId();
5291 sp<EffectChain> chain = getEffectChain_l(sessionId);
5292 bool chainCreated = false;
5293
5294 if (chain == 0) {
5295 // create a new chain for this session
5296 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5297 chain = new EffectChain(this, sessionId);
5298 addEffectChain_l(chain);
5299 chain->setStrategy(getStrategyForSession_l(sessionId));
5300 chainCreated = true;
5301 }
5302 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5303
5304 if (chain->getEffectFromId_l(effect->id()) != 0) {
5305 LOGW("addEffect_l() %p effect %s already present in chain %p",
5306 this, effect->desc().name, chain.get());
5307 return BAD_VALUE;
5308 }
5309
5310 status_t status = chain->addEffect_l(effect);
5311 if (status != NO_ERROR) {
5312 if (chainCreated) {
5313 removeEffectChain_l(chain);
5314 }
5315 return status;
5316 }
5317
5318 effect->setDevice(mDevice);
5319 effect->setMode(mAudioFlinger->getMode());
5320 return NO_ERROR;
5321}
5322
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005323void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005324
5325 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005327 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5328 detachAuxEffect_l(effect->id());
5329 }
5330
5331 sp<EffectChain> chain = effect->chain().promote();
5332 if (chain != 0) {
5333 // remove effect chain if removing last effect
5334 if (chain->removeEffect_l(effect) == 0) {
5335 removeEffectChain_l(chain);
5336 }
5337 } else {
5338 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5339 }
5340}
5341
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005342void AudioFlinger::ThreadBase::lockEffectChains_l(
5343 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5344{
5345 effectChains = mEffectChains;
5346 for (size_t i = 0; i < mEffectChains.size(); i++) {
5347 mEffectChains[i]->lock();
5348 }
5349}
5350
5351void AudioFlinger::ThreadBase::unlockEffectChains(
5352 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5353{
5354 for (size_t i = 0; i < effectChains.size(); i++) {
5355 effectChains[i]->unlock();
5356 }
5357}
5358
5359sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5360{
5361 Mutex::Autolock _l(mLock);
5362 return getEffectChain_l(sessionId);
5363}
5364
5365sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5366{
5367 sp<EffectChain> chain;
5368
5369 size_t size = mEffectChains.size();
5370 for (size_t i = 0; i < size; i++) {
5371 if (mEffectChains[i]->sessionId() == sessionId) {
5372 chain = mEffectChains[i];
5373 break;
5374 }
5375 }
5376 return chain;
5377}
5378
5379void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5380{
5381 Mutex::Autolock _l(mLock);
5382 size_t size = mEffectChains.size();
5383 for (size_t i = 0; i < size; i++) {
5384 mEffectChains[i]->setMode_l(mode);
5385 }
5386}
5387
5388void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurentde070132010-07-13 04:45:46 -07005389 const wp<EffectHandle>& handle) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005391 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 // delete the effect module if removing last handle on it
5393 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07005394 removeEffect_l(effect);
5395 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 }
5397}
5398
5399status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5400{
5401 int session = chain->sessionId();
5402 int16_t *buffer = mMixBuffer;
5403 bool ownsBuffer = false;
5404
5405 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5406 if (session > 0) {
5407 // Only one effect chain can be present in direct output thread and it uses
5408 // the mix buffer as input
5409 if (mType != DIRECT) {
5410 size_t numSamples = mFrameCount * mChannelCount;
5411 buffer = new int16_t[numSamples];
5412 memset(buffer, 0, numSamples * sizeof(int16_t));
5413 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5414 ownsBuffer = true;
5415 }
5416
5417 // Attach all tracks with same session ID to this chain.
5418 for (size_t i = 0; i < mTracks.size(); ++i) {
5419 sp<Track> track = mTracks[i];
5420 if (session == track->sessionId()) {
5421 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5422 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005423 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005424 }
5425 }
5426
5427 // indicate all active tracks in the chain
5428 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5429 sp<Track> track = mActiveTracks[i].promote();
5430 if (track == 0) continue;
5431 if (session == track->sessionId()) {
5432 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005433 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434 }
5435 }
5436 }
5437
5438 chain->setInBuffer(buffer, ownsBuffer);
5439 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005440 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005441 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005442 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5443 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005445 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5446 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005447 // Effect chain for other sessions are inserted at beginning of effect
5448 // chains list to be processed before output mix effects. Relative order between other
5449 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 size_t size = mEffectChains.size();
5451 size_t i = 0;
5452 for (i = 0; i < size; i++) {
5453 if (mEffectChains[i]->sessionId() < session) break;
5454 }
5455 mEffectChains.insertAt(chain, i);
5456
5457 return NO_ERROR;
5458}
5459
5460size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5461{
5462 int session = chain->sessionId();
5463
5464 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5465
5466 for (size_t i = 0; i < mEffectChains.size(); i++) {
5467 if (chain == mEffectChains[i]) {
5468 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005469 // detach all active tracks from the chain
5470 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5471 sp<Track> track = mActiveTracks[i].promote();
5472 if (track == 0) continue;
5473 if (session == track->sessionId()) {
5474 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5475 chain.get(), session);
5476 chain->decActiveTrackCnt();
5477 }
5478 }
5479
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 // detach all tracks with same session ID from this chain
5481 for (size_t i = 0; i < mTracks.size(); ++i) {
5482 sp<Track> track = mTracks[i];
5483 if (session == track->sessionId()) {
5484 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005485 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 }
5487 }
Eric Laurentde070132010-07-13 04:45:46 -07005488 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489 }
5490 }
5491 return mEffectChains.size();
5492}
5493
Eric Laurentde070132010-07-13 04:45:46 -07005494status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5495 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005496{
5497 Mutex::Autolock _l(mLock);
5498 return attachAuxEffect_l(track, EffectId);
5499}
5500
Eric Laurentde070132010-07-13 04:45:46 -07005501status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5502 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503{
5504 status_t status = NO_ERROR;
5505
5506 if (EffectId == 0) {
5507 track->setAuxBuffer(0, NULL);
5508 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005509 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5510 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511 if (effect != 0) {
5512 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5513 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5514 } else {
5515 status = INVALID_OPERATION;
5516 }
5517 } else {
5518 status = BAD_VALUE;
5519 }
5520 }
5521 return status;
5522}
5523
5524void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5525{
5526 for (size_t i = 0; i < mTracks.size(); ++i) {
5527 sp<Track> track = mTracks[i];
5528 if (track->auxEffectId() == effectId) {
5529 attachAuxEffect_l(track, 0);
5530 }
5531 }
5532}
5533
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005534status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5535{
5536 // only one chain per input thread
5537 if (mEffectChains.size() != 0) {
5538 return INVALID_OPERATION;
5539 }
5540 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5541
5542 chain->setInBuffer(NULL);
5543 chain->setOutBuffer(NULL);
5544
5545 mEffectChains.add(chain);
5546
5547 return NO_ERROR;
5548}
5549
5550size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5551{
5552 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5553 LOGW_IF(mEffectChains.size() != 1,
5554 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5555 chain.get(), mEffectChains.size(), this);
5556 if (mEffectChains.size() == 1) {
5557 mEffectChains.removeAt(0);
5558 }
5559 return 0;
5560}
5561
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562// ----------------------------------------------------------------------------
5563// EffectModule implementation
5564// ----------------------------------------------------------------------------
5565
5566#undef LOG_TAG
5567#define LOG_TAG "AudioFlinger::EffectModule"
5568
5569AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5570 const wp<AudioFlinger::EffectChain>& chain,
5571 effect_descriptor_t *desc,
5572 int id,
5573 int sessionId)
5574 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5575 mStatus(NO_INIT), mState(IDLE)
5576{
5577 LOGV("Constructor %p", this);
5578 int lStatus;
5579 sp<ThreadBase> thread = mThread.promote();
5580 if (thread == 0) {
5581 return;
5582 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005583
5584 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5585
5586 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005587 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005588
5589 if (mStatus != NO_ERROR) {
5590 return;
5591 }
5592 lStatus = init();
5593 if (lStatus < 0) {
5594 mStatus = lStatus;
5595 goto Error;
5596 }
5597
5598 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5599 return;
5600Error:
5601 EffectRelease(mEffectInterface);
5602 mEffectInterface = NULL;
5603 LOGV("Constructor Error %d", mStatus);
5604}
5605
5606AudioFlinger::EffectModule::~EffectModule()
5607{
5608 LOGV("Destructor %p", this);
5609 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005610 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5611 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
5612 sp<ThreadBase> thread = mThread.promote();
5613 if (thread != 0) {
5614 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5615 }
5616 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005617 // release effect engine
5618 EffectRelease(mEffectInterface);
5619 }
5620}
5621
5622status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5623{
5624 status_t status;
5625
5626 Mutex::Autolock _l(mLock);
5627 // First handle in mHandles has highest priority and controls the effect module
5628 int priority = handle->priority();
5629 size_t size = mHandles.size();
5630 sp<EffectHandle> h;
5631 size_t i;
5632 for (i = 0; i < size; i++) {
5633 h = mHandles[i].promote();
5634 if (h == 0) continue;
5635 if (h->priority() <= priority) break;
5636 }
5637 // if inserted in first place, move effect control from previous owner to this handle
5638 if (i == 0) {
5639 if (h != 0) {
5640 h->setControl(false, true);
5641 }
5642 handle->setControl(true, false);
5643 status = NO_ERROR;
5644 } else {
5645 status = ALREADY_EXISTS;
5646 }
5647 mHandles.insertAt(handle, i);
5648 return status;
5649}
5650
5651size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5652{
5653 Mutex::Autolock _l(mLock);
5654 size_t size = mHandles.size();
5655 size_t i;
5656 for (i = 0; i < size; i++) {
5657 if (mHandles[i] == handle) break;
5658 }
5659 if (i == size) {
5660 return size;
5661 }
5662 mHandles.removeAt(i);
5663 size = mHandles.size();
5664 // if removed from first place, move effect control from this handle to next in line
5665 if (i == 0 && size != 0) {
5666 sp<EffectHandle> h = mHandles[0].promote();
5667 if (h != 0) {
5668 h->setControl(true, true);
5669 }
5670 }
5671
Eric Laurentdac69112010-09-28 14:09:57 -07005672 // Release effect engine here so that it is done immediately. Otherwise it will be released
5673 // by the destructor when the last strong reference on the this object is released which can
5674 // happen after next process is called on this effect.
5675 if (size == 0 && mEffectInterface != NULL) {
5676 // release effect engine
5677 EffectRelease(mEffectInterface);
5678 mEffectInterface = NULL;
5679 }
5680
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681 return size;
5682}
5683
5684void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5685{
5686 // keep a strong reference on this EffectModule to avoid calling the
5687 // destructor before we exit
5688 sp<EffectModule> keep(this);
5689 {
5690 sp<ThreadBase> thread = mThread.promote();
5691 if (thread != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005692 thread->disconnectEffect(keep, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005693 }
5694 }
5695}
5696
5697void AudioFlinger::EffectModule::updateState() {
5698 Mutex::Autolock _l(mLock);
5699
5700 switch (mState) {
5701 case RESTART:
5702 reset_l();
5703 // FALL THROUGH
5704
5705 case STARTING:
5706 // clear auxiliary effect input buffer for next accumulation
5707 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5708 memset(mConfig.inputCfg.buffer.raw,
5709 0,
5710 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5711 }
5712 start_l();
5713 mState = ACTIVE;
5714 break;
5715 case STOPPING:
5716 stop_l();
5717 mDisableWaitCnt = mMaxDisableWaitCnt;
5718 mState = STOPPED;
5719 break;
5720 case STOPPED:
5721 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5722 // turn off sequence.
5723 if (--mDisableWaitCnt == 0) {
5724 reset_l();
5725 mState = IDLE;
5726 }
5727 break;
5728 default: //IDLE , ACTIVE
5729 break;
5730 }
5731}
5732
5733void AudioFlinger::EffectModule::process()
5734{
5735 Mutex::Autolock _l(mLock);
5736
5737 if (mEffectInterface == NULL ||
5738 mConfig.inputCfg.buffer.raw == NULL ||
5739 mConfig.outputCfg.buffer.raw == NULL) {
5740 return;
5741 }
5742
Eric Laurent8f45bd72010-08-31 13:50:07 -07005743 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005744 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5745 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5746 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5747 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005748 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005749 }
5750
5751 // do the actual processing in the effect engine
5752 int ret = (*mEffectInterface)->process(mEffectInterface,
5753 &mConfig.inputCfg.buffer,
5754 &mConfig.outputCfg.buffer);
5755
5756 // force transition to IDLE state when engine is ready
5757 if (mState == STOPPED && ret == -ENODATA) {
5758 mDisableWaitCnt = 1;
5759 }
5760
5761 // clear auxiliary effect input buffer for next accumulation
5762 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005763 memset(mConfig.inputCfg.buffer.raw, 0,
5764 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005765 }
5766 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005767 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5768 // If an insert effect is idle and input buffer is different from output buffer,
5769 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005770 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07005771 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005772 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5773 int16_t *in = mConfig.inputCfg.buffer.s16;
5774 int16_t *out = mConfig.outputCfg.buffer.s16;
5775 for (size_t i = 0; i < frameCnt; i++) {
5776 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778 }
5779 }
5780}
5781
5782void AudioFlinger::EffectModule::reset_l()
5783{
5784 if (mEffectInterface == NULL) {
5785 return;
5786 }
5787 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5788}
5789
5790status_t AudioFlinger::EffectModule::configure()
5791{
5792 uint32_t channels;
5793 if (mEffectInterface == NULL) {
5794 return NO_INIT;
5795 }
5796
5797 sp<ThreadBase> thread = mThread.promote();
5798 if (thread == 0) {
5799 return DEAD_OBJECT;
5800 }
5801
5802 // TODO: handle configuration of effects replacing track process
5803 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005804 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005805 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07005806 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 }
5808
5809 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005810 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005811 } else {
5812 mConfig.inputCfg.channels = channels;
5813 }
5814 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07005815 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5816 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005817 mConfig.inputCfg.samplingRate = thread->sampleRate();
5818 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5819 mConfig.inputCfg.bufferProvider.cookie = NULL;
5820 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5821 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5822 mConfig.outputCfg.bufferProvider.cookie = NULL;
5823 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5824 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5825 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5826 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07005827 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07005828 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005829 // - in other sessions:
5830 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5831 // other effect: overwrites output buffer: input buffer == output buffer
5832 // Auxiliary effect:
5833 // accumulates in output buffer: input buffer != output buffer
5834 // Therefore: accumulate <=> input buffer != output buffer
5835 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5836 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5837 } else {
5838 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5839 }
5840 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5841 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5842 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5843 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5844
Eric Laurentde070132010-07-13 04:45:46 -07005845 LOGV("configure() %p thread %p buffer %p framecount %d",
5846 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5847
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005849 uint32_t size = sizeof(int);
5850 status_t status = (*mEffectInterface)->command(mEffectInterface,
5851 EFFECT_CMD_CONFIGURE,
5852 sizeof(effect_config_t),
5853 &mConfig,
5854 &size,
5855 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005856 if (status == 0) {
5857 status = cmdStatus;
5858 }
5859
5860 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5861 (1000 * mConfig.outputCfg.buffer.frameCount);
5862
5863 return status;
5864}
5865
5866status_t AudioFlinger::EffectModule::init()
5867{
5868 Mutex::Autolock _l(mLock);
5869 if (mEffectInterface == NULL) {
5870 return NO_INIT;
5871 }
5872 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005873 uint32_t size = sizeof(status_t);
5874 status_t status = (*mEffectInterface)->command(mEffectInterface,
5875 EFFECT_CMD_INIT,
5876 0,
5877 NULL,
5878 &size,
5879 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005880 if (status == 0) {
5881 status = cmdStatus;
5882 }
5883 return status;
5884}
5885
5886status_t AudioFlinger::EffectModule::start_l()
5887{
5888 if (mEffectInterface == NULL) {
5889 return NO_INIT;
5890 }
5891 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005892 uint32_t size = sizeof(status_t);
5893 status_t status = (*mEffectInterface)->command(mEffectInterface,
5894 EFFECT_CMD_ENABLE,
5895 0,
5896 NULL,
5897 &size,
5898 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 if (status == 0) {
5900 status = cmdStatus;
5901 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005902 if (status == 0 &&
5903 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5904 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
5905 sp<ThreadBase> thread = mThread.promote();
5906 if (thread != 0) {
5907 thread->stream()->add_audio_effect(thread->stream(), mEffectInterface);
5908 }
5909 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 return status;
5911}
5912
5913status_t AudioFlinger::EffectModule::stop_l()
5914{
5915 if (mEffectInterface == NULL) {
5916 return NO_INIT;
5917 }
5918 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005919 uint32_t size = sizeof(status_t);
5920 status_t status = (*mEffectInterface)->command(mEffectInterface,
5921 EFFECT_CMD_DISABLE,
5922 0,
5923 NULL,
5924 &size,
5925 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 if (status == 0) {
5927 status = cmdStatus;
5928 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005929 if (status == 0 &&
5930 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5931 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
5932 sp<ThreadBase> thread = mThread.promote();
5933 if (thread != 0) {
5934 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5935 }
5936 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 return status;
5938}
5939
Eric Laurent25f43952010-07-28 05:40:18 -07005940status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5941 uint32_t cmdSize,
5942 void *pCmdData,
5943 uint32_t *replySize,
5944 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005945{
5946 Mutex::Autolock _l(mLock);
5947// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5948
5949 if (mEffectInterface == NULL) {
5950 return NO_INIT;
5951 }
Eric Laurent25f43952010-07-28 05:40:18 -07005952 status_t status = (*mEffectInterface)->command(mEffectInterface,
5953 cmdCode,
5954 cmdSize,
5955 pCmdData,
5956 replySize,
5957 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005958 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07005959 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005960 for (size_t i = 1; i < mHandles.size(); i++) {
5961 sp<EffectHandle> h = mHandles[i].promote();
5962 if (h != 0) {
5963 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5964 }
5965 }
5966 }
5967 return status;
5968}
5969
5970status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5971{
5972 Mutex::Autolock _l(mLock);
5973 LOGV("setEnabled %p enabled %d", this, enabled);
5974
5975 if (enabled != isEnabled()) {
5976 switch (mState) {
5977 // going from disabled to enabled
5978 case IDLE:
5979 mState = STARTING;
5980 break;
5981 case STOPPED:
5982 mState = RESTART;
5983 break;
5984 case STOPPING:
5985 mState = ACTIVE;
5986 break;
5987
5988 // going from enabled to disabled
5989 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005990 mState = STOPPED;
5991 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005992 case STARTING:
5993 mState = IDLE;
5994 break;
5995 case ACTIVE:
5996 mState = STOPPING;
5997 break;
5998 }
5999 for (size_t i = 1; i < mHandles.size(); i++) {
6000 sp<EffectHandle> h = mHandles[i].promote();
6001 if (h != 0) {
6002 h->setEnabled(enabled);
6003 }
6004 }
6005 }
6006 return NO_ERROR;
6007}
6008
6009bool AudioFlinger::EffectModule::isEnabled()
6010{
6011 switch (mState) {
6012 case RESTART:
6013 case STARTING:
6014 case ACTIVE:
6015 return true;
6016 case IDLE:
6017 case STOPPING:
6018 case STOPPED:
6019 default:
6020 return false;
6021 }
6022}
6023
Eric Laurent8f45bd72010-08-31 13:50:07 -07006024bool AudioFlinger::EffectModule::isProcessEnabled()
6025{
6026 switch (mState) {
6027 case RESTART:
6028 case ACTIVE:
6029 case STOPPING:
6030 case STOPPED:
6031 return true;
6032 case IDLE:
6033 case STARTING:
6034 default:
6035 return false;
6036 }
6037}
6038
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6040{
6041 Mutex::Autolock _l(mLock);
6042 status_t status = NO_ERROR;
6043
6044 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6045 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006046 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006047 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6048 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006049 status_t cmdStatus;
6050 uint32_t volume[2];
6051 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006052 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006053 volume[0] = *left;
6054 volume[1] = *right;
6055 if (controller) {
6056 pVolume = volume;
6057 }
Eric Laurent25f43952010-07-28 05:40:18 -07006058 status = (*mEffectInterface)->command(mEffectInterface,
6059 EFFECT_CMD_SET_VOLUME,
6060 size,
6061 volume,
6062 &size,
6063 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006064 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6065 *left = volume[0];
6066 *right = volume[1];
6067 }
6068 }
6069 return status;
6070}
6071
6072status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6073{
6074 Mutex::Autolock _l(mLock);
6075 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006076 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6077 // audio pre processing modules on RecordThread can receive both output and
6078 // input device indication in the same call
6079 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6080 if (dev) {
6081 status_t cmdStatus;
6082 uint32_t size = sizeof(status_t);
6083
6084 status = (*mEffectInterface)->command(mEffectInterface,
6085 EFFECT_CMD_SET_DEVICE,
6086 sizeof(uint32_t),
6087 &dev,
6088 &size,
6089 &cmdStatus);
6090 if (status == NO_ERROR) {
6091 status = cmdStatus;
6092 }
6093 }
6094 dev = device & AUDIO_DEVICE_IN_ALL;
6095 if (dev) {
6096 status_t cmdStatus;
6097 uint32_t size = sizeof(status_t);
6098
6099 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6100 EFFECT_CMD_SET_INPUT_DEVICE,
6101 sizeof(uint32_t),
6102 &dev,
6103 &size,
6104 &cmdStatus);
6105 if (status2 == NO_ERROR) {
6106 status2 = cmdStatus;
6107 }
6108 if (status == NO_ERROR) {
6109 status = status2;
6110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 }
6112 }
6113 return status;
6114}
6115
6116status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6117{
6118 Mutex::Autolock _l(mLock);
6119 status_t status = NO_ERROR;
6120 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006122 uint32_t size = sizeof(status_t);
6123 status = (*mEffectInterface)->command(mEffectInterface,
6124 EFFECT_CMD_SET_AUDIO_MODE,
6125 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006126 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006127 &size,
6128 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 if (status == NO_ERROR) {
6130 status = cmdStatus;
6131 }
6132 }
6133 return status;
6134}
6135
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6137{
6138 const size_t SIZE = 256;
6139 char buffer[SIZE];
6140 String8 result;
6141
6142 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6143 result.append(buffer);
6144
6145 bool locked = tryLock(mLock);
6146 // failed to lock - AudioFlinger is probably deadlocked
6147 if (!locked) {
6148 result.append("\t\tCould not lock Fx mutex:\n");
6149 }
6150
6151 result.append("\t\tSession Status State Engine:\n");
6152 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6153 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6154 result.append(buffer);
6155
6156 result.append("\t\tDescriptor:\n");
6157 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6158 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6159 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6160 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6161 result.append(buffer);
6162 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6163 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6164 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6165 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6166 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006167 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006168 mDescriptor.apiVersion,
6169 mDescriptor.flags);
6170 result.append(buffer);
6171 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6172 mDescriptor.name);
6173 result.append(buffer);
6174 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6175 mDescriptor.implementor);
6176 result.append(buffer);
6177
6178 result.append("\t\t- Input configuration:\n");
6179 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6180 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6181 (uint32_t)mConfig.inputCfg.buffer.raw,
6182 mConfig.inputCfg.buffer.frameCount,
6183 mConfig.inputCfg.samplingRate,
6184 mConfig.inputCfg.channels,
6185 mConfig.inputCfg.format);
6186 result.append(buffer);
6187
6188 result.append("\t\t- Output configuration:\n");
6189 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6190 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6191 (uint32_t)mConfig.outputCfg.buffer.raw,
6192 mConfig.outputCfg.buffer.frameCount,
6193 mConfig.outputCfg.samplingRate,
6194 mConfig.outputCfg.channels,
6195 mConfig.outputCfg.format);
6196 result.append(buffer);
6197
6198 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6199 result.append(buffer);
6200 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6201 for (size_t i = 0; i < mHandles.size(); ++i) {
6202 sp<EffectHandle> handle = mHandles[i].promote();
6203 if (handle != 0) {
6204 handle->dump(buffer, SIZE);
6205 result.append(buffer);
6206 }
6207 }
6208
6209 result.append("\n");
6210
6211 write(fd, result.string(), result.length());
6212
6213 if (locked) {
6214 mLock.unlock();
6215 }
6216
6217 return NO_ERROR;
6218}
6219
6220// ----------------------------------------------------------------------------
6221// EffectHandle implementation
6222// ----------------------------------------------------------------------------
6223
6224#undef LOG_TAG
6225#define LOG_TAG "AudioFlinger::EffectHandle"
6226
6227AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6228 const sp<AudioFlinger::Client>& client,
6229 const sp<IEffectClient>& effectClient,
6230 int32_t priority)
6231 : BnEffect(),
6232 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
6233{
6234 LOGV("constructor %p", this);
6235
6236 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6237 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6238 if (mCblkMemory != 0) {
6239 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6240
6241 if (mCblk) {
6242 new(mCblk) effect_param_cblk_t();
6243 mBuffer = (uint8_t *)mCblk + bufOffset;
6244 }
6245 } else {
6246 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6247 return;
6248 }
6249}
6250
6251AudioFlinger::EffectHandle::~EffectHandle()
6252{
6253 LOGV("Destructor %p", this);
6254 disconnect();
6255}
6256
6257status_t AudioFlinger::EffectHandle::enable()
6258{
6259 if (!mHasControl) return INVALID_OPERATION;
6260 if (mEffect == 0) return DEAD_OBJECT;
6261
6262 return mEffect->setEnabled(true);
6263}
6264
6265status_t AudioFlinger::EffectHandle::disable()
6266{
6267 if (!mHasControl) return INVALID_OPERATION;
6268 if (mEffect == NULL) return DEAD_OBJECT;
6269
6270 return mEffect->setEnabled(false);
6271}
6272
6273void AudioFlinger::EffectHandle::disconnect()
6274{
6275 if (mEffect == 0) {
6276 return;
6277 }
6278 mEffect->disconnect(this);
6279 // release sp on module => module destructor can be called now
6280 mEffect.clear();
6281 if (mCblk) {
6282 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6283 }
6284 mCblkMemory.clear(); // and free the shared memory
6285 if (mClient != 0) {
6286 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6287 mClient.clear();
6288 }
6289}
6290
Eric Laurent25f43952010-07-28 05:40:18 -07006291status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6292 uint32_t cmdSize,
6293 void *pCmdData,
6294 uint32_t *replySize,
6295 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006296{
Eric Laurent25f43952010-07-28 05:40:18 -07006297// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6298// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006299
6300 // only get parameter command is permitted for applications not controlling the effect
6301 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6302 return INVALID_OPERATION;
6303 }
6304 if (mEffect == 0) return DEAD_OBJECT;
6305
6306 // handle commands that are not forwarded transparently to effect engine
6307 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6308 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6309 // no risk to block the whole media server process or mixer threads is we are stuck here
6310 Mutex::Autolock _l(mCblk->lock);
6311 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6312 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6313 mCblk->serverIndex = 0;
6314 mCblk->clientIndex = 0;
6315 return BAD_VALUE;
6316 }
6317 status_t status = NO_ERROR;
6318 while (mCblk->serverIndex < mCblk->clientIndex) {
6319 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006320 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006321 int *p = (int *)(mBuffer + mCblk->serverIndex);
6322 int size = *p++;
6323 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6324 LOGW("command(): invalid parameter block size");
6325 break;
6326 }
6327 effect_param_t *param = (effect_param_t *)p;
6328 if (param->psize == 0 || param->vsize == 0) {
6329 LOGW("command(): null parameter or value size");
6330 mCblk->serverIndex += size;
6331 continue;
6332 }
Eric Laurent25f43952010-07-28 05:40:18 -07006333 uint32_t psize = sizeof(effect_param_t) +
6334 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6335 param->vsize;
6336 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6337 psize,
6338 p,
6339 &rsize,
6340 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006341 // stop at first error encountered
6342 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006343 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006344 *(int *)pReplyData = reply;
6345 break;
6346 } else if (reply != NO_ERROR) {
6347 *(int *)pReplyData = reply;
6348 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006349 }
6350 mCblk->serverIndex += size;
6351 }
6352 mCblk->serverIndex = 0;
6353 mCblk->clientIndex = 0;
6354 return status;
6355 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006356 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006357 return enable();
6358 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006359 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006360 return disable();
6361 }
6362
6363 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6364}
6365
6366sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6367 return mCblkMemory;
6368}
6369
6370void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6371{
6372 LOGV("setControl %p control %d", this, hasControl);
6373
6374 mHasControl = hasControl;
6375 if (signal && mEffectClient != 0) {
6376 mEffectClient->controlStatusChanged(hasControl);
6377 }
6378}
6379
Eric Laurent25f43952010-07-28 05:40:18 -07006380void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6381 uint32_t cmdSize,
6382 void *pCmdData,
6383 uint32_t replySize,
6384 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006385{
6386 if (mEffectClient != 0) {
6387 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6388 }
6389}
6390
6391
6392
6393void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6394{
6395 if (mEffectClient != 0) {
6396 mEffectClient->enableStatusChanged(enabled);
6397 }
6398}
6399
6400status_t AudioFlinger::EffectHandle::onTransact(
6401 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6402{
6403 return BnEffect::onTransact(code, data, reply, flags);
6404}
6405
6406
6407void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6408{
6409 bool locked = tryLock(mCblk->lock);
6410
6411 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6412 (mClient == NULL) ? getpid() : mClient->pid(),
6413 mPriority,
6414 mHasControl,
6415 !locked,
6416 mCblk->clientIndex,
6417 mCblk->serverIndex
6418 );
6419
6420 if (locked) {
6421 mCblk->lock.unlock();
6422 }
6423}
6424
6425#undef LOG_TAG
6426#define LOG_TAG "AudioFlinger::EffectChain"
6427
6428AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6429 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006430 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6431 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6432 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433{
Dima Zavinfce7a472011-04-19 22:30:36 -07006434 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006435}
6436
6437AudioFlinger::EffectChain::~EffectChain()
6438{
6439 if (mOwnInBuffer) {
6440 delete mInBuffer;
6441 }
6442
6443}
6444
Eric Laurentcab11242010-07-15 12:50:15 -07006445// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6446sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006447{
6448 sp<EffectModule> effect;
6449 size_t size = mEffects.size();
6450
6451 for (size_t i = 0; i < size; i++) {
6452 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6453 effect = mEffects[i];
6454 break;
6455 }
6456 }
6457 return effect;
6458}
6459
Eric Laurentcab11242010-07-15 12:50:15 -07006460// getEffectFromId_l() must be called with PlaybackThread::mLock held
6461sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006462{
6463 sp<EffectModule> effect;
6464 size_t size = mEffects.size();
6465
6466 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006467 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6468 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006469 effect = mEffects[i];
6470 break;
6471 }
6472 }
6473 return effect;
6474}
6475
6476// Must be called with EffectChain::mLock locked
6477void AudioFlinger::EffectChain::process_l()
6478{
Eric Laurentdac69112010-09-28 14:09:57 -07006479 sp<ThreadBase> thread = mThread.promote();
6480 if (thread == 0) {
6481 LOGW("process_l(): cannot promote mixer thread");
6482 return;
6483 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006484 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6485 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07006486 bool tracksOnSession = false;
6487 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07006488 tracksOnSession = (trackCnt() != 0);
6489 }
6490
6491 // if no track is active, input buffer must be cleared here as the mixer process
6492 // will not do it
6493 if (tracksOnSession &&
6494 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006495 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07006496 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07006497 }
6498
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006500 // do not process effect if no track is present in same audio session
6501 if (isGlobalSession || tracksOnSession) {
6502 for (size_t i = 0; i < size; i++) {
6503 mEffects[i]->process();
6504 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006505 }
6506 for (size_t i = 0; i < size; i++) {
6507 mEffects[i]->updateState();
6508 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509}
6510
Eric Laurentcab11242010-07-15 12:50:15 -07006511// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006512status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513{
6514 effect_descriptor_t desc = effect->desc();
6515 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6516
6517 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006518 effect->setChain(this);
6519 sp<ThreadBase> thread = mThread.promote();
6520 if (thread == 0) {
6521 return NO_INIT;
6522 }
6523 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524
6525 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6526 // Auxiliary effects are inserted at the beginning of mEffects vector as
6527 // they are processed first and accumulated in chain input buffer
6528 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006529
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530 // the input buffer for auxiliary effect contains mono samples in
6531 // 32 bit format. This is to avoid saturation in AudoMixer
6532 // accumulation stage. Saturation is done in EffectModule::process() before
6533 // calling the process in effect engine
6534 size_t numSamples = thread->frameCount();
6535 int32_t *buffer = new int32_t[numSamples];
6536 memset(buffer, 0, numSamples * sizeof(int32_t));
6537 effect->setInBuffer((int16_t *)buffer);
6538 // auxiliary effects output samples to chain input buffer for further processing
6539 // by insert effects
6540 effect->setOutBuffer(mInBuffer);
6541 } else {
6542 // Insert effects are inserted at the end of mEffects vector as they are processed
6543 // after track and auxiliary effects.
6544 // Insert effect order as a function of indicated preference:
6545 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6546 // another effect is present
6547 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6548 // last effect claiming first position
6549 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6550 // first effect claiming last position
6551 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6552 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6553 // already present
6554
6555 int size = (int)mEffects.size();
6556 int idx_insert = size;
6557 int idx_insert_first = -1;
6558 int idx_insert_last = -1;
6559
6560 for (int i = 0; i < size; i++) {
6561 effect_descriptor_t d = mEffects[i]->desc();
6562 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6563 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6564 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6565 // check invalid effect chaining combinations
6566 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6567 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006568 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006569 return INVALID_OPERATION;
6570 }
6571 // remember position of first insert effect and by default
6572 // select this as insert position for new effect
6573 if (idx_insert == size) {
6574 idx_insert = i;
6575 }
6576 // remember position of last insert effect claiming
6577 // first position
6578 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6579 idx_insert_first = i;
6580 }
6581 // remember position of first insert effect claiming
6582 // last position
6583 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6584 idx_insert_last == -1) {
6585 idx_insert_last = i;
6586 }
6587 }
6588 }
6589
6590 // modify idx_insert from first position if needed
6591 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6592 if (idx_insert_last != -1) {
6593 idx_insert = idx_insert_last;
6594 } else {
6595 idx_insert = size;
6596 }
6597 } else {
6598 if (idx_insert_first != -1) {
6599 idx_insert = idx_insert_first + 1;
6600 }
6601 }
6602
6603 // always read samples from chain input buffer
6604 effect->setInBuffer(mInBuffer);
6605
6606 // if last effect in the chain, output samples to chain
6607 // output buffer, otherwise to chain input buffer
6608 if (idx_insert == size) {
6609 if (idx_insert != 0) {
6610 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6611 mEffects[idx_insert-1]->configure();
6612 }
6613 effect->setOutBuffer(mOutBuffer);
6614 } else {
6615 effect->setOutBuffer(mInBuffer);
6616 }
6617 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618
Eric Laurentcab11242010-07-15 12:50:15 -07006619 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006620 }
6621 effect->configure();
6622 return NO_ERROR;
6623}
6624
Eric Laurentcab11242010-07-15 12:50:15 -07006625// removeEffect_l() must be called with PlaybackThread::mLock held
6626size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006627{
6628 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629 int size = (int)mEffects.size();
6630 int i;
6631 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6632
6633 for (i = 0; i < size; i++) {
6634 if (effect == mEffects[i]) {
6635 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6636 delete[] effect->inBuffer();
6637 } else {
6638 if (i == size - 1 && i != 0) {
6639 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6640 mEffects[i - 1]->configure();
6641 }
6642 }
6643 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006644 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006645 break;
6646 }
6647 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648
6649 return mEffects.size();
6650}
6651
Eric Laurentcab11242010-07-15 12:50:15 -07006652// setDevice_l() must be called with PlaybackThread::mLock held
6653void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654{
6655 size_t size = mEffects.size();
6656 for (size_t i = 0; i < size; i++) {
6657 mEffects[i]->setDevice(device);
6658 }
6659}
6660
Eric Laurentcab11242010-07-15 12:50:15 -07006661// setMode_l() must be called with PlaybackThread::mLock held
6662void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006663{
6664 size_t size = mEffects.size();
6665 for (size_t i = 0; i < size; i++) {
6666 mEffects[i]->setMode(mode);
6667 }
6668}
6669
Eric Laurentcab11242010-07-15 12:50:15 -07006670// setVolume_l() must be called with PlaybackThread::mLock held
6671bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672{
6673 uint32_t newLeft = *left;
6674 uint32_t newRight = *right;
6675 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006676 int ctrlIdx = -1;
6677 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006678
Eric Laurentcab11242010-07-15 12:50:15 -07006679 // first update volume controller
6680 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006681 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006682 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6683 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006684 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006685 break;
6686 }
6687 }
6688
6689 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006690 if (hasControl) {
6691 *left = mNewLeftVolume;
6692 *right = mNewRightVolume;
6693 }
6694 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006695 }
6696
6697 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006698 mLeftVolume = newLeft;
6699 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006700
6701 // second get volume update from volume controller
6702 if (ctrlIdx >= 0) {
6703 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006704 mNewLeftVolume = newLeft;
6705 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006706 }
6707 // then indicate volume to all other effects in chain.
6708 // Pass altered volume to effects before volume controller
6709 // and requested volume to effects after controller
6710 uint32_t lVol = newLeft;
6711 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006712
Mathias Agopian65ab4712010-07-14 17:59:35 -07006713 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006714 if ((int)i == ctrlIdx) continue;
6715 // this also works for ctrlIdx == -1 when there is no volume controller
6716 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717 lVol = *left;
6718 rVol = *right;
6719 }
6720 mEffects[i]->setVolume(&lVol, &rVol, false);
6721 }
6722 *left = newLeft;
6723 *right = newRight;
6724
6725 return hasControl;
6726}
6727
Mathias Agopian65ab4712010-07-14 17:59:35 -07006728status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6729{
6730 const size_t SIZE = 256;
6731 char buffer[SIZE];
6732 String8 result;
6733
6734 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6735 result.append(buffer);
6736
6737 bool locked = tryLock(mLock);
6738 // failed to lock - AudioFlinger is probably deadlocked
6739 if (!locked) {
6740 result.append("\tCould not lock mutex:\n");
6741 }
6742
Eric Laurentcab11242010-07-15 12:50:15 -07006743 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6744 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006745 mEffects.size(),
6746 (uint32_t)mInBuffer,
6747 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006748 mActiveTrackCnt);
6749 result.append(buffer);
6750 write(fd, result.string(), result.size());
6751
6752 for (size_t i = 0; i < mEffects.size(); ++i) {
6753 sp<EffectModule> effect = mEffects[i];
6754 if (effect != 0) {
6755 effect->dump(fd, args);
6756 }
6757 }
6758
6759 if (locked) {
6760 mLock.unlock();
6761 }
6762
6763 return NO_ERROR;
6764}
6765
6766#undef LOG_TAG
6767#define LOG_TAG "AudioFlinger"
6768
6769// ----------------------------------------------------------------------------
6770
6771status_t AudioFlinger::onTransact(
6772 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6773{
6774 return BnAudioFlinger::onTransact(code, data, reply, flags);
6775}
6776
Mathias Agopian65ab4712010-07-14 17:59:35 -07006777}; // namespace android