blob: 64030615d66efc61837f34fce946ea8393c9c437 [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>
56// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
57
Mathias Agopian65ab4712010-07-14 17:59:35 -070058// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070059
Eric Laurentde070132010-07-13 04:45:46 -070060
Mathias Agopian65ab4712010-07-14 17:59:35 -070061namespace android {
62
63static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
64static const char* kHardwareLockedString = "Hardware lock is taken\n";
65
66//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
67static const float MAX_GAIN = 4096.0f;
68static const float MAX_GAIN_INT = 0x1000;
69
70// retry counts for buffer fill timeout
71// 50 * ~20msecs = 1 second
72static const int8_t kMaxTrackRetries = 50;
73static const int8_t kMaxTrackStartupRetries = 50;
74// allow less retry attempts on direct output thread.
75// direct outputs can be a scarce resource in audio hardware and should
76// be released as quickly as possible.
77static const int8_t kMaxTrackRetriesDirect = 2;
78
79static const int kDumpLockRetries = 50;
80static const int kDumpLockSleep = 20000;
81
82static const nsecs_t kWarningThrottle = seconds(5);
83
Eric Laurent7c7f10b2011-06-17 21:29:58 -070084// RecordThread loop sleep time upon application overrun or audio HAL read error
85static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Mathias Agopian65ab4712010-07-14 17:59:35 -070087// ----------------------------------------------------------------------------
88
89static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070090 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
91 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
92 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
93 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070094}
95
96static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070097 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
98 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
99 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
100 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700101}
102
Gloria Wang9ee159b2011-02-24 14:51:45 -0800103// To collect the amplifier usage
104static void addBatteryData(uint32_t params) {
105 sp<IBinder> binder =
106 defaultServiceManager()->getService(String16("media.player"));
107 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
108 if (service.get() == NULL) {
109 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
110 return;
111 }
112
113 service->addBatteryData(params);
114}
115
Dima Zavin799a70e2011-04-18 16:57:27 -0700116static int load_audio_interface(const char *if_name, const hw_module_t **mod,
117 audio_hw_device_t **dev)
118{
119 int rc;
120
121 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
122 if (rc)
123 goto out;
124
125 rc = audio_hw_device_open(*mod, dev);
126 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
127 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
128 if (rc)
129 goto out;
130
131 return 0;
132
133out:
134 *mod = NULL;
135 *dev = NULL;
136 return rc;
137}
138
139static const char *audio_interfaces[] = {
140 "primary",
141 "a2dp",
142 "usb",
143};
144#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
148AudioFlinger::AudioFlinger()
149 : BnAudioFlinger(),
Dima Zavin799a70e2011-04-18 16:57:27 -0700150 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700151{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700152}
153
154void AudioFlinger::onFirstRef()
155{
Dima Zavin799a70e2011-04-18 16:57:27 -0700156 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700157
Eric Laurent93575202011-01-18 18:39:02 -0800158 Mutex::Autolock _l(mLock);
159
Dima Zavin799a70e2011-04-18 16:57:27 -0700160 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161 mHardwareStatus = AUDIO_HW_IDLE;
162
Dima Zavin799a70e2011-04-18 16:57:27 -0700163 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
164 const hw_module_t *mod;
165 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700166
Dima Zavin799a70e2011-04-18 16:57:27 -0700167 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
168 if (rc)
169 continue;
170
171 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
172 mod->name, mod->id);
173 mAudioHwDevs.push(dev);
174
175 if (!mPrimaryHardwareDev) {
176 mPrimaryHardwareDev = dev;
177 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700178 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 }
180 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700181
182 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
185 LOGE("Primary audio interface not found");
186 return;
187 }
188
189 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
190 audio_hw_device_t *dev = mAudioHwDevs[i];
191
192 mHardwareStatus = AUDIO_HW_INIT;
193 rc = dev->init_check(dev);
194 if (rc == 0) {
195 AutoMutex lock(mHardwareLock);
196
197 mMode = AUDIO_MODE_NORMAL;
198 mHardwareStatus = AUDIO_HW_SET_MODE;
199 dev->set_mode(dev, mMode);
200 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
201 dev->set_master_volume(dev, 1.0f);
202 mHardwareStatus = AUDIO_HW_IDLE;
203 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700205}
206
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700207status_t AudioFlinger::initCheck() const
208{
209 Mutex::Autolock _l(mLock);
210 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
211 return NO_INIT;
212 return NO_ERROR;
213}
214
Mathias Agopian65ab4712010-07-14 17:59:35 -0700215AudioFlinger::~AudioFlinger()
216{
Dima Zavin799a70e2011-04-18 16:57:27 -0700217 int num_devs = mAudioHwDevs.size();
218
Mathias Agopian65ab4712010-07-14 17:59:35 -0700219 while (!mRecordThreads.isEmpty()) {
220 // closeInput() will remove first entry from mRecordThreads
221 closeInput(mRecordThreads.keyAt(0));
222 }
223 while (!mPlaybackThreads.isEmpty()) {
224 // closeOutput() will remove first entry from mPlaybackThreads
225 closeOutput(mPlaybackThreads.keyAt(0));
226 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700227
228 for (int i = 0; i < num_devs; i++) {
229 audio_hw_device_t *dev = mAudioHwDevs[i];
230 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700232 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233}
234
Dima Zavin799a70e2011-04-18 16:57:27 -0700235audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
236{
237 /* first matching HW device is returned */
238 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
239 audio_hw_device_t *dev = mAudioHwDevs[i];
240 if ((dev->get_supported_devices(dev) & devices) == devices)
241 return dev;
242 }
243 return NULL;
244}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700245
246status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
247{
248 const size_t SIZE = 256;
249 char buffer[SIZE];
250 String8 result;
251
252 result.append("Clients:\n");
253 for (size_t i = 0; i < mClients.size(); ++i) {
254 wp<Client> wClient = mClients.valueAt(i);
255 if (wClient != 0) {
256 sp<Client> client = wClient.promote();
257 if (client != 0) {
258 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
259 result.append(buffer);
260 }
261 }
262 }
263 write(fd, result.string(), result.size());
264 return NO_ERROR;
265}
266
267
268status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
269{
270 const size_t SIZE = 256;
271 char buffer[SIZE];
272 String8 result;
273 int hardwareStatus = mHardwareStatus;
274
275 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
276 result.append(buffer);
277 write(fd, result.string(), result.size());
278 return NO_ERROR;
279}
280
281status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
282{
283 const size_t SIZE = 256;
284 char buffer[SIZE];
285 String8 result;
286 snprintf(buffer, SIZE, "Permission Denial: "
287 "can't dump AudioFlinger from pid=%d, uid=%d\n",
288 IPCThreadState::self()->getCallingPid(),
289 IPCThreadState::self()->getCallingUid());
290 result.append(buffer);
291 write(fd, result.string(), result.size());
292 return NO_ERROR;
293}
294
295static bool tryLock(Mutex& mutex)
296{
297 bool locked = false;
298 for (int i = 0; i < kDumpLockRetries; ++i) {
299 if (mutex.tryLock() == NO_ERROR) {
300 locked = true;
301 break;
302 }
303 usleep(kDumpLockSleep);
304 }
305 return locked;
306}
307
308status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
309{
310 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
311 dumpPermissionDenial(fd, args);
312 } else {
313 // get state of hardware lock
314 bool hardwareLocked = tryLock(mHardwareLock);
315 if (!hardwareLocked) {
316 String8 result(kHardwareLockedString);
317 write(fd, result.string(), result.size());
318 } else {
319 mHardwareLock.unlock();
320 }
321
322 bool locked = tryLock(mLock);
323
324 // failed to lock - AudioFlinger is probably deadlocked
325 if (!locked) {
326 String8 result(kDeadlockedString);
327 write(fd, result.string(), result.size());
328 }
329
330 dumpClients(fd, args);
331 dumpInternals(fd, args);
332
333 // dump playback threads
334 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
335 mPlaybackThreads.valueAt(i)->dump(fd, args);
336 }
337
338 // dump record threads
339 for (size_t i = 0; i < mRecordThreads.size(); i++) {
340 mRecordThreads.valueAt(i)->dump(fd, args);
341 }
342
Dima Zavin799a70e2011-04-18 16:57:27 -0700343 // dump all hardware devs
344 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
345 audio_hw_device_t *dev = mAudioHwDevs[i];
346 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347 }
348 if (locked) mLock.unlock();
349 }
350 return NO_ERROR;
351}
352
353
354// IAudioFlinger interface
355
356
357sp<IAudioTrack> AudioFlinger::createTrack(
358 pid_t pid,
359 int streamType,
360 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700361 uint32_t format,
362 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700363 int frameCount,
364 uint32_t flags,
365 const sp<IMemory>& sharedBuffer,
366 int output,
367 int *sessionId,
368 status_t *status)
369{
370 sp<PlaybackThread::Track> track;
371 sp<TrackHandle> trackHandle;
372 sp<Client> client;
373 wp<Client> wclient;
374 status_t lStatus;
375 int lSessionId;
376
Dima Zavinfce7a472011-04-19 22:30:36 -0700377 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700378 LOGE("invalid stream type");
379 lStatus = BAD_VALUE;
380 goto Exit;
381 }
382
383 {
384 Mutex::Autolock _l(mLock);
385 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700386 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 if (thread == NULL) {
388 LOGE("unknown output thread");
389 lStatus = BAD_VALUE;
390 goto Exit;
391 }
392
393 wclient = mClients.valueFor(pid);
394
395 if (wclient != NULL) {
396 client = wclient.promote();
397 } else {
398 client = new Client(this, pid);
399 mClients.add(pid, client);
400 }
401
Mathias Agopian65ab4712010-07-14 17:59:35 -0700402 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700403 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700404 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700405 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
406 if (mPlaybackThreads.keyAt(i) != output) {
407 // prevent same audio session on different output threads
408 uint32_t sessions = t->hasAudioSession(*sessionId);
409 if (sessions & PlaybackThread::TRACK_SESSION) {
410 lStatus = BAD_VALUE;
411 goto Exit;
412 }
413 // check if an effect with same session ID is waiting for a track to be created
414 if (sessions & PlaybackThread::EFFECT_SESSION) {
415 effectThread = t.get();
416 }
Eric Laurentde070132010-07-13 04:45:46 -0700417 }
418 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 lSessionId = *sessionId;
420 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700421 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700422 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700423 if (sessionId != NULL) {
424 *sessionId = lSessionId;
425 }
426 }
427 LOGV("createTrack() lSessionId: %d", lSessionId);
428
429 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700430 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700431
432 // move effect chain to this output thread if an effect on same session was waiting
433 // for a track to be created
434 if (lStatus == NO_ERROR && effectThread != NULL) {
435 Mutex::Autolock _dl(thread->mLock);
436 Mutex::Autolock _sl(effectThread->mLock);
437 moveEffectChain_l(lSessionId, effectThread, thread, true);
438 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700439 }
440 if (lStatus == NO_ERROR) {
441 trackHandle = new TrackHandle(track);
442 } else {
443 // remove local strong reference to Client before deleting the Track so that the Client
444 // destructor is called by the TrackBase destructor with mLock held
445 client.clear();
446 track.clear();
447 }
448
449Exit:
450 if(status) {
451 *status = lStatus;
452 }
453 return trackHandle;
454}
455
456uint32_t AudioFlinger::sampleRate(int output) const
457{
458 Mutex::Autolock _l(mLock);
459 PlaybackThread *thread = checkPlaybackThread_l(output);
460 if (thread == NULL) {
461 LOGW("sampleRate() unknown thread %d", output);
462 return 0;
463 }
464 return thread->sampleRate();
465}
466
467int AudioFlinger::channelCount(int output) const
468{
469 Mutex::Autolock _l(mLock);
470 PlaybackThread *thread = checkPlaybackThread_l(output);
471 if (thread == NULL) {
472 LOGW("channelCount() unknown thread %d", output);
473 return 0;
474 }
475 return thread->channelCount();
476}
477
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700478uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479{
480 Mutex::Autolock _l(mLock);
481 PlaybackThread *thread = checkPlaybackThread_l(output);
482 if (thread == NULL) {
483 LOGW("format() unknown thread %d", output);
484 return 0;
485 }
486 return thread->format();
487}
488
489size_t AudioFlinger::frameCount(int output) const
490{
491 Mutex::Autolock _l(mLock);
492 PlaybackThread *thread = checkPlaybackThread_l(output);
493 if (thread == NULL) {
494 LOGW("frameCount() unknown thread %d", output);
495 return 0;
496 }
497 return thread->frameCount();
498}
499
500uint32_t AudioFlinger::latency(int output) const
501{
502 Mutex::Autolock _l(mLock);
503 PlaybackThread *thread = checkPlaybackThread_l(output);
504 if (thread == NULL) {
505 LOGW("latency() unknown thread %d", output);
506 return 0;
507 }
508 return thread->latency();
509}
510
511status_t AudioFlinger::setMasterVolume(float value)
512{
513 // check calling permissions
514 if (!settingsAllowed()) {
515 return PERMISSION_DENIED;
516 }
517
518 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800519 { // scope for the lock
520 AutoMutex lock(mHardwareLock);
521 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700522 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800523 value = 1.0f;
524 }
525 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527
Eric Laurent93575202011-01-18 18:39:02 -0800528 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529 mMasterVolume = value;
530 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
531 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
532
533 return NO_ERROR;
534}
535
536status_t AudioFlinger::setMode(int mode)
537{
538 status_t ret;
539
540 // check calling permissions
541 if (!settingsAllowed()) {
542 return PERMISSION_DENIED;
543 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700544 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700545 LOGW("Illegal value: setMode(%d)", mode);
546 return BAD_VALUE;
547 }
548
549 { // scope for the lock
550 AutoMutex lock(mHardwareLock);
551 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700552 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700553 mHardwareStatus = AUDIO_HW_IDLE;
554 }
555
556 if (NO_ERROR == ret) {
557 Mutex::Autolock _l(mLock);
558 mMode = mode;
559 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
560 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700561 }
562
563 return ret;
564}
565
566status_t AudioFlinger::setMicMute(bool state)
567{
568 // check calling permissions
569 if (!settingsAllowed()) {
570 return PERMISSION_DENIED;
571 }
572
573 AutoMutex lock(mHardwareLock);
574 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700575 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700576 mHardwareStatus = AUDIO_HW_IDLE;
577 return ret;
578}
579
580bool AudioFlinger::getMicMute() const
581{
Dima Zavinfce7a472011-04-19 22:30:36 -0700582 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700583 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700584 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 mHardwareStatus = AUDIO_HW_IDLE;
586 return state;
587}
588
589status_t AudioFlinger::setMasterMute(bool muted)
590{
591 // check calling permissions
592 if (!settingsAllowed()) {
593 return PERMISSION_DENIED;
594 }
595
Eric Laurent93575202011-01-18 18:39:02 -0800596 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597 mMasterMute = muted;
598 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
599 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
600
601 return NO_ERROR;
602}
603
604float AudioFlinger::masterVolume() const
605{
606 return mMasterVolume;
607}
608
609bool AudioFlinger::masterMute() const
610{
611 return mMasterMute;
612}
613
614status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
615{
616 // check calling permissions
617 if (!settingsAllowed()) {
618 return PERMISSION_DENIED;
619 }
620
Dima Zavinfce7a472011-04-19 22:30:36 -0700621 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700622 return BAD_VALUE;
623 }
624
625 AutoMutex lock(mLock);
626 PlaybackThread *thread = NULL;
627 if (output) {
628 thread = checkPlaybackThread_l(output);
629 if (thread == NULL) {
630 return BAD_VALUE;
631 }
632 }
633
634 mStreamTypes[stream].volume = value;
635
636 if (thread == NULL) {
637 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
638 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
639 }
640 } else {
641 thread->setStreamVolume(stream, value);
642 }
643
644 return NO_ERROR;
645}
646
647status_t AudioFlinger::setStreamMute(int stream, bool muted)
648{
649 // check calling permissions
650 if (!settingsAllowed()) {
651 return PERMISSION_DENIED;
652 }
653
Dima Zavinfce7a472011-04-19 22:30:36 -0700654 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
655 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700656 return BAD_VALUE;
657 }
658
Eric Laurent93575202011-01-18 18:39:02 -0800659 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700660 mStreamTypes[stream].mute = muted;
661 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
662 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
663
664 return NO_ERROR;
665}
666
667float AudioFlinger::streamVolume(int stream, int output) const
668{
Dima Zavinfce7a472011-04-19 22:30:36 -0700669 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700670 return 0.0f;
671 }
672
673 AutoMutex lock(mLock);
674 float volume;
675 if (output) {
676 PlaybackThread *thread = checkPlaybackThread_l(output);
677 if (thread == NULL) {
678 return 0.0f;
679 }
680 volume = thread->streamVolume(stream);
681 } else {
682 volume = mStreamTypes[stream].volume;
683 }
684
685 return volume;
686}
687
688bool AudioFlinger::streamMute(int stream) const
689{
Dima Zavinfce7a472011-04-19 22:30:36 -0700690 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700691 return true;
692 }
693
694 return mStreamTypes[stream].mute;
695}
696
Mathias Agopian65ab4712010-07-14 17:59:35 -0700697status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
698{
699 status_t result;
700
701 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
702 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
703 // check calling permissions
704 if (!settingsAllowed()) {
705 return PERMISSION_DENIED;
706 }
707
Mathias Agopian65ab4712010-07-14 17:59:35 -0700708 // ioHandle == 0 means the parameters are global to the audio hardware interface
709 if (ioHandle == 0) {
710 AutoMutex lock(mHardwareLock);
711 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700712 status_t final_result = NO_ERROR;
713 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
714 audio_hw_device_t *dev = mAudioHwDevs[i];
715 result = dev->set_parameters(dev, keyValuePairs.string());
716 final_result = result ?: final_result;
717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700718 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700719 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720 }
721
722 // hold a strong ref on thread in case closeOutput() or closeInput() is called
723 // and the thread is exited once the lock is released
724 sp<ThreadBase> thread;
725 {
726 Mutex::Autolock _l(mLock);
727 thread = checkPlaybackThread_l(ioHandle);
728 if (thread == NULL) {
729 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700730 } else if (thread.get() == primaryPlaybackThread_l()) {
731 // indicate output device change to all input threads for pre processing
732 AudioParameter param = AudioParameter(keyValuePairs);
733 int value;
734 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
735 for (size_t i = 0; i < mRecordThreads.size(); i++) {
736 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
737 }
738 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739 }
740 }
741 if (thread != NULL) {
742 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743 return result;
744 }
745 return BAD_VALUE;
746}
747
748String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
749{
750// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
751// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
752
753 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700754 String8 out_s8;
755
Dima Zavin799a70e2011-04-18 16:57:27 -0700756 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
757 audio_hw_device_t *dev = mAudioHwDevs[i];
758 char *s = dev->get_parameters(dev, keys.string());
759 out_s8 += String8(s);
760 free(s);
761 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700762 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 }
764
765 Mutex::Autolock _l(mLock);
766
767 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
768 if (playbackThread != NULL) {
769 return playbackThread->getParameters(keys);
770 }
771 RecordThread *recordThread = checkRecordThread_l(ioHandle);
772 if (recordThread != NULL) {
773 return recordThread->getParameters(keys);
774 }
775 return String8("");
776}
777
778size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
779{
Dima Zavin799a70e2011-04-18 16:57:27 -0700780 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700781}
782
783unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
784{
785 if (ioHandle == 0) {
786 return 0;
787 }
788
789 Mutex::Autolock _l(mLock);
790
791 RecordThread *recordThread = checkRecordThread_l(ioHandle);
792 if (recordThread != NULL) {
793 return recordThread->getInputFramesLost();
794 }
795 return 0;
796}
797
798status_t AudioFlinger::setVoiceVolume(float value)
799{
800 // check calling permissions
801 if (!settingsAllowed()) {
802 return PERMISSION_DENIED;
803 }
804
805 AutoMutex lock(mHardwareLock);
806 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700807 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 mHardwareStatus = AUDIO_HW_IDLE;
809
810 return ret;
811}
812
813status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
814{
815 status_t status;
816
817 Mutex::Autolock _l(mLock);
818
819 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
820 if (playbackThread != NULL) {
821 return playbackThread->getRenderPosition(halFrames, dspFrames);
822 }
823
824 return BAD_VALUE;
825}
826
827void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
828{
829
830 Mutex::Autolock _l(mLock);
831
832 int pid = IPCThreadState::self()->getCallingPid();
833 if (mNotificationClients.indexOfKey(pid) < 0) {
834 sp<NotificationClient> notificationClient = new NotificationClient(this,
835 client,
836 pid);
837 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
838
839 mNotificationClients.add(pid, notificationClient);
840
841 sp<IBinder> binder = client->asBinder();
842 binder->linkToDeath(notificationClient);
843
844 // the config change is always sent from playback or record threads to avoid deadlock
845 // with AudioSystem::gLock
846 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
847 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
848 }
849
850 for (size_t i = 0; i < mRecordThreads.size(); i++) {
851 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
852 }
853 }
854}
855
856void AudioFlinger::removeNotificationClient(pid_t pid)
857{
858 Mutex::Autolock _l(mLock);
859
860 int index = mNotificationClients.indexOfKey(pid);
861 if (index >= 0) {
862 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
863 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 mNotificationClients.removeItem(pid);
865 }
866}
867
868// audioConfigChanged_l() must be called with AudioFlinger::mLock held
869void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
870{
871 size_t size = mNotificationClients.size();
872 for (size_t i = 0; i < size; i++) {
873 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
874 }
875}
876
877// removeClient_l() must be called with AudioFlinger::mLock held
878void AudioFlinger::removeClient_l(pid_t pid)
879{
880 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
881 mClients.removeItem(pid);
882}
883
884
885// ----------------------------------------------------------------------------
886
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700887AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 : Thread(false),
889 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700890 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false), mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700891{
892}
893
894AudioFlinger::ThreadBase::~ThreadBase()
895{
896 mParamCond.broadcast();
897 mNewParameters.clear();
898}
899
900void AudioFlinger::ThreadBase::exit()
901{
902 // keep a strong ref on ourself so that we wont get
903 // destroyed in the middle of requestExitAndWait()
904 sp <ThreadBase> strongMe = this;
905
906 LOGV("ThreadBase::exit");
907 {
908 AutoMutex lock(&mLock);
909 mExiting = true;
910 requestExit();
911 mWaitWorkCV.signal();
912 }
913 requestExitAndWait();
914}
915
916uint32_t AudioFlinger::ThreadBase::sampleRate() const
917{
918 return mSampleRate;
919}
920
921int AudioFlinger::ThreadBase::channelCount() const
922{
923 return (int)mChannelCount;
924}
925
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700926uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700927{
928 return mFormat;
929}
930
931size_t AudioFlinger::ThreadBase::frameCount() const
932{
933 return mFrameCount;
934}
935
936status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
937{
938 status_t status;
939
940 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
941 Mutex::Autolock _l(mLock);
942
943 mNewParameters.add(keyValuePairs);
944 mWaitWorkCV.signal();
945 // wait condition with timeout in case the thread loop has exited
946 // before the request could be processed
947 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
948 status = mParamStatus;
949 mWaitWorkCV.signal();
950 } else {
951 status = TIMED_OUT;
952 }
953 return status;
954}
955
956void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
957{
958 Mutex::Autolock _l(mLock);
959 sendConfigEvent_l(event, param);
960}
961
962// sendConfigEvent_l() must be called with ThreadBase::mLock held
963void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
964{
965 ConfigEvent *configEvent = new ConfigEvent();
966 configEvent->mEvent = event;
967 configEvent->mParam = param;
968 mConfigEvents.add(configEvent);
969 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
970 mWaitWorkCV.signal();
971}
972
973void AudioFlinger::ThreadBase::processConfigEvents()
974{
975 mLock.lock();
976 while(!mConfigEvents.isEmpty()) {
977 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
978 ConfigEvent *configEvent = mConfigEvents[0];
979 mConfigEvents.removeAt(0);
980 // release mLock before locking AudioFlinger mLock: lock order is always
981 // AudioFlinger then ThreadBase to avoid cross deadlock
982 mLock.unlock();
983 mAudioFlinger->mLock.lock();
984 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
985 mAudioFlinger->mLock.unlock();
986 delete configEvent;
987 mLock.lock();
988 }
989 mLock.unlock();
990}
991
992status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
993{
994 const size_t SIZE = 256;
995 char buffer[SIZE];
996 String8 result;
997
998 bool locked = tryLock(mLock);
999 if (!locked) {
1000 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1001 write(fd, buffer, strlen(buffer));
1002 }
1003
1004 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1005 result.append(buffer);
1006 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1007 result.append(buffer);
1008 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1009 result.append(buffer);
1010 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1011 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001012 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1013 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1015 result.append(buffer);
1016 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1017 result.append(buffer);
1018
1019 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1020 result.append(buffer);
1021 result.append(" Index Command");
1022 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1023 snprintf(buffer, SIZE, "\n %02d ", i);
1024 result.append(buffer);
1025 result.append(mNewParameters[i]);
1026 }
1027
1028 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1029 result.append(buffer);
1030 snprintf(buffer, SIZE, " Index event param\n");
1031 result.append(buffer);
1032 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1033 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1034 result.append(buffer);
1035 }
1036 result.append("\n");
1037
1038 write(fd, result.string(), result.size());
1039
1040 if (locked) {
1041 mLock.unlock();
1042 }
1043 return NO_ERROR;
1044}
1045
Eric Laurent1d2bff02011-07-24 17:49:51 -07001046status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1047{
1048 const size_t SIZE = 256;
1049 char buffer[SIZE];
1050 String8 result;
1051
1052 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1053 write(fd, buffer, strlen(buffer));
1054
1055 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1056 sp<EffectChain> chain = mEffectChains[i];
1057 if (chain != 0) {
1058 chain->dump(fd, args);
1059 }
1060 }
1061 return NO_ERROR;
1062}
1063
1064
Mathias Agopian65ab4712010-07-14 17:59:35 -07001065// ----------------------------------------------------------------------------
1066
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001067AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1068 AudioStreamOut* output,
1069 int id,
1070 uint32_t device)
1071 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001072 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001073 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074{
1075 readOutputParameters();
1076
1077 mMasterVolume = mAudioFlinger->masterVolume();
1078 mMasterMute = mAudioFlinger->masterMute();
1079
Dima Zavinfce7a472011-04-19 22:30:36 -07001080 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001081 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1082 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1083 }
1084}
1085
1086AudioFlinger::PlaybackThread::~PlaybackThread()
1087{
1088 delete [] mMixBuffer;
1089}
1090
1091status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1092{
1093 dumpInternals(fd, args);
1094 dumpTracks(fd, args);
1095 dumpEffectChains(fd, args);
1096 return NO_ERROR;
1097}
1098
1099status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1100{
1101 const size_t SIZE = 256;
1102 char buffer[SIZE];
1103 String8 result;
1104
1105 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1106 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001107 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 -07001108 for (size_t i = 0; i < mTracks.size(); ++i) {
1109 sp<Track> track = mTracks[i];
1110 if (track != 0) {
1111 track->dump(buffer, SIZE);
1112 result.append(buffer);
1113 }
1114 }
1115
1116 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1117 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001118 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 -07001119 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1120 wp<Track> wTrack = mActiveTracks[i];
1121 if (wTrack != 0) {
1122 sp<Track> track = wTrack.promote();
1123 if (track != 0) {
1124 track->dump(buffer, SIZE);
1125 result.append(buffer);
1126 }
1127 }
1128 }
1129 write(fd, result.string(), result.size());
1130 return NO_ERROR;
1131}
1132
Mathias Agopian65ab4712010-07-14 17:59:35 -07001133status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1134{
1135 const size_t SIZE = 256;
1136 char buffer[SIZE];
1137 String8 result;
1138
1139 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1140 result.append(buffer);
1141 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1142 result.append(buffer);
1143 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1144 result.append(buffer);
1145 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1146 result.append(buffer);
1147 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1148 result.append(buffer);
1149 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1150 result.append(buffer);
1151 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1152 result.append(buffer);
1153 write(fd, result.string(), result.size());
1154
1155 dumpBase(fd, args);
1156
1157 return NO_ERROR;
1158}
1159
1160// Thread virtuals
1161status_t AudioFlinger::PlaybackThread::readyToRun()
1162{
1163 if (mSampleRate == 0) {
1164 LOGE("No working audio driver found.");
1165 return NO_INIT;
1166 }
1167 LOGI("AudioFlinger's thread %p ready to run", this);
1168 return NO_ERROR;
1169}
1170
1171void AudioFlinger::PlaybackThread::onFirstRef()
1172{
1173 const size_t SIZE = 256;
1174 char buffer[SIZE];
1175
1176 snprintf(buffer, SIZE, "Playback Thread %p", this);
1177
1178 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1179}
1180
1181// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1182sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1183 const sp<AudioFlinger::Client>& client,
1184 int streamType,
1185 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001186 uint32_t format,
1187 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001188 int frameCount,
1189 const sp<IMemory>& sharedBuffer,
1190 int sessionId,
1191 status_t *status)
1192{
1193 sp<Track> track;
1194 status_t lStatus;
1195
1196 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001197 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1198 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1199 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1200 "for output %p with format %d",
1201 sampleRate, format, channelMask, mOutput, mFormat);
1202 lStatus = BAD_VALUE;
1203 goto Exit;
1204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001205 }
1206 } else {
1207 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1208 if (sampleRate > mSampleRate*2) {
1209 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1210 lStatus = BAD_VALUE;
1211 goto Exit;
1212 }
1213 }
1214
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001215 lStatus = initCheck();
1216 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001217 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001218 goto Exit;
1219 }
1220
1221 { // scope for mLock
1222 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001223
1224 // all tracks in same audio session must share the same routing strategy otherwise
1225 // conflicts will happen when tracks are moved from one output to another by audio policy
1226 // manager
1227 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001228 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001229 for (size_t i = 0; i < mTracks.size(); ++i) {
1230 sp<Track> t = mTracks[i];
1231 if (t != 0) {
1232 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001233 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001234 lStatus = BAD_VALUE;
1235 goto Exit;
1236 }
1237 }
1238 }
1239
Mathias Agopian65ab4712010-07-14 17:59:35 -07001240 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001241 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001242 if (track->getCblk() == NULL || track->name() < 0) {
1243 lStatus = NO_MEMORY;
1244 goto Exit;
1245 }
1246 mTracks.add(track);
1247
1248 sp<EffectChain> chain = getEffectChain_l(sessionId);
1249 if (chain != 0) {
1250 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1251 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001252 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001253 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001254 }
1255 }
1256 lStatus = NO_ERROR;
1257
1258Exit:
1259 if(status) {
1260 *status = lStatus;
1261 }
1262 return track;
1263}
1264
1265uint32_t AudioFlinger::PlaybackThread::latency() const
1266{
1267 if (mOutput) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001268 return mOutput->stream->get_latency(mOutput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001269 }
1270 else {
1271 return 0;
1272 }
1273}
1274
1275status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1276{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001277 mMasterVolume = value;
1278 return NO_ERROR;
1279}
1280
1281status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1282{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001283 mMasterMute = muted;
1284 return NO_ERROR;
1285}
1286
1287float AudioFlinger::PlaybackThread::masterVolume() const
1288{
1289 return mMasterVolume;
1290}
1291
1292bool AudioFlinger::PlaybackThread::masterMute() const
1293{
1294 return mMasterMute;
1295}
1296
1297status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1298{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001299 mStreamTypes[stream].volume = value;
1300 return NO_ERROR;
1301}
1302
1303status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1304{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001305 mStreamTypes[stream].mute = muted;
1306 return NO_ERROR;
1307}
1308
1309float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1310{
1311 return mStreamTypes[stream].volume;
1312}
1313
1314bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1315{
1316 return mStreamTypes[stream].mute;
1317}
1318
Mathias Agopian65ab4712010-07-14 17:59:35 -07001319// addTrack_l() must be called with ThreadBase::mLock held
1320status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1321{
1322 status_t status = ALREADY_EXISTS;
1323
1324 // set retry count for buffer fill
1325 track->mRetryCount = kMaxTrackStartupRetries;
1326 if (mActiveTracks.indexOf(track) < 0) {
1327 // the track is newly added, make sure it fills up all its
1328 // buffers before playing. This is to ensure the client will
1329 // effectively get the latency it requested.
1330 track->mFillingUpStatus = Track::FS_FILLING;
1331 track->mResetDone = false;
1332 mActiveTracks.add(track);
1333 if (track->mainBuffer() != mMixBuffer) {
1334 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1335 if (chain != 0) {
1336 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001337 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001338 }
1339 }
1340
1341 status = NO_ERROR;
1342 }
1343
1344 LOGV("mWaitWorkCV.broadcast");
1345 mWaitWorkCV.broadcast();
1346
1347 return status;
1348}
1349
1350// destroyTrack_l() must be called with ThreadBase::mLock held
1351void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1352{
1353 track->mState = TrackBase::TERMINATED;
1354 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001355 removeTrack_l(track);
1356 }
1357}
1358
1359void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1360{
1361 mTracks.remove(track);
1362 deleteTrackName_l(track->name());
1363 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1364 if (chain != 0) {
1365 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001366 }
1367}
1368
1369String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1370{
Dima Zavinfce7a472011-04-19 22:30:36 -07001371 String8 out_s8;
1372 char *s;
1373
Dima Zavin799a70e2011-04-18 16:57:27 -07001374 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001375 out_s8 = String8(s);
1376 free(s);
1377 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378}
1379
1380// destroyTrack_l() must be called with AudioFlinger::mLock held
1381void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1382 AudioSystem::OutputDescriptor desc;
1383 void *param2 = 0;
1384
1385 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1386
1387 switch (event) {
1388 case AudioSystem::OUTPUT_OPENED:
1389 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001390 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001391 desc.samplingRate = mSampleRate;
1392 desc.format = mFormat;
1393 desc.frameCount = mFrameCount;
1394 desc.latency = latency();
1395 param2 = &desc;
1396 break;
1397
1398 case AudioSystem::STREAM_CONFIG_CHANGED:
1399 param2 = &param;
1400 case AudioSystem::OUTPUT_CLOSED:
1401 default:
1402 break;
1403 }
1404 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1405}
1406
1407void AudioFlinger::PlaybackThread::readOutputParameters()
1408{
Dima Zavin799a70e2011-04-18 16:57:27 -07001409 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001410 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1411 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001412 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1413 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1414 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415
1416 // FIXME - Current mixer implementation only supports stereo output: Always
1417 // Allocate a stereo buffer even if HW output is mono.
1418 if (mMixBuffer != NULL) delete[] mMixBuffer;
1419 mMixBuffer = new int16_t[mFrameCount * 2];
1420 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1421
Eric Laurentde070132010-07-13 04:45:46 -07001422 // force reconfiguration of effect chains and engines to take new buffer size and audio
1423 // parameters into account
1424 // Note that mLock is not held when readOutputParameters() is called from the constructor
1425 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1426 // matter.
1427 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1428 Vector< sp<EffectChain> > effectChains = mEffectChains;
1429 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001430 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001431 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001432}
1433
1434status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1435{
1436 if (halFrames == 0 || dspFrames == 0) {
1437 return BAD_VALUE;
1438 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001439 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 return INVALID_OPERATION;
1441 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001442 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443
Dima Zavin799a70e2011-04-18 16:57:27 -07001444 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001445}
1446
Eric Laurent39e94f82010-07-28 01:32:47 -07001447uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001448{
1449 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001450 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001451 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001452 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 }
1454
1455 for (size_t i = 0; i < mTracks.size(); ++i) {
1456 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001457 if (sessionId == track->sessionId() &&
1458 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001459 result |= TRACK_SESSION;
1460 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001461 }
1462 }
1463
Eric Laurent39e94f82010-07-28 01:32:47 -07001464 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001465}
1466
Eric Laurentde070132010-07-13 04:45:46 -07001467uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1468{
Dima Zavinfce7a472011-04-19 22:30:36 -07001469 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001470 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001471 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1472 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001473 }
1474 for (size_t i = 0; i < mTracks.size(); i++) {
1475 sp<Track> track = mTracks[i];
1476 if (sessionId == track->sessionId() &&
1477 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001478 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001479 }
1480 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001481 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001482}
1483
Mathias Agopian65ab4712010-07-14 17:59:35 -07001484
1485// ----------------------------------------------------------------------------
1486
Dima Zavin799a70e2011-04-18 16:57:27 -07001487AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001488 : PlaybackThread(audioFlinger, output, id, device),
1489 mAudioMixer(0)
1490{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001491 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1493
1494 // FIXME - Current mixer implementation only supports stereo output
1495 if (mChannelCount == 1) {
1496 LOGE("Invalid audio hardware channel count");
1497 }
1498}
1499
1500AudioFlinger::MixerThread::~MixerThread()
1501{
1502 delete mAudioMixer;
1503}
1504
1505bool AudioFlinger::MixerThread::threadLoop()
1506{
1507 Vector< sp<Track> > tracksToRemove;
1508 uint32_t mixerStatus = MIXER_IDLE;
1509 nsecs_t standbyTime = systemTime();
1510 size_t mixBufferSize = mFrameCount * mFrameSize;
1511 // FIXME: Relaxed timing because of a certain device that can't meet latency
1512 // Should be reduced to 2x after the vendor fixes the driver issue
1513 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1514 nsecs_t lastWarning = 0;
1515 bool longStandbyExit = false;
1516 uint32_t activeSleepTime = activeSleepTimeUs();
1517 uint32_t idleSleepTime = idleSleepTimeUs();
1518 uint32_t sleepTime = idleSleepTime;
1519 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001520#ifdef DEBUG_CPU_USAGE
1521 ThreadCpuUsage cpu;
1522 const CentralTendencyStatistics& stats = cpu.statistics();
1523#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524
1525 while (!exitPending())
1526 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001527#ifdef DEBUG_CPU_USAGE
1528 cpu.sampleAndEnable();
1529 unsigned n = stats.n();
1530 // cpu.elapsed() is expensive, so don't call it every loop
1531 if ((n & 127) == 1) {
1532 long long elapsed = cpu.elapsed();
1533 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1534 double perLoop = elapsed / (double) n;
1535 double perLoop100 = perLoop * 0.01;
1536 double mean = stats.mean();
1537 double stddev = stats.stddev();
1538 double minimum = stats.minimum();
1539 double maximum = stats.maximum();
1540 cpu.resetStatistics();
1541 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",
1542 elapsed * .000000001, n, perLoop * .000001,
1543 mean * .001,
1544 stddev * .001,
1545 minimum * .001,
1546 maximum * .001,
1547 mean / perLoop100,
1548 stddev / perLoop100,
1549 minimum / perLoop100,
1550 maximum / perLoop100);
1551 }
1552 }
1553#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 processConfigEvents();
1555
1556 mixerStatus = MIXER_IDLE;
1557 { // scope for mLock
1558
1559 Mutex::Autolock _l(mLock);
1560
1561 if (checkForNewParameters_l()) {
1562 mixBufferSize = mFrameCount * mFrameSize;
1563 // FIXME: Relaxed timing because of a certain device that can't meet latency
1564 // Should be reduced to 2x after the vendor fixes the driver issue
1565 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1566 activeSleepTime = activeSleepTimeUs();
1567 idleSleepTime = idleSleepTimeUs();
1568 }
1569
1570 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1571
1572 // put audio hardware into standby after short delay
1573 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1574 mSuspended) {
1575 if (!mStandby) {
1576 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001577 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001578 mStandby = true;
1579 mBytesWritten = 0;
1580 }
1581
1582 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1583 // we're about to wait, flush the binder command buffer
1584 IPCThreadState::self()->flushCommands();
1585
1586 if (exitPending()) break;
1587
1588 // wait until we have something to do...
1589 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1590 mWaitWorkCV.wait(mLock);
1591 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1592
1593 if (mMasterMute == false) {
1594 char value[PROPERTY_VALUE_MAX];
1595 property_get("ro.audio.silent", value, "0");
1596 if (atoi(value)) {
1597 LOGD("Silence is golden");
1598 setMasterMute(true);
1599 }
1600 }
1601
1602 standbyTime = systemTime() + kStandbyTimeInNsecs;
1603 sleepTime = idleSleepTime;
1604 continue;
1605 }
1606 }
1607
1608 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1609
1610 // prevent any changes in effect chain list and in each effect chain
1611 // during mixing and effect process as the audio buffers could be deleted
1612 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001613 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614 }
1615
1616 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1617 // mix buffers...
1618 mAudioMixer->process();
1619 sleepTime = 0;
1620 standbyTime = systemTime() + kStandbyTimeInNsecs;
1621 //TODO: delay standby when effects have a tail
1622 } else {
1623 // If no tracks are ready, sleep once for the duration of an output
1624 // buffer size, then write 0s to the output
1625 if (sleepTime == 0) {
1626 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1627 sleepTime = activeSleepTime;
1628 } else {
1629 sleepTime = idleSleepTime;
1630 }
1631 } else if (mBytesWritten != 0 ||
1632 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1633 memset (mMixBuffer, 0, mixBufferSize);
1634 sleepTime = 0;
1635 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1636 }
1637 // TODO add standby time extension fct of effect tail
1638 }
1639
1640 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001641 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642 }
1643 // sleepTime == 0 means we must write to audio hardware
1644 if (sleepTime == 0) {
1645 for (size_t i = 0; i < effectChains.size(); i ++) {
1646 effectChains[i]->process_l();
1647 }
1648 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001649 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 mLastWriteTime = systemTime();
1651 mInWrite = true;
1652 mBytesWritten += mixBufferSize;
1653
Dima Zavin799a70e2011-04-18 16:57:27 -07001654 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001655 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1656 mNumWrites++;
1657 mInWrite = false;
1658 nsecs_t now = systemTime();
1659 nsecs_t delta = now - mLastWriteTime;
1660 if (delta > maxPeriod) {
1661 mNumDelayedWrites++;
1662 if ((now - lastWarning) > kWarningThrottle) {
1663 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1664 ns2ms(delta), mNumDelayedWrites, this);
1665 lastWarning = now;
1666 }
1667 if (mStandby) {
1668 longStandbyExit = true;
1669 }
1670 }
1671 mStandby = false;
1672 } else {
1673 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001674 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 usleep(sleepTime);
1676 }
1677
1678 // finally let go of all our tracks, without the lock held
1679 // since we can't guarantee the destructors won't acquire that
1680 // same lock.
1681 tracksToRemove.clear();
1682
1683 // Effect chains will be actually deleted here if they were removed from
1684 // mEffectChains list during mixing or effects processing
1685 effectChains.clear();
1686 }
1687
1688 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001689 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 }
1691
1692 LOGV("MixerThread %p exiting", this);
1693 return false;
1694}
1695
1696// prepareTracks_l() must be called with ThreadBase::mLock held
1697uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1698{
1699
1700 uint32_t mixerStatus = MIXER_IDLE;
1701 // find out which tracks need to be processed
1702 size_t count = activeTracks.size();
1703 size_t mixedTracks = 0;
1704 size_t tracksWithEffect = 0;
1705
1706 float masterVolume = mMasterVolume;
1707 bool masterMute = mMasterMute;
1708
Eric Laurent571d49c2010-08-11 05:20:11 -07001709 if (masterMute) {
1710 masterVolume = 0;
1711 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001712 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07001713 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07001715 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07001716 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717 masterVolume = (float)((v + (1 << 23)) >> 24);
1718 chain.clear();
1719 }
1720
1721 for (size_t i=0 ; i<count ; i++) {
1722 sp<Track> t = activeTracks[i].promote();
1723 if (t == 0) continue;
1724
1725 Track* const track = t.get();
1726 audio_track_cblk_t* cblk = track->cblk();
1727
1728 // The first time a track is added we wait
1729 // for all its buffers to be filled before processing it
1730 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07001731 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 !track->isPaused() && !track->isTerminated())
1733 {
1734 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1735
1736 mixedTracks++;
1737
1738 // track->mainBuffer() != mMixBuffer means there is an effect chain
1739 // connected to the track
1740 chain.clear();
1741 if (track->mainBuffer() != mMixBuffer) {
1742 chain = getEffectChain_l(track->sessionId());
1743 // Delegate volume control to effect in track effect chain if needed
1744 if (chain != 0) {
1745 tracksWithEffect++;
1746 } else {
1747 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1748 track->name(), track->sessionId());
1749 }
1750 }
1751
1752
1753 int param = AudioMixer::VOLUME;
1754 if (track->mFillingUpStatus == Track::FS_FILLED) {
1755 // no ramp for the first volume setting
1756 track->mFillingUpStatus = Track::FS_ACTIVE;
1757 if (track->mState == TrackBase::RESUMING) {
1758 track->mState = TrackBase::ACTIVE;
1759 param = AudioMixer::RAMP_VOLUME;
1760 }
Eric Laurent243f5f92011-02-28 16:52:51 -08001761 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 } else if (cblk->server != 0) {
1763 // If the track is stopped before the first frame was mixed,
1764 // do not apply ramp
1765 param = AudioMixer::RAMP_VOLUME;
1766 }
1767
1768 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07001769 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07001770 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001772 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 if (track->isPausing()) {
1774 track->setPaused();
1775 }
1776 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001777
Mathias Agopian65ab4712010-07-14 17:59:35 -07001778 // read original volumes with volume control
1779 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07001781 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1782 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783
Eric Laurente0aed6d2010-09-10 17:44:44 -07001784 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001785 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07001786 // Delegate volume control to effect in track effect chain if needed
1787 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1788 // Do not ramp volume if volume is controlled by effect
1789 param = AudioMixer::VOLUME;
1790 track->mHasVolumeController = true;
1791 } else {
1792 // force no volume ramp when volume controller was just disabled or removed
1793 // from effect chain to avoid volume spike
1794 if (track->mHasVolumeController) {
1795 param = AudioMixer::VOLUME;
1796 }
1797 track->mHasVolumeController = false;
1798 }
1799
1800 // Convert volumes from 8.24 to 4.12 format
1801 int16_t left, right, aux;
1802 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1803 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1804 left = int16_t(v_clamped);
1805 v_clamped = (vr + (1 << 11)) >> 12;
1806 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1807 right = int16_t(v_clamped);
1808
1809 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1810 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001811
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812 // XXX: these things DON'T need to be done each time
1813 mAudioMixer->setBufferProvider(track);
1814 mAudioMixer->enable(AudioMixer::MIXING);
1815
1816 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1817 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1818 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
1819 mAudioMixer->setParameter(
1820 AudioMixer::TRACK,
1821 AudioMixer::FORMAT, (void *)track->format());
1822 mAudioMixer->setParameter(
1823 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001824 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 mAudioMixer->setParameter(
1826 AudioMixer::RESAMPLE,
1827 AudioMixer::SAMPLE_RATE,
1828 (void *)(cblk->sampleRate));
1829 mAudioMixer->setParameter(
1830 AudioMixer::TRACK,
1831 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1832 mAudioMixer->setParameter(
1833 AudioMixer::TRACK,
1834 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
1835
1836 // reset retry count
1837 track->mRetryCount = kMaxTrackRetries;
1838 mixerStatus = MIXER_TRACKS_READY;
1839 } else {
1840 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
1841 if (track->isStopped()) {
1842 track->reset();
1843 }
1844 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1845 // We have consumed all the buffers of this track.
1846 // Remove it from the list of active tracks.
1847 tracksToRemove->add(track);
1848 } else {
1849 // No buffers for this track. Give it a few chances to
1850 // fill a buffer, then remove it from active list.
1851 if (--(track->mRetryCount) <= 0) {
1852 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
1853 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07001854 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07001855 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856 } else if (mixerStatus != MIXER_TRACKS_READY) {
1857 mixerStatus = MIXER_TRACKS_ENABLED;
1858 }
1859 }
1860 mAudioMixer->disable(AudioMixer::MIXING);
1861 }
1862 }
1863
1864 // remove all the tracks that need to be...
1865 count = tracksToRemove->size();
1866 if (UNLIKELY(count)) {
1867 for (size_t i=0 ; i<count ; i++) {
1868 const sp<Track>& track = tracksToRemove->itemAt(i);
1869 mActiveTracks.remove(track);
1870 if (track->mainBuffer() != mMixBuffer) {
1871 chain = getEffectChain_l(track->sessionId());
1872 if (chain != 0) {
1873 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001874 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 }
1876 }
1877 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07001878 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001879 }
1880 }
1881 }
1882
1883 // mix buffer must be cleared if all tracks are connected to an
1884 // effect chain as in this case the mixer will not write to
1885 // mix buffer and track effects will accumulate into it
1886 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1887 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1888 }
1889
1890 return mixerStatus;
1891}
1892
1893void AudioFlinger::MixerThread::invalidateTracks(int streamType)
1894{
Eric Laurentde070132010-07-13 04:45:46 -07001895 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1896 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001898
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 size_t size = mTracks.size();
1900 for (size_t i = 0; i < size; i++) {
1901 sp<Track> t = mTracks[i];
1902 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07001903 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001904 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001905 }
1906 }
1907}
1908
1909
1910// getTrackName_l() must be called with ThreadBase::mLock held
1911int AudioFlinger::MixerThread::getTrackName_l()
1912{
1913 return mAudioMixer->getTrackName();
1914}
1915
1916// deleteTrackName_l() must be called with ThreadBase::mLock held
1917void AudioFlinger::MixerThread::deleteTrackName_l(int name)
1918{
1919 LOGV("remove track (%d) and delete from mixer", name);
1920 mAudioMixer->deleteTrackName(name);
1921}
1922
1923// checkForNewParameters_l() must be called with ThreadBase::mLock held
1924bool AudioFlinger::MixerThread::checkForNewParameters_l()
1925{
1926 bool reconfig = false;
1927
1928 while (!mNewParameters.isEmpty()) {
1929 status_t status = NO_ERROR;
1930 String8 keyValuePair = mNewParameters[0];
1931 AudioParameter param = AudioParameter(keyValuePair);
1932 int value;
1933
1934 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1935 reconfig = true;
1936 }
1937 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001938 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 status = BAD_VALUE;
1940 } else {
1941 reconfig = true;
1942 }
1943 }
1944 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001945 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001946 status = BAD_VALUE;
1947 } else {
1948 reconfig = true;
1949 }
1950 }
1951 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1952 // do not accept frame count changes if tracks are open as the track buffer
1953 // size depends on frame count and correct behavior would not be garantied
1954 // if frame count is changed after track creation
1955 if (!mTracks.isEmpty()) {
1956 status = INVALID_OPERATION;
1957 } else {
1958 reconfig = true;
1959 }
1960 }
1961 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001962 // when changing the audio output device, call addBatteryData to notify
1963 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07001964 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001965 uint32_t params = 0;
1966 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07001967 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001968 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1969 }
1970
1971 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07001972 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08001973 // check if any other device (except speaker) is on
1974 if (value & deviceWithoutSpeaker ) {
1975 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1976 }
1977
1978 if (params != 0) {
1979 addBatteryData(params);
1980 }
1981 }
1982
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 // forward device change to effects that have requested to be
1984 // aware of attached audio device.
1985 mDevice = (uint32_t)value;
1986 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001987 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 }
1989 }
1990
1991 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001992 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07001993 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001994 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001995 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001996 mStandby = true;
1997 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07001998 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07001999 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002000 }
2001 if (status == NO_ERROR && reconfig) {
2002 delete mAudioMixer;
2003 readOutputParameters();
2004 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2005 for (size_t i = 0; i < mTracks.size() ; i++) {
2006 int name = getTrackName_l();
2007 if (name < 0) break;
2008 mTracks[i]->mName = name;
2009 // limit track sample rate to 2 x new output sample rate
2010 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2011 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2012 }
2013 }
2014 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2015 }
2016 }
2017
2018 mNewParameters.removeAt(0);
2019
2020 mParamStatus = status;
2021 mParamCond.signal();
2022 mWaitWorkCV.wait(mLock);
2023 }
2024 return reconfig;
2025}
2026
2027status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2028{
2029 const size_t SIZE = 256;
2030 char buffer[SIZE];
2031 String8 result;
2032
2033 PlaybackThread::dumpInternals(fd, args);
2034
2035 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2036 result.append(buffer);
2037 write(fd, result.string(), result.size());
2038 return NO_ERROR;
2039}
2040
2041uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2042{
Dima Zavin799a70e2011-04-18 16:57:27 -07002043 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044}
2045
2046uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2047{
Eric Laurent60e18242010-07-29 06:50:24 -07002048 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049}
2050
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002051uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2052{
2053 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2054}
2055
Mathias Agopian65ab4712010-07-14 17:59:35 -07002056// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002057AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 : PlaybackThread(audioFlinger, output, id, device)
2059{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002060 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061}
2062
2063AudioFlinger::DirectOutputThread::~DirectOutputThread()
2064{
2065}
2066
2067
2068static inline int16_t clamp16(int32_t sample)
2069{
2070 if ((sample>>15) ^ (sample>>31))
2071 sample = 0x7FFF ^ (sample>>31);
2072 return sample;
2073}
2074
2075static inline
2076int32_t mul(int16_t in, int16_t v)
2077{
2078#if defined(__arm__) && !defined(__thumb__)
2079 int32_t out;
2080 asm( "smulbb %[out], %[in], %[v] \n"
2081 : [out]"=r"(out)
2082 : [in]"%r"(in), [v]"r"(v)
2083 : );
2084 return out;
2085#else
2086 return in * int32_t(v);
2087#endif
2088}
2089
2090void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2091{
2092 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002093 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 return;
2095 }
2096
2097 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002098 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 size_t count = mFrameCount * mChannelCount;
2100 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2101 int16_t *dst = mMixBuffer + count-1;
2102 while(count--) {
2103 *dst-- = (int16_t)(*src--^0x80) << 8;
2104 }
2105 }
2106
2107 size_t frameCount = mFrameCount;
2108 int16_t *out = mMixBuffer;
2109 if (ramp) {
2110 if (mChannelCount == 1) {
2111 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2112 int32_t vlInc = d / (int32_t)frameCount;
2113 int32_t vl = ((int32_t)mLeftVolShort << 16);
2114 do {
2115 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2116 out++;
2117 vl += vlInc;
2118 } while (--frameCount);
2119
2120 } else {
2121 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2122 int32_t vlInc = d / (int32_t)frameCount;
2123 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2124 int32_t vrInc = d / (int32_t)frameCount;
2125 int32_t vl = ((int32_t)mLeftVolShort << 16);
2126 int32_t vr = ((int32_t)mRightVolShort << 16);
2127 do {
2128 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2129 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2130 out += 2;
2131 vl += vlInc;
2132 vr += vrInc;
2133 } while (--frameCount);
2134 }
2135 } else {
2136 if (mChannelCount == 1) {
2137 do {
2138 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2139 out++;
2140 } while (--frameCount);
2141 } else {
2142 do {
2143 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2144 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2145 out += 2;
2146 } while (--frameCount);
2147 }
2148 }
2149
2150 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002151 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002152 size_t count = mFrameCount * mChannelCount;
2153 int16_t *src = mMixBuffer;
2154 uint8_t *dst = (uint8_t *)mMixBuffer;
2155 while(count--) {
2156 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2157 }
2158 }
2159
2160 mLeftVolShort = leftVol;
2161 mRightVolShort = rightVol;
2162}
2163
2164bool AudioFlinger::DirectOutputThread::threadLoop()
2165{
2166 uint32_t mixerStatus = MIXER_IDLE;
2167 sp<Track> trackToRemove;
2168 sp<Track> activeTrack;
2169 nsecs_t standbyTime = systemTime();
2170 int8_t *curBuf;
2171 size_t mixBufferSize = mFrameCount*mFrameSize;
2172 uint32_t activeSleepTime = activeSleepTimeUs();
2173 uint32_t idleSleepTime = idleSleepTimeUs();
2174 uint32_t sleepTime = idleSleepTime;
2175 // use shorter standby delay as on normal output to release
2176 // hardware resources as soon as possible
2177 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2178
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 while (!exitPending())
2180 {
2181 bool rampVolume;
2182 uint16_t leftVol;
2183 uint16_t rightVol;
2184 Vector< sp<EffectChain> > effectChains;
2185
2186 processConfigEvents();
2187
2188 mixerStatus = MIXER_IDLE;
2189
2190 { // scope for the mLock
2191
2192 Mutex::Autolock _l(mLock);
2193
2194 if (checkForNewParameters_l()) {
2195 mixBufferSize = mFrameCount*mFrameSize;
2196 activeSleepTime = activeSleepTimeUs();
2197 idleSleepTime = idleSleepTimeUs();
2198 standbyDelay = microseconds(activeSleepTime*2);
2199 }
2200
2201 // put audio hardware into standby after short delay
2202 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2203 mSuspended) {
2204 // wait until we have something to do...
2205 if (!mStandby) {
2206 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002207 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002208 mStandby = true;
2209 mBytesWritten = 0;
2210 }
2211
2212 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2213 // we're about to wait, flush the binder command buffer
2214 IPCThreadState::self()->flushCommands();
2215
2216 if (exitPending()) break;
2217
2218 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2219 mWaitWorkCV.wait(mLock);
2220 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2221
2222 if (mMasterMute == false) {
2223 char value[PROPERTY_VALUE_MAX];
2224 property_get("ro.audio.silent", value, "0");
2225 if (atoi(value)) {
2226 LOGD("Silence is golden");
2227 setMasterMute(true);
2228 }
2229 }
2230
2231 standbyTime = systemTime() + standbyDelay;
2232 sleepTime = idleSleepTime;
2233 continue;
2234 }
2235 }
2236
2237 effectChains = mEffectChains;
2238
2239 // find out which tracks need to be processed
2240 if (mActiveTracks.size() != 0) {
2241 sp<Track> t = mActiveTracks[0].promote();
2242 if (t == 0) continue;
2243
2244 Track* const track = t.get();
2245 audio_track_cblk_t* cblk = track->cblk();
2246
2247 // The first time a track is added we wait
2248 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002249 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002250 !track->isPaused() && !track->isTerminated())
2251 {
2252 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2253
2254 if (track->mFillingUpStatus == Track::FS_FILLED) {
2255 track->mFillingUpStatus = Track::FS_ACTIVE;
2256 mLeftVolFloat = mRightVolFloat = 0;
2257 mLeftVolShort = mRightVolShort = 0;
2258 if (track->mState == TrackBase::RESUMING) {
2259 track->mState = TrackBase::ACTIVE;
2260 rampVolume = true;
2261 }
2262 } else if (cblk->server != 0) {
2263 // If the track is stopped before the first frame was mixed,
2264 // do not apply ramp
2265 rampVolume = true;
2266 }
2267 // compute volume for this track
2268 float left, right;
2269 if (track->isMuted() || mMasterMute || track->isPausing() ||
2270 mStreamTypes[track->type()].mute) {
2271 left = right = 0;
2272 if (track->isPausing()) {
2273 track->setPaused();
2274 }
2275 } else {
2276 float typeVolume = mStreamTypes[track->type()].volume;
2277 float v = mMasterVolume * typeVolume;
2278 float v_clamped = v * cblk->volume[0];
2279 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2280 left = v_clamped/MAX_GAIN;
2281 v_clamped = v * cblk->volume[1];
2282 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2283 right = v_clamped/MAX_GAIN;
2284 }
2285
2286 if (left != mLeftVolFloat || right != mRightVolFloat) {
2287 mLeftVolFloat = left;
2288 mRightVolFloat = right;
2289
2290 // If audio HAL implements volume control,
2291 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002292 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 left = 1.0f;
2294 right = 1.0f;
2295 }
2296
2297 // Convert volumes from float to 8.24
2298 uint32_t vl = (uint32_t)(left * (1 << 24));
2299 uint32_t vr = (uint32_t)(right * (1 << 24));
2300
2301 // Delegate volume control to effect in track effect chain if needed
2302 // only one effect chain can be present on DirectOutputThread, so if
2303 // there is one, the track is connected to it
2304 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002305 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002306 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 rampVolume = false;
2308 }
2309 }
2310
2311 // Convert volumes from 8.24 to 4.12 format
2312 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2313 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2314 leftVol = (uint16_t)v_clamped;
2315 v_clamped = (vr + (1 << 11)) >> 12;
2316 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2317 rightVol = (uint16_t)v_clamped;
2318 } else {
2319 leftVol = mLeftVolShort;
2320 rightVol = mRightVolShort;
2321 rampVolume = false;
2322 }
2323
2324 // reset retry count
2325 track->mRetryCount = kMaxTrackRetriesDirect;
2326 activeTrack = t;
2327 mixerStatus = MIXER_TRACKS_READY;
2328 } else {
2329 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2330 if (track->isStopped()) {
2331 track->reset();
2332 }
2333 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2334 // We have consumed all the buffers of this track.
2335 // Remove it from the list of active tracks.
2336 trackToRemove = track;
2337 } else {
2338 // No buffers for this track. Give it a few chances to
2339 // fill a buffer, then remove it from active list.
2340 if (--(track->mRetryCount) <= 0) {
2341 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2342 trackToRemove = track;
2343 } else {
2344 mixerStatus = MIXER_TRACKS_ENABLED;
2345 }
2346 }
2347 }
2348 }
2349
2350 // remove all the tracks that need to be...
2351 if (UNLIKELY(trackToRemove != 0)) {
2352 mActiveTracks.remove(trackToRemove);
2353 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002354 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2355 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002356 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 }
2358 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002359 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002360 }
2361 }
2362
Eric Laurentde070132010-07-13 04:45:46 -07002363 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 }
2365
2366 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2367 AudioBufferProvider::Buffer buffer;
2368 size_t frameCount = mFrameCount;
2369 curBuf = (int8_t *)mMixBuffer;
2370 // output audio to hardware
2371 while (frameCount) {
2372 buffer.frameCount = frameCount;
2373 activeTrack->getNextBuffer(&buffer);
2374 if (UNLIKELY(buffer.raw == 0)) {
2375 memset(curBuf, 0, frameCount * mFrameSize);
2376 break;
2377 }
2378 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2379 frameCount -= buffer.frameCount;
2380 curBuf += buffer.frameCount * mFrameSize;
2381 activeTrack->releaseBuffer(&buffer);
2382 }
2383 sleepTime = 0;
2384 standbyTime = systemTime() + standbyDelay;
2385 } else {
2386 if (sleepTime == 0) {
2387 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2388 sleepTime = activeSleepTime;
2389 } else {
2390 sleepTime = idleSleepTime;
2391 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002392 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2394 sleepTime = 0;
2395 }
2396 }
2397
2398 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002399 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002400 }
2401 // sleepTime == 0 means we must write to audio hardware
2402 if (sleepTime == 0) {
2403 if (mixerStatus == MIXER_TRACKS_READY) {
2404 applyVolume(leftVol, rightVol, rampVolume);
2405 }
2406 for (size_t i = 0; i < effectChains.size(); i ++) {
2407 effectChains[i]->process_l();
2408 }
Eric Laurentde070132010-07-13 04:45:46 -07002409 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410
2411 mLastWriteTime = systemTime();
2412 mInWrite = true;
2413 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002414 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2416 mNumWrites++;
2417 mInWrite = false;
2418 mStandby = false;
2419 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002420 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002421 usleep(sleepTime);
2422 }
2423
2424 // finally let go of removed track, without the lock held
2425 // since we can't guarantee the destructors won't acquire that
2426 // same lock.
2427 trackToRemove.clear();
2428 activeTrack.clear();
2429
2430 // Effect chains will be actually deleted here if they were removed from
2431 // mEffectChains list during mixing or effects processing
2432 effectChains.clear();
2433 }
2434
2435 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002436 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002437 }
2438
2439 LOGV("DirectOutputThread %p exiting", this);
2440 return false;
2441}
2442
2443// getTrackName_l() must be called with ThreadBase::mLock held
2444int AudioFlinger::DirectOutputThread::getTrackName_l()
2445{
2446 return 0;
2447}
2448
2449// deleteTrackName_l() must be called with ThreadBase::mLock held
2450void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2451{
2452}
2453
2454// checkForNewParameters_l() must be called with ThreadBase::mLock held
2455bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2456{
2457 bool reconfig = false;
2458
2459 while (!mNewParameters.isEmpty()) {
2460 status_t status = NO_ERROR;
2461 String8 keyValuePair = mNewParameters[0];
2462 AudioParameter param = AudioParameter(keyValuePair);
2463 int value;
2464
2465 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2466 // do not accept frame count changes if tracks are open as the track buffer
2467 // size depends on frame count and correct behavior would not be garantied
2468 // if frame count is changed after track creation
2469 if (!mTracks.isEmpty()) {
2470 status = INVALID_OPERATION;
2471 } else {
2472 reconfig = true;
2473 }
2474 }
2475 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002476 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002477 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002478 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002479 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002480 mStandby = true;
2481 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002482 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002483 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484 }
2485 if (status == NO_ERROR && reconfig) {
2486 readOutputParameters();
2487 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2488 }
2489 }
2490
2491 mNewParameters.removeAt(0);
2492
2493 mParamStatus = status;
2494 mParamCond.signal();
2495 mWaitWorkCV.wait(mLock);
2496 }
2497 return reconfig;
2498}
2499
2500uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2501{
2502 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002503 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002504 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002505 } else {
2506 time = 10000;
2507 }
2508 return time;
2509}
2510
2511uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2512{
2513 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002514 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002515 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 } else {
2517 time = 10000;
2518 }
2519 return time;
2520}
2521
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002522uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2523{
2524 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002525 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002526 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2527 } else {
2528 time = 10000;
2529 }
2530 return time;
2531}
2532
2533
Mathias Agopian65ab4712010-07-14 17:59:35 -07002534// ----------------------------------------------------------------------------
2535
2536AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2537 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2538{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002539 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002540 addOutputTrack(mainThread);
2541}
2542
2543AudioFlinger::DuplicatingThread::~DuplicatingThread()
2544{
2545 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2546 mOutputTracks[i]->destroy();
2547 }
2548 mOutputTracks.clear();
2549}
2550
2551bool AudioFlinger::DuplicatingThread::threadLoop()
2552{
2553 Vector< sp<Track> > tracksToRemove;
2554 uint32_t mixerStatus = MIXER_IDLE;
2555 nsecs_t standbyTime = systemTime();
2556 size_t mixBufferSize = mFrameCount*mFrameSize;
2557 SortedVector< sp<OutputTrack> > outputTracks;
2558 uint32_t writeFrames = 0;
2559 uint32_t activeSleepTime = activeSleepTimeUs();
2560 uint32_t idleSleepTime = idleSleepTimeUs();
2561 uint32_t sleepTime = idleSleepTime;
2562 Vector< sp<EffectChain> > effectChains;
2563
2564 while (!exitPending())
2565 {
2566 processConfigEvents();
2567
2568 mixerStatus = MIXER_IDLE;
2569 { // scope for the mLock
2570
2571 Mutex::Autolock _l(mLock);
2572
2573 if (checkForNewParameters_l()) {
2574 mixBufferSize = mFrameCount*mFrameSize;
2575 updateWaitTime();
2576 activeSleepTime = activeSleepTimeUs();
2577 idleSleepTime = idleSleepTimeUs();
2578 }
2579
2580 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2581
2582 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2583 outputTracks.add(mOutputTracks[i]);
2584 }
2585
2586 // put audio hardware into standby after short delay
2587 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2588 mSuspended) {
2589 if (!mStandby) {
2590 for (size_t i = 0; i < outputTracks.size(); i++) {
2591 outputTracks[i]->stop();
2592 }
2593 mStandby = true;
2594 mBytesWritten = 0;
2595 }
2596
2597 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2598 // we're about to wait, flush the binder command buffer
2599 IPCThreadState::self()->flushCommands();
2600 outputTracks.clear();
2601
2602 if (exitPending()) break;
2603
2604 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2605 mWaitWorkCV.wait(mLock);
2606 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2607 if (mMasterMute == false) {
2608 char value[PROPERTY_VALUE_MAX];
2609 property_get("ro.audio.silent", value, "0");
2610 if (atoi(value)) {
2611 LOGD("Silence is golden");
2612 setMasterMute(true);
2613 }
2614 }
2615
2616 standbyTime = systemTime() + kStandbyTimeInNsecs;
2617 sleepTime = idleSleepTime;
2618 continue;
2619 }
2620 }
2621
2622 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2623
2624 // prevent any changes in effect chain list and in each effect chain
2625 // during mixing and effect process as the audio buffers could be deleted
2626 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002627 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 }
2629
2630 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2631 // mix buffers...
2632 if (outputsReady(outputTracks)) {
2633 mAudioMixer->process();
2634 } else {
2635 memset(mMixBuffer, 0, mixBufferSize);
2636 }
2637 sleepTime = 0;
2638 writeFrames = mFrameCount;
2639 } else {
2640 if (sleepTime == 0) {
2641 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2642 sleepTime = activeSleepTime;
2643 } else {
2644 sleepTime = idleSleepTime;
2645 }
2646 } else if (mBytesWritten != 0) {
2647 // flush remaining overflow buffers in output tracks
2648 for (size_t i = 0; i < outputTracks.size(); i++) {
2649 if (outputTracks[i]->isActive()) {
2650 sleepTime = 0;
2651 writeFrames = 0;
2652 memset(mMixBuffer, 0, mixBufferSize);
2653 break;
2654 }
2655 }
2656 }
2657 }
2658
2659 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002660 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 }
2662 // sleepTime == 0 means we must write to audio hardware
2663 if (sleepTime == 0) {
2664 for (size_t i = 0; i < effectChains.size(); i ++) {
2665 effectChains[i]->process_l();
2666 }
2667 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002668 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002669
2670 standbyTime = systemTime() + kStandbyTimeInNsecs;
2671 for (size_t i = 0; i < outputTracks.size(); i++) {
2672 outputTracks[i]->write(mMixBuffer, writeFrames);
2673 }
2674 mStandby = false;
2675 mBytesWritten += mixBufferSize;
2676 } else {
2677 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002678 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002679 usleep(sleepTime);
2680 }
2681
2682 // finally let go of all our tracks, without the lock held
2683 // since we can't guarantee the destructors won't acquire that
2684 // same lock.
2685 tracksToRemove.clear();
2686 outputTracks.clear();
2687
2688 // Effect chains will be actually deleted here if they were removed from
2689 // mEffectChains list during mixing or effects processing
2690 effectChains.clear();
2691 }
2692
2693 return false;
2694}
2695
2696void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2697{
2698 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2699 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2700 this,
2701 mSampleRate,
2702 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002703 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 frameCount);
2705 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002706 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 mOutputTracks.add(outputTrack);
2708 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2709 updateWaitTime();
2710 }
2711}
2712
2713void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2714{
2715 Mutex::Autolock _l(mLock);
2716 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2717 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2718 mOutputTracks[i]->destroy();
2719 mOutputTracks.removeAt(i);
2720 updateWaitTime();
2721 return;
2722 }
2723 }
2724 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2725}
2726
2727void AudioFlinger::DuplicatingThread::updateWaitTime()
2728{
2729 mWaitTimeMs = UINT_MAX;
2730 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2731 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2732 if (strong != NULL) {
2733 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2734 if (waitTimeMs < mWaitTimeMs) {
2735 mWaitTimeMs = waitTimeMs;
2736 }
2737 }
2738 }
2739}
2740
2741
2742bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2743{
2744 for (size_t i = 0; i < outputTracks.size(); i++) {
2745 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2746 if (thread == 0) {
2747 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2748 return false;
2749 }
2750 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2751 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2752 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2753 return false;
2754 }
2755 }
2756 return true;
2757}
2758
2759uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2760{
2761 return (mWaitTimeMs * 1000) / 2;
2762}
2763
2764// ----------------------------------------------------------------------------
2765
2766// TrackBase constructor must be called with AudioFlinger::mLock held
2767AudioFlinger::ThreadBase::TrackBase::TrackBase(
2768 const wp<ThreadBase>& thread,
2769 const sp<Client>& client,
2770 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002771 uint32_t format,
2772 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002773 int frameCount,
2774 uint32_t flags,
2775 const sp<IMemory>& sharedBuffer,
2776 int sessionId)
2777 : RefBase(),
2778 mThread(thread),
2779 mClient(client),
2780 mCblk(0),
2781 mFrameCount(0),
2782 mState(IDLE),
2783 mClientTid(-1),
2784 mFormat(format),
2785 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2786 mSessionId(sessionId)
2787{
2788 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2789
2790 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
2791 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002792 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2794 if (sharedBuffer == 0) {
2795 size += bufferSize;
2796 }
2797
2798 if (client != NULL) {
2799 mCblkMemory = client->heap()->allocate(size);
2800 if (mCblkMemory != 0) {
2801 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2802 if (mCblk) { // construct the shared structure in-place.
2803 new(mCblk) audio_track_cblk_t();
2804 // clear all buffers
2805 mCblk->frameCount = frameCount;
2806 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002807 mChannelCount = channelCount;
2808 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002809 if (sharedBuffer == 0) {
2810 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2811 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2812 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002813 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002814 mCblk->flags = CBLK_UNDERRUN_ON;
2815 } else {
2816 mBuffer = sharedBuffer->pointer();
2817 }
2818 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2819 }
2820 } else {
2821 LOGE("not enough memory for AudioTrack size=%u", size);
2822 client->heap()->dump("AudioTrack");
2823 return;
2824 }
2825 } else {
2826 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2827 if (mCblk) { // construct the shared structure in-place.
2828 new(mCblk) audio_track_cblk_t();
2829 // clear all buffers
2830 mCblk->frameCount = frameCount;
2831 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002832 mChannelCount = channelCount;
2833 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002834 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2835 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2836 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002837 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002838 mCblk->flags = CBLK_UNDERRUN_ON;
2839 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2840 }
2841 }
2842}
2843
2844AudioFlinger::ThreadBase::TrackBase::~TrackBase()
2845{
2846 if (mCblk) {
2847 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2848 if (mClient == NULL) {
2849 delete mCblk;
2850 }
2851 }
2852 mCblkMemory.clear(); // and free the shared memory
2853 if (mClient != NULL) {
2854 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2855 mClient.clear();
2856 }
2857}
2858
2859void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2860{
2861 buffer->raw = 0;
2862 mFrameCount = buffer->frameCount;
2863 step();
2864 buffer->frameCount = 0;
2865}
2866
2867bool AudioFlinger::ThreadBase::TrackBase::step() {
2868 bool result;
2869 audio_track_cblk_t* cblk = this->cblk();
2870
2871 result = cblk->stepServer(mFrameCount);
2872 if (!result) {
2873 LOGV("stepServer failed acquiring cblk mutex");
2874 mFlags |= STEPSERVER_FAILED;
2875 }
2876 return result;
2877}
2878
2879void AudioFlinger::ThreadBase::TrackBase::reset() {
2880 audio_track_cblk_t* cblk = this->cblk();
2881
2882 cblk->user = 0;
2883 cblk->server = 0;
2884 cblk->userBase = 0;
2885 cblk->serverBase = 0;
2886 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
2887 LOGV("TrackBase::reset");
2888}
2889
2890sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
2891{
2892 return mCblkMemory;
2893}
2894
2895int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
2896 return (int)mCblk->sampleRate;
2897}
2898
2899int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002900 return (const int)mChannelCount;
2901}
2902
2903uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
2904 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905}
2906
2907void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
2908 audio_track_cblk_t* cblk = this->cblk();
2909 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2910 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
2911
2912 // Check validity of returned pointer in case the track control block would have been corrupted.
2913 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2914 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
2915 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 -07002916 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002917 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002918 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 return 0;
2920 }
2921
2922 return bufferStart;
2923}
2924
2925// ----------------------------------------------------------------------------
2926
2927// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2928AudioFlinger::PlaybackThread::Track::Track(
2929 const wp<ThreadBase>& thread,
2930 const sp<Client>& client,
2931 int streamType,
2932 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002933 uint32_t format,
2934 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002935 int frameCount,
2936 const sp<IMemory>& sharedBuffer,
2937 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002938 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07002939 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2940 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941{
2942 if (mCblk != NULL) {
2943 sp<ThreadBase> baseThread = thread.promote();
2944 if (baseThread != 0) {
2945 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2946 mName = playbackThread->getTrackName_l();
2947 mMainBuffer = playbackThread->mixBuffer();
2948 }
2949 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2950 if (mName < 0) {
2951 LOGE("no more track names available");
2952 }
2953 mVolume[0] = 1.0f;
2954 mVolume[1] = 1.0f;
2955 mStreamType = streamType;
2956 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2957 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07002958 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002959 }
2960}
2961
2962AudioFlinger::PlaybackThread::Track::~Track()
2963{
2964 LOGV("PlaybackThread::Track destructor");
2965 sp<ThreadBase> thread = mThread.promote();
2966 if (thread != 0) {
2967 Mutex::Autolock _l(thread->mLock);
2968 mState = TERMINATED;
2969 }
2970}
2971
2972void AudioFlinger::PlaybackThread::Track::destroy()
2973{
2974 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2975 // by removing it from mTracks vector, so there is a risk that this Tracks's
2976 // desctructor is called. As the destructor needs to lock mLock,
2977 // we must acquire a strong reference on this Track before locking mLock
2978 // here so that the destructor is called only when exiting this function.
2979 // On the other hand, as long as Track::destroy() is only called by
2980 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2981 // this Track with its member mTrack.
2982 sp<Track> keep(this);
2983 { // scope for mLock
2984 sp<ThreadBase> thread = mThread.promote();
2985 if (thread != 0) {
2986 if (!isOutputTrack()) {
2987 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07002988 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07002989 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07002990 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002991
2992 // to track the speaker usage
2993 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002994 }
2995 AudioSystem::releaseOutput(thread->id());
2996 }
2997 Mutex::Autolock _l(thread->mLock);
2998 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2999 playbackThread->destroyTrack_l(this);
3000 }
3001 }
3002}
3003
3004void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3005{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003006 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 -07003007 mName - AudioMixer::TRACK0,
3008 (mClient == NULL) ? getpid() : mClient->pid(),
3009 mStreamType,
3010 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003011 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 mSessionId,
3013 mFrameCount,
3014 mState,
3015 mMute,
3016 mFillingUpStatus,
3017 mCblk->sampleRate,
3018 mCblk->volume[0],
3019 mCblk->volume[1],
3020 mCblk->server,
3021 mCblk->user,
3022 (int)mMainBuffer,
3023 (int)mAuxBuffer);
3024}
3025
3026status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3027{
3028 audio_track_cblk_t* cblk = this->cblk();
3029 uint32_t framesReady;
3030 uint32_t framesReq = buffer->frameCount;
3031
3032 // Check if last stepServer failed, try to step now
3033 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3034 if (!step()) goto getNextBuffer_exit;
3035 LOGV("stepServer recovered");
3036 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3037 }
3038
3039 framesReady = cblk->framesReady();
3040
3041 if (LIKELY(framesReady)) {
3042 uint32_t s = cblk->server;
3043 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3044
3045 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3046 if (framesReq > framesReady) {
3047 framesReq = framesReady;
3048 }
3049 if (s + framesReq > bufferEnd) {
3050 framesReq = bufferEnd - s;
3051 }
3052
3053 buffer->raw = getBuffer(s, framesReq);
3054 if (buffer->raw == 0) goto getNextBuffer_exit;
3055
3056 buffer->frameCount = framesReq;
3057 return NO_ERROR;
3058 }
3059
3060getNextBuffer_exit:
3061 buffer->raw = 0;
3062 buffer->frameCount = 0;
3063 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3064 return NOT_ENOUGH_DATA;
3065}
3066
3067bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003068 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003069
3070 if (mCblk->framesReady() >= mCblk->frameCount ||
3071 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3072 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003073 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003074 return true;
3075 }
3076 return false;
3077}
3078
3079status_t AudioFlinger::PlaybackThread::Track::start()
3080{
3081 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003082 LOGV("start(%d), calling thread %d session %d",
3083 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084 sp<ThreadBase> thread = mThread.promote();
3085 if (thread != 0) {
3086 Mutex::Autolock _l(thread->mLock);
3087 int state = mState;
3088 // here the track could be either new, or restarted
3089 // in both cases "unstop" the track
3090 if (mState == PAUSED) {
3091 mState = TrackBase::RESUMING;
3092 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3093 } else {
3094 mState = TrackBase::ACTIVE;
3095 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3096 }
3097
3098 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3099 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003100 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003101 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003102 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003104
3105 // to track the speaker usage
3106 if (status == NO_ERROR) {
3107 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3108 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003109 }
3110 if (status == NO_ERROR) {
3111 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3112 playbackThread->addTrack_l(this);
3113 } else {
3114 mState = state;
3115 }
3116 } else {
3117 status = BAD_VALUE;
3118 }
3119 return status;
3120}
3121
3122void AudioFlinger::PlaybackThread::Track::stop()
3123{
3124 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3125 sp<ThreadBase> thread = mThread.promote();
3126 if (thread != 0) {
3127 Mutex::Autolock _l(thread->mLock);
3128 int state = mState;
3129 if (mState > STOPPED) {
3130 mState = STOPPED;
3131 // If the track is not active (PAUSED and buffers full), flush buffers
3132 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3133 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3134 reset();
3135 }
3136 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3137 }
3138 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3139 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003140 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003141 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003142 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003143 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003144
3145 // to track the speaker usage
3146 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003147 }
3148 }
3149}
3150
3151void AudioFlinger::PlaybackThread::Track::pause()
3152{
3153 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3154 sp<ThreadBase> thread = mThread.promote();
3155 if (thread != 0) {
3156 Mutex::Autolock _l(thread->mLock);
3157 if (mState == ACTIVE || mState == RESUMING) {
3158 mState = PAUSING;
3159 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3160 if (!isOutputTrack()) {
3161 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003162 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003163 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003164 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003166
3167 // to track the speaker usage
3168 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003169 }
3170 }
3171 }
3172}
3173
3174void AudioFlinger::PlaybackThread::Track::flush()
3175{
3176 LOGV("flush(%d)", mName);
3177 sp<ThreadBase> thread = mThread.promote();
3178 if (thread != 0) {
3179 Mutex::Autolock _l(thread->mLock);
3180 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3181 return;
3182 }
3183 // No point remaining in PAUSED state after a flush => go to
3184 // STOPPED state
3185 mState = STOPPED;
3186
Eric Laurent38ccae22011-03-28 18:37:07 -07003187 // do not reset the track if it is still in the process of being stopped or paused.
3188 // this will be done by prepareTracks_l() when the track is stopped.
3189 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3190 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3191 reset();
3192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003193 }
3194}
3195
3196void AudioFlinger::PlaybackThread::Track::reset()
3197{
3198 // Do not reset twice to avoid discarding data written just after a flush and before
3199 // the audioflinger thread detects the track is stopped.
3200 if (!mResetDone) {
3201 TrackBase::reset();
3202 // Force underrun condition to avoid false underrun callback until first data is
3203 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003204 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3205 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003206 mFillingUpStatus = FS_FILLING;
3207 mResetDone = true;
3208 }
3209}
3210
3211void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3212{
3213 mMute = muted;
3214}
3215
3216void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3217{
3218 mVolume[0] = left;
3219 mVolume[1] = right;
3220}
3221
3222status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3223{
3224 status_t status = DEAD_OBJECT;
3225 sp<ThreadBase> thread = mThread.promote();
3226 if (thread != 0) {
3227 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3228 status = playbackThread->attachAuxEffect(this, EffectId);
3229 }
3230 return status;
3231}
3232
3233void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3234{
3235 mAuxEffectId = EffectId;
3236 mAuxBuffer = buffer;
3237}
3238
3239// ----------------------------------------------------------------------------
3240
3241// RecordTrack constructor must be called with AudioFlinger::mLock held
3242AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3243 const wp<ThreadBase>& thread,
3244 const sp<Client>& client,
3245 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003246 uint32_t format,
3247 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 int frameCount,
3249 uint32_t flags,
3250 int sessionId)
3251 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003252 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 mOverflow(false)
3254{
3255 if (mCblk != NULL) {
3256 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003257 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003258 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003259 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003260 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003261 } else {
3262 mCblk->frameSize = sizeof(int8_t);
3263 }
3264 }
3265}
3266
3267AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3268{
3269 sp<ThreadBase> thread = mThread.promote();
3270 if (thread != 0) {
3271 AudioSystem::releaseInput(thread->id());
3272 }
3273}
3274
3275status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3276{
3277 audio_track_cblk_t* cblk = this->cblk();
3278 uint32_t framesAvail;
3279 uint32_t framesReq = buffer->frameCount;
3280
3281 // Check if last stepServer failed, try to step now
3282 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3283 if (!step()) goto getNextBuffer_exit;
3284 LOGV("stepServer recovered");
3285 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3286 }
3287
3288 framesAvail = cblk->framesAvailable_l();
3289
3290 if (LIKELY(framesAvail)) {
3291 uint32_t s = cblk->server;
3292 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3293
3294 if (framesReq > framesAvail) {
3295 framesReq = framesAvail;
3296 }
3297 if (s + framesReq > bufferEnd) {
3298 framesReq = bufferEnd - s;
3299 }
3300
3301 buffer->raw = getBuffer(s, framesReq);
3302 if (buffer->raw == 0) goto getNextBuffer_exit;
3303
3304 buffer->frameCount = framesReq;
3305 return NO_ERROR;
3306 }
3307
3308getNextBuffer_exit:
3309 buffer->raw = 0;
3310 buffer->frameCount = 0;
3311 return NOT_ENOUGH_DATA;
3312}
3313
3314status_t AudioFlinger::RecordThread::RecordTrack::start()
3315{
3316 sp<ThreadBase> thread = mThread.promote();
3317 if (thread != 0) {
3318 RecordThread *recordThread = (RecordThread *)thread.get();
3319 return recordThread->start(this);
3320 } else {
3321 return BAD_VALUE;
3322 }
3323}
3324
3325void AudioFlinger::RecordThread::RecordTrack::stop()
3326{
3327 sp<ThreadBase> thread = mThread.promote();
3328 if (thread != 0) {
3329 RecordThread *recordThread = (RecordThread *)thread.get();
3330 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003331 TrackBase::reset();
3332 // Force overerrun condition to avoid false overrun callback until first data is
3333 // read from buffer
3334 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003335 }
3336}
3337
3338void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3339{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003340 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003341 (mClient == NULL) ? getpid() : mClient->pid(),
3342 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003343 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003344 mSessionId,
3345 mFrameCount,
3346 mState,
3347 mCblk->sampleRate,
3348 mCblk->server,
3349 mCblk->user);
3350}
3351
3352
3353// ----------------------------------------------------------------------------
3354
3355AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3356 const wp<ThreadBase>& thread,
3357 DuplicatingThread *sourceThread,
3358 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003359 uint32_t format,
3360 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003362 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 mActive(false), mSourceThread(sourceThread)
3364{
3365
3366 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3367 if (mCblk != NULL) {
3368 mCblk->flags |= CBLK_DIRECTION_OUT;
3369 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3370 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3371 mOutBuffer.frameCount = 0;
3372 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003373 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3374 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3375 mCblk, mBuffer, mCblk->buffers,
3376 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 } else {
3378 LOGW("Error creating output track on thread %p", playbackThread);
3379 }
3380}
3381
3382AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3383{
3384 clearBufferQueue();
3385}
3386
3387status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3388{
3389 status_t status = Track::start();
3390 if (status != NO_ERROR) {
3391 return status;
3392 }
3393
3394 mActive = true;
3395 mRetryCount = 127;
3396 return status;
3397}
3398
3399void AudioFlinger::PlaybackThread::OutputTrack::stop()
3400{
3401 Track::stop();
3402 clearBufferQueue();
3403 mOutBuffer.frameCount = 0;
3404 mActive = false;
3405}
3406
3407bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3408{
3409 Buffer *pInBuffer;
3410 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003411 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003412 bool outputBufferFull = false;
3413 inBuffer.frameCount = frames;
3414 inBuffer.i16 = data;
3415
3416 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3417
3418 if (!mActive && frames != 0) {
3419 start();
3420 sp<ThreadBase> thread = mThread.promote();
3421 if (thread != 0) {
3422 MixerThread *mixerThread = (MixerThread *)thread.get();
3423 if (mCblk->frameCount > frames){
3424 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3425 uint32_t startFrames = (mCblk->frameCount - frames);
3426 pInBuffer = new Buffer;
3427 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3428 pInBuffer->frameCount = startFrames;
3429 pInBuffer->i16 = pInBuffer->mBuffer;
3430 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3431 mBufferQueue.add(pInBuffer);
3432 } else {
3433 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3434 }
3435 }
3436 }
3437 }
3438
3439 while (waitTimeLeftMs) {
3440 // First write pending buffers, then new data
3441 if (mBufferQueue.size()) {
3442 pInBuffer = mBufferQueue.itemAt(0);
3443 } else {
3444 pInBuffer = &inBuffer;
3445 }
3446
3447 if (pInBuffer->frameCount == 0) {
3448 break;
3449 }
3450
3451 if (mOutBuffer.frameCount == 0) {
3452 mOutBuffer.frameCount = pInBuffer->frameCount;
3453 nsecs_t startTime = systemTime();
3454 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3455 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3456 outputBufferFull = true;
3457 break;
3458 }
3459 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3460 if (waitTimeLeftMs >= waitTimeMs) {
3461 waitTimeLeftMs -= waitTimeMs;
3462 } else {
3463 waitTimeLeftMs = 0;
3464 }
3465 }
3466
3467 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3468 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3469 mCblk->stepUser(outFrames);
3470 pInBuffer->frameCount -= outFrames;
3471 pInBuffer->i16 += outFrames * channelCount;
3472 mOutBuffer.frameCount -= outFrames;
3473 mOutBuffer.i16 += outFrames * channelCount;
3474
3475 if (pInBuffer->frameCount == 0) {
3476 if (mBufferQueue.size()) {
3477 mBufferQueue.removeAt(0);
3478 delete [] pInBuffer->mBuffer;
3479 delete pInBuffer;
3480 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3481 } else {
3482 break;
3483 }
3484 }
3485 }
3486
3487 // If we could not write all frames, allocate a buffer and queue it for next time.
3488 if (inBuffer.frameCount) {
3489 sp<ThreadBase> thread = mThread.promote();
3490 if (thread != 0 && !thread->standby()) {
3491 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3492 pInBuffer = new Buffer;
3493 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3494 pInBuffer->frameCount = inBuffer.frameCount;
3495 pInBuffer->i16 = pInBuffer->mBuffer;
3496 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3497 mBufferQueue.add(pInBuffer);
3498 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3499 } else {
3500 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3501 }
3502 }
3503 }
3504
3505 // Calling write() with a 0 length buffer, means that no more data will be written:
3506 // If no more buffers are pending, fill output track buffer to make sure it is started
3507 // by output mixer.
3508 if (frames == 0 && mBufferQueue.size() == 0) {
3509 if (mCblk->user < mCblk->frameCount) {
3510 frames = mCblk->frameCount - mCblk->user;
3511 pInBuffer = new Buffer;
3512 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3513 pInBuffer->frameCount = frames;
3514 pInBuffer->i16 = pInBuffer->mBuffer;
3515 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3516 mBufferQueue.add(pInBuffer);
3517 } else if (mActive) {
3518 stop();
3519 }
3520 }
3521
3522 return outputBufferFull;
3523}
3524
3525status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3526{
3527 int active;
3528 status_t result;
3529 audio_track_cblk_t* cblk = mCblk;
3530 uint32_t framesReq = buffer->frameCount;
3531
3532// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3533 buffer->frameCount = 0;
3534
3535 uint32_t framesAvail = cblk->framesAvailable();
3536
3537
3538 if (framesAvail == 0) {
3539 Mutex::Autolock _l(cblk->lock);
3540 goto start_loop_here;
3541 while (framesAvail == 0) {
3542 active = mActive;
3543 if (UNLIKELY(!active)) {
3544 LOGV("Not active and NO_MORE_BUFFERS");
3545 return AudioTrack::NO_MORE_BUFFERS;
3546 }
3547 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3548 if (result != NO_ERROR) {
3549 return AudioTrack::NO_MORE_BUFFERS;
3550 }
3551 // read the server count again
3552 start_loop_here:
3553 framesAvail = cblk->framesAvailable_l();
3554 }
3555 }
3556
3557// if (framesAvail < framesReq) {
3558// return AudioTrack::NO_MORE_BUFFERS;
3559// }
3560
3561 if (framesReq > framesAvail) {
3562 framesReq = framesAvail;
3563 }
3564
3565 uint32_t u = cblk->user;
3566 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3567
3568 if (u + framesReq > bufferEnd) {
3569 framesReq = bufferEnd - u;
3570 }
3571
3572 buffer->frameCount = framesReq;
3573 buffer->raw = (void *)cblk->buffer(u);
3574 return NO_ERROR;
3575}
3576
3577
3578void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3579{
3580 size_t size = mBufferQueue.size();
3581 Buffer *pBuffer;
3582
3583 for (size_t i = 0; i < size; i++) {
3584 pBuffer = mBufferQueue.itemAt(i);
3585 delete [] pBuffer->mBuffer;
3586 delete pBuffer;
3587 }
3588 mBufferQueue.clear();
3589}
3590
3591// ----------------------------------------------------------------------------
3592
3593AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3594 : RefBase(),
3595 mAudioFlinger(audioFlinger),
3596 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3597 mPid(pid)
3598{
3599 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3600}
3601
3602// Client destructor must be called with AudioFlinger::mLock held
3603AudioFlinger::Client::~Client()
3604{
3605 mAudioFlinger->removeClient_l(mPid);
3606}
3607
3608const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3609{
3610 return mMemoryDealer;
3611}
3612
3613// ----------------------------------------------------------------------------
3614
3615AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3616 const sp<IAudioFlingerClient>& client,
3617 pid_t pid)
3618 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3619{
3620}
3621
3622AudioFlinger::NotificationClient::~NotificationClient()
3623{
3624 mClient.clear();
3625}
3626
3627void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3628{
3629 sp<NotificationClient> keep(this);
3630 {
3631 mAudioFlinger->removeNotificationClient(mPid);
3632 }
3633}
3634
3635// ----------------------------------------------------------------------------
3636
3637AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3638 : BnAudioTrack(),
3639 mTrack(track)
3640{
3641}
3642
3643AudioFlinger::TrackHandle::~TrackHandle() {
3644 // just stop the track on deletion, associated resources
3645 // will be freed from the main thread once all pending buffers have
3646 // been played. Unless it's not in the active track list, in which
3647 // case we free everything now...
3648 mTrack->destroy();
3649}
3650
3651status_t AudioFlinger::TrackHandle::start() {
3652 return mTrack->start();
3653}
3654
3655void AudioFlinger::TrackHandle::stop() {
3656 mTrack->stop();
3657}
3658
3659void AudioFlinger::TrackHandle::flush() {
3660 mTrack->flush();
3661}
3662
3663void AudioFlinger::TrackHandle::mute(bool e) {
3664 mTrack->mute(e);
3665}
3666
3667void AudioFlinger::TrackHandle::pause() {
3668 mTrack->pause();
3669}
3670
3671void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3672 mTrack->setVolume(left, right);
3673}
3674
3675sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3676 return mTrack->getCblk();
3677}
3678
3679status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3680{
3681 return mTrack->attachAuxEffect(EffectId);
3682}
3683
3684status_t AudioFlinger::TrackHandle::onTransact(
3685 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3686{
3687 return BnAudioTrack::onTransact(code, data, reply, flags);
3688}
3689
3690// ----------------------------------------------------------------------------
3691
3692sp<IAudioRecord> AudioFlinger::openRecord(
3693 pid_t pid,
3694 int input,
3695 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003696 uint32_t format,
3697 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 int frameCount,
3699 uint32_t flags,
3700 int *sessionId,
3701 status_t *status)
3702{
3703 sp<RecordThread::RecordTrack> recordTrack;
3704 sp<RecordHandle> recordHandle;
3705 sp<Client> client;
3706 wp<Client> wclient;
3707 status_t lStatus;
3708 RecordThread *thread;
3709 size_t inFrameCount;
3710 int lSessionId;
3711
3712 // check calling permissions
3713 if (!recordingAllowed()) {
3714 lStatus = PERMISSION_DENIED;
3715 goto Exit;
3716 }
3717
3718 // add client to list
3719 { // scope for mLock
3720 Mutex::Autolock _l(mLock);
3721 thread = checkRecordThread_l(input);
3722 if (thread == NULL) {
3723 lStatus = BAD_VALUE;
3724 goto Exit;
3725 }
3726
3727 wclient = mClients.valueFor(pid);
3728 if (wclient != NULL) {
3729 client = wclient.promote();
3730 } else {
3731 client = new Client(this, pid);
3732 mClients.add(pid, client);
3733 }
3734
3735 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07003736 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003737 lSessionId = *sessionId;
3738 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003739 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003740 if (sessionId != NULL) {
3741 *sessionId = lSessionId;
3742 }
3743 }
3744 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003745 recordTrack = thread->createRecordTrack_l(client,
3746 sampleRate,
3747 format,
3748 channelMask,
3749 frameCount,
3750 flags,
3751 lSessionId,
3752 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003753 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003754 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3756 // destructor is called by the TrackBase destructor with mLock held
3757 client.clear();
3758 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003759 goto Exit;
3760 }
3761
3762 // return to handle to client
3763 recordHandle = new RecordHandle(recordTrack);
3764 lStatus = NO_ERROR;
3765
3766Exit:
3767 if (status) {
3768 *status = lStatus;
3769 }
3770 return recordHandle;
3771}
3772
3773// ----------------------------------------------------------------------------
3774
3775AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3776 : BnAudioRecord(),
3777 mRecordTrack(recordTrack)
3778{
3779}
3780
3781AudioFlinger::RecordHandle::~RecordHandle() {
3782 stop();
3783}
3784
3785status_t AudioFlinger::RecordHandle::start() {
3786 LOGV("RecordHandle::start()");
3787 return mRecordTrack->start();
3788}
3789
3790void AudioFlinger::RecordHandle::stop() {
3791 LOGV("RecordHandle::stop()");
3792 mRecordTrack->stop();
3793}
3794
3795sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3796 return mRecordTrack->getCblk();
3797}
3798
3799status_t AudioFlinger::RecordHandle::onTransact(
3800 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3801{
3802 return BnAudioRecord::onTransact(code, data, reply, flags);
3803}
3804
3805// ----------------------------------------------------------------------------
3806
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003807AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
3808 AudioStreamIn *input,
3809 uint32_t sampleRate,
3810 uint32_t channels,
3811 int id,
3812 uint32_t device) :
3813 ThreadBase(audioFlinger, id, device),
3814 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003816 mType = ThreadBase::RECORD;
Dima Zavinfce7a472011-04-19 22:30:36 -07003817 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003818 mReqSampleRate = sampleRate;
3819 readInputParameters();
3820}
3821
3822
3823AudioFlinger::RecordThread::~RecordThread()
3824{
3825 delete[] mRsmpInBuffer;
3826 if (mResampler != 0) {
3827 delete mResampler;
3828 delete[] mRsmpOutBuffer;
3829 }
3830}
3831
3832void AudioFlinger::RecordThread::onFirstRef()
3833{
3834 const size_t SIZE = 256;
3835 char buffer[SIZE];
3836
3837 snprintf(buffer, SIZE, "Record Thread %p", this);
3838
3839 run(buffer, PRIORITY_URGENT_AUDIO);
3840}
3841
3842bool AudioFlinger::RecordThread::threadLoop()
3843{
3844 AudioBufferProvider::Buffer buffer;
3845 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003846 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003847
Eric Laurent44d98482010-09-30 16:12:31 -07003848 nsecs_t lastWarning = 0;
3849
Mathias Agopian65ab4712010-07-14 17:59:35 -07003850 // start recording
3851 while (!exitPending()) {
3852
3853 processConfigEvents();
3854
3855 { // scope for mLock
3856 Mutex::Autolock _l(mLock);
3857 checkForNewParameters_l();
3858 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3859 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003860 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003861 mStandby = true;
3862 }
3863
3864 if (exitPending()) break;
3865
3866 LOGV("RecordThread: loop stopping");
3867 // go to sleep
3868 mWaitWorkCV.wait(mLock);
3869 LOGV("RecordThread: loop starting");
3870 continue;
3871 }
3872 if (mActiveTrack != 0) {
3873 if (mActiveTrack->mState == TrackBase::PAUSING) {
3874 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003875 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003876 mStandby = true;
3877 }
3878 mActiveTrack.clear();
3879 mStartStopCond.broadcast();
3880 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3881 if (mReqChannelCount != mActiveTrack->channelCount()) {
3882 mActiveTrack.clear();
3883 mStartStopCond.broadcast();
3884 } else if (mBytesRead != 0) {
3885 // record start succeeds only if first read from audio input
3886 // succeeds
3887 if (mBytesRead > 0) {
3888 mActiveTrack->mState = TrackBase::ACTIVE;
3889 } else {
3890 mActiveTrack.clear();
3891 }
3892 mStartStopCond.broadcast();
3893 }
3894 mStandby = false;
3895 }
3896 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003897 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898 }
3899
3900 if (mActiveTrack != 0) {
3901 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3902 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003903 unlockEffectChains(effectChains);
3904 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003905 continue;
3906 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003907 for (size_t i = 0; i < effectChains.size(); i ++) {
3908 effectChains[i]->process_l();
3909 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003910
Mathias Agopian65ab4712010-07-14 17:59:35 -07003911 buffer.frameCount = mFrameCount;
3912 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3913 size_t framesOut = buffer.frameCount;
3914 if (mResampler == 0) {
3915 // no resampling
3916 while (framesOut) {
3917 size_t framesIn = mFrameCount - mRsmpInIndex;
3918 if (framesIn) {
3919 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3920 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3921 if (framesIn > framesOut)
3922 framesIn = framesOut;
3923 mRsmpInIndex += framesIn;
3924 framesOut -= framesIn;
3925 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07003926 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003927 memcpy(dst, src, framesIn * mFrameSize);
3928 } else {
3929 int16_t *src16 = (int16_t *)src;
3930 int16_t *dst16 = (int16_t *)dst;
3931 if (mChannelCount == 1) {
3932 while (framesIn--) {
3933 *dst16++ = *src16;
3934 *dst16++ = *src16++;
3935 }
3936 } else {
3937 while (framesIn--) {
3938 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3939 src16 += 2;
3940 }
3941 }
3942 }
3943 }
3944 if (framesOut && mFrameCount == mRsmpInIndex) {
3945 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07003946 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003947 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003948 framesOut = 0;
3949 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07003950 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 mRsmpInIndex = 0;
3952 }
3953 if (mBytesRead < 0) {
3954 LOGE("Error reading audio input");
3955 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3956 // Force input into standby so that it tries to
3957 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07003958 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003959 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003960 }
3961 mRsmpInIndex = mFrameCount;
3962 framesOut = 0;
3963 buffer.frameCount = 0;
3964 }
3965 }
3966 }
3967 } else {
3968 // resampling
3969
3970 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3971 // alter output frame count as if we were expecting stereo samples
3972 if (mChannelCount == 1 && mReqChannelCount == 1) {
3973 framesOut >>= 1;
3974 }
3975 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3976 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3977 // are 32 bit aligned which should be always true.
3978 if (mChannelCount == 2 && mReqChannelCount == 1) {
3979 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3980 // the resampler always outputs stereo samples: do post stereo to mono conversion
3981 int16_t *src = (int16_t *)mRsmpOutBuffer;
3982 int16_t *dst = buffer.i16;
3983 while (framesOut--) {
3984 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3985 src += 2;
3986 }
3987 } else {
3988 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3989 }
3990
3991 }
3992 mActiveTrack->releaseBuffer(&buffer);
3993 mActiveTrack->overflow();
3994 }
3995 // client isn't retrieving buffers fast enough
3996 else {
Eric Laurent44d98482010-09-30 16:12:31 -07003997 if (!mActiveTrack->setOverflow()) {
3998 nsecs_t now = systemTime();
3999 if ((now - lastWarning) > kWarningThrottle) {
4000 LOGW("RecordThread: buffer overflow");
4001 lastWarning = now;
4002 }
4003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004004 // Release the processor for a while before asking for a new buffer.
4005 // This will give the application more chance to read from the buffer and
4006 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004007 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 }
4009 }
Eric Laurentec437d82011-07-26 20:54:46 -07004010 // enable changes in effect chain
4011 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004012 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013 }
4014
4015 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004016 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004017 }
4018 mActiveTrack.clear();
4019
4020 mStartStopCond.broadcast();
4021
4022 LOGV("RecordThread %p exiting", this);
4023 return false;
4024}
4025
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004026
4027sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4028 const sp<AudioFlinger::Client>& client,
4029 uint32_t sampleRate,
4030 int format,
4031 int channelMask,
4032 int frameCount,
4033 uint32_t flags,
4034 int sessionId,
4035 status_t *status)
4036{
4037 sp<RecordTrack> track;
4038 status_t lStatus;
4039
4040 lStatus = initCheck();
4041 if (lStatus != NO_ERROR) {
4042 LOGE("Audio driver not initialized.");
4043 goto Exit;
4044 }
4045
4046 { // scope for mLock
4047 Mutex::Autolock _l(mLock);
4048
4049 track = new RecordTrack(this, client, sampleRate,
4050 format, channelMask, frameCount, flags, sessionId);
4051
4052 if (track->getCblk() == NULL) {
4053 lStatus = NO_MEMORY;
4054 goto Exit;
4055 }
4056
4057 mTrack = track.get();
4058
4059 }
4060 lStatus = NO_ERROR;
4061
4062Exit:
4063 if (status) {
4064 *status = lStatus;
4065 }
4066 return track;
4067}
4068
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4070{
4071 LOGV("RecordThread::start");
4072 sp <ThreadBase> strongMe = this;
4073 status_t status = NO_ERROR;
4074 {
4075 AutoMutex lock(&mLock);
4076 if (mActiveTrack != 0) {
4077 if (recordTrack != mActiveTrack.get()) {
4078 status = -EBUSY;
4079 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4080 mActiveTrack->mState = TrackBase::ACTIVE;
4081 }
4082 return status;
4083 }
4084
4085 recordTrack->mState = TrackBase::IDLE;
4086 mActiveTrack = recordTrack;
4087 mLock.unlock();
4088 status_t status = AudioSystem::startInput(mId);
4089 mLock.lock();
4090 if (status != NO_ERROR) {
4091 mActiveTrack.clear();
4092 return status;
4093 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 mRsmpInIndex = mFrameCount;
4095 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004096 if (mResampler != NULL) {
4097 mResampler->reset();
4098 }
4099 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100 // signal thread to start
4101 LOGV("Signal record thread");
4102 mWaitWorkCV.signal();
4103 // do not wait for mStartStopCond if exiting
4104 if (mExiting) {
4105 mActiveTrack.clear();
4106 status = INVALID_OPERATION;
4107 goto startError;
4108 }
4109 mStartStopCond.wait(mLock);
4110 if (mActiveTrack == 0) {
4111 LOGV("Record failed to start");
4112 status = BAD_VALUE;
4113 goto startError;
4114 }
4115 LOGV("Record started OK");
4116 return status;
4117 }
4118startError:
4119 AudioSystem::stopInput(mId);
4120 return status;
4121}
4122
4123void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4124 LOGV("RecordThread::stop");
4125 sp <ThreadBase> strongMe = this;
4126 {
4127 AutoMutex lock(&mLock);
4128 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4129 mActiveTrack->mState = TrackBase::PAUSING;
4130 // do not wait for mStartStopCond if exiting
4131 if (mExiting) {
4132 return;
4133 }
4134 mStartStopCond.wait(mLock);
4135 // if we have been restarted, recordTrack == mActiveTrack.get() here
4136 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4137 mLock.unlock();
4138 AudioSystem::stopInput(mId);
4139 mLock.lock();
4140 LOGV("Record stopped OK");
4141 }
4142 }
4143 }
4144}
4145
4146status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4147{
4148 const size_t SIZE = 256;
4149 char buffer[SIZE];
4150 String8 result;
4151 pid_t pid = 0;
4152
4153 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4154 result.append(buffer);
4155
4156 if (mActiveTrack != 0) {
4157 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004158 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004159 mActiveTrack->dump(buffer, SIZE);
4160 result.append(buffer);
4161
4162 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4163 result.append(buffer);
4164 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4165 result.append(buffer);
4166 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4167 result.append(buffer);
4168 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4169 result.append(buffer);
4170 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4171 result.append(buffer);
4172
4173
4174 } else {
4175 result.append("No record client\n");
4176 }
4177 write(fd, result.string(), result.size());
4178
4179 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004180 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004181
4182 return NO_ERROR;
4183}
4184
4185status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4186{
4187 size_t framesReq = buffer->frameCount;
4188 size_t framesReady = mFrameCount - mRsmpInIndex;
4189 int channelCount;
4190
4191 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004192 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 if (mBytesRead < 0) {
4194 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4195 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4196 // Force input into standby so that it tries to
4197 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004198 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004199 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 }
4201 buffer->raw = 0;
4202 buffer->frameCount = 0;
4203 return NOT_ENOUGH_DATA;
4204 }
4205 mRsmpInIndex = 0;
4206 framesReady = mFrameCount;
4207 }
4208
4209 if (framesReq > framesReady) {
4210 framesReq = framesReady;
4211 }
4212
4213 if (mChannelCount == 1 && mReqChannelCount == 2) {
4214 channelCount = 1;
4215 } else {
4216 channelCount = 2;
4217 }
4218 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4219 buffer->frameCount = framesReq;
4220 return NO_ERROR;
4221}
4222
4223void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4224{
4225 mRsmpInIndex += buffer->frameCount;
4226 buffer->frameCount = 0;
4227}
4228
4229bool AudioFlinger::RecordThread::checkForNewParameters_l()
4230{
4231 bool reconfig = false;
4232
4233 while (!mNewParameters.isEmpty()) {
4234 status_t status = NO_ERROR;
4235 String8 keyValuePair = mNewParameters[0];
4236 AudioParameter param = AudioParameter(keyValuePair);
4237 int value;
4238 int reqFormat = mFormat;
4239 int reqSamplingRate = mReqSampleRate;
4240 int reqChannelCount = mReqChannelCount;
4241
4242 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4243 reqSamplingRate = value;
4244 reconfig = true;
4245 }
4246 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4247 reqFormat = value;
4248 reconfig = true;
4249 }
4250 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004251 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004252 reconfig = true;
4253 }
4254 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4255 // do not accept frame count changes if tracks are open as the track buffer
4256 // size depends on frame count and correct behavior would not be garantied
4257 // if frame count is changed after track creation
4258 if (mActiveTrack != 0) {
4259 status = INVALID_OPERATION;
4260 } else {
4261 reconfig = true;
4262 }
4263 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004264 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4265 // forward device change to effects that have requested to be
4266 // aware of attached audio device.
4267 for (size_t i = 0; i < mEffectChains.size(); i++) {
4268 mEffectChains[i]->setDevice_l(value);
4269 }
4270 // store input device and output device but do not forward output device to audio HAL.
4271 // Note that status is ignored by the caller for output device
4272 // (see AudioFlinger::setParameters()
4273 if (value & AUDIO_DEVICE_OUT_ALL) {
4274 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4275 status = BAD_VALUE;
4276 } else {
4277 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4278 }
4279 mDevice |= (uint32_t)value;
4280 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004282 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004284 mInput->stream->common.standby(&mInput->stream->common);
4285 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 }
4287 if (reconfig) {
4288 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004289 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004290 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004291 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4292 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004293 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294 status = NO_ERROR;
4295 }
4296 if (status == NO_ERROR) {
4297 readInputParameters();
4298 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4299 }
4300 }
4301 }
4302
4303 mNewParameters.removeAt(0);
4304
4305 mParamStatus = status;
4306 mParamCond.signal();
4307 mWaitWorkCV.wait(mLock);
4308 }
4309 return reconfig;
4310}
4311
4312String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4313{
Dima Zavinfce7a472011-04-19 22:30:36 -07004314 char *s;
4315 String8 out_s8;
4316
Dima Zavin799a70e2011-04-18 16:57:27 -07004317 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004318 out_s8 = String8(s);
4319 free(s);
4320 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004321}
4322
4323void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4324 AudioSystem::OutputDescriptor desc;
4325 void *param2 = 0;
4326
4327 switch (event) {
4328 case AudioSystem::INPUT_OPENED:
4329 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004330 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 desc.samplingRate = mSampleRate;
4332 desc.format = mFormat;
4333 desc.frameCount = mFrameCount;
4334 desc.latency = 0;
4335 param2 = &desc;
4336 break;
4337
4338 case AudioSystem::INPUT_CLOSED:
4339 default:
4340 break;
4341 }
4342 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4343}
4344
4345void AudioFlinger::RecordThread::readInputParameters()
4346{
4347 if (mRsmpInBuffer) delete mRsmpInBuffer;
4348 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4349 if (mResampler) delete mResampler;
4350 mResampler = 0;
4351
Dima Zavin799a70e2011-04-18 16:57:27 -07004352 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004353 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4354 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004355 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4356 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4357 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004358 mFrameCount = mInputBytes / mFrameSize;
4359 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4360
4361 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4362 {
4363 int channelCount;
4364 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4365 // stereo to mono post process as the resampler always outputs stereo.
4366 if (mChannelCount == 1 && mReqChannelCount == 2) {
4367 channelCount = 1;
4368 } else {
4369 channelCount = 2;
4370 }
4371 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4372 mResampler->setSampleRate(mSampleRate);
4373 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4374 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4375
4376 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4377 if (mChannelCount == 1 && mReqChannelCount == 1) {
4378 mFrameCount >>= 1;
4379 }
4380
4381 }
4382 mRsmpInIndex = mFrameCount;
4383}
4384
4385unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4386{
Dima Zavin799a70e2011-04-18 16:57:27 -07004387 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004388}
4389
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004390uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4391{
4392 Mutex::Autolock _l(mLock);
4393 uint32_t result = 0;
4394 if (getEffectChain_l(sessionId) != 0) {
4395 result = EFFECT_SESSION;
4396 }
4397
4398 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4399 result |= TRACK_SESSION;
4400 }
4401
4402 return result;
4403}
4404
Mathias Agopian65ab4712010-07-14 17:59:35 -07004405// ----------------------------------------------------------------------------
4406
4407int AudioFlinger::openOutput(uint32_t *pDevices,
4408 uint32_t *pSamplingRate,
4409 uint32_t *pFormat,
4410 uint32_t *pChannels,
4411 uint32_t *pLatencyMs,
4412 uint32_t flags)
4413{
4414 status_t status;
4415 PlaybackThread *thread = NULL;
4416 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4417 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4418 uint32_t format = pFormat ? *pFormat : 0;
4419 uint32_t channels = pChannels ? *pChannels : 0;
4420 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004421 audio_stream_out_t *outStream;
4422 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004423
4424 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4425 pDevices ? *pDevices : 0,
4426 samplingRate,
4427 format,
4428 channels,
4429 flags);
4430
4431 if (pDevices == NULL || *pDevices == 0) {
4432 return 0;
4433 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004434
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435 Mutex::Autolock _l(mLock);
4436
Dima Zavin799a70e2011-04-18 16:57:27 -07004437 outHwDev = findSuitableHwDev_l(*pDevices);
4438 if (outHwDev == NULL)
4439 return 0;
4440
4441 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4442 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004443 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004444 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 samplingRate,
4446 format,
4447 channels,
4448 status);
4449
4450 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004451 if (outStream != NULL) {
4452 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004453 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004454
Dima Zavinfce7a472011-04-19 22:30:36 -07004455 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4456 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4457 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004458 thread = new DirectOutputThread(this, output, id, *pDevices);
4459 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4460 } else {
4461 thread = new MixerThread(this, output, id, *pDevices);
4462 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004463 }
4464 mPlaybackThreads.add(id, thread);
4465
4466 if (pSamplingRate) *pSamplingRate = samplingRate;
4467 if (pFormat) *pFormat = format;
4468 if (pChannels) *pChannels = channels;
4469 if (pLatencyMs) *pLatencyMs = thread->latency();
4470
4471 // notify client processes of the new output creation
4472 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4473 return id;
4474 }
4475
4476 return 0;
4477}
4478
4479int AudioFlinger::openDuplicateOutput(int output1, int output2)
4480{
4481 Mutex::Autolock _l(mLock);
4482 MixerThread *thread1 = checkMixerThread_l(output1);
4483 MixerThread *thread2 = checkMixerThread_l(output2);
4484
4485 if (thread1 == NULL || thread2 == NULL) {
4486 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4487 return 0;
4488 }
4489
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004490 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004491 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4492 thread->addOutputTrack(thread2);
4493 mPlaybackThreads.add(id, thread);
4494 // notify client processes of the new output creation
4495 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4496 return id;
4497}
4498
4499status_t AudioFlinger::closeOutput(int output)
4500{
4501 // keep strong reference on the playback thread so that
4502 // it is not destroyed while exit() is executed
4503 sp <PlaybackThread> thread;
4504 {
4505 Mutex::Autolock _l(mLock);
4506 thread = checkPlaybackThread_l(output);
4507 if (thread == NULL) {
4508 return BAD_VALUE;
4509 }
4510
4511 LOGV("closeOutput() %d", output);
4512
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004513 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004515 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4517 dupThread->removeOutputTrack((MixerThread *)thread.get());
4518 }
4519 }
4520 }
4521 void *param2 = 0;
4522 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4523 mPlaybackThreads.removeItem(output);
4524 }
4525 thread->exit();
4526
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004527 if (thread->type() != ThreadBase::DUPLICATING) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004528 AudioStreamOut *out = thread->getOutput();
4529 out->hwDev->close_output_stream(out->hwDev, out->stream);
4530 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004531 }
4532 return NO_ERROR;
4533}
4534
4535status_t AudioFlinger::suspendOutput(int output)
4536{
4537 Mutex::Autolock _l(mLock);
4538 PlaybackThread *thread = checkPlaybackThread_l(output);
4539
4540 if (thread == NULL) {
4541 return BAD_VALUE;
4542 }
4543
4544 LOGV("suspendOutput() %d", output);
4545 thread->suspend();
4546
4547 return NO_ERROR;
4548}
4549
4550status_t AudioFlinger::restoreOutput(int output)
4551{
4552 Mutex::Autolock _l(mLock);
4553 PlaybackThread *thread = checkPlaybackThread_l(output);
4554
4555 if (thread == NULL) {
4556 return BAD_VALUE;
4557 }
4558
4559 LOGV("restoreOutput() %d", output);
4560
4561 thread->restore();
4562
4563 return NO_ERROR;
4564}
4565
4566int AudioFlinger::openInput(uint32_t *pDevices,
4567 uint32_t *pSamplingRate,
4568 uint32_t *pFormat,
4569 uint32_t *pChannels,
4570 uint32_t acoustics)
4571{
4572 status_t status;
4573 RecordThread *thread = NULL;
4574 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4575 uint32_t format = pFormat ? *pFormat : 0;
4576 uint32_t channels = pChannels ? *pChannels : 0;
4577 uint32_t reqSamplingRate = samplingRate;
4578 uint32_t reqFormat = format;
4579 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004580 audio_stream_in_t *inStream;
4581 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004582
4583 if (pDevices == NULL || *pDevices == 0) {
4584 return 0;
4585 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004586
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 Mutex::Autolock _l(mLock);
4588
Dima Zavin799a70e2011-04-18 16:57:27 -07004589 inHwDev = findSuitableHwDev_l(*pDevices);
4590 if (inHwDev == NULL)
4591 return 0;
4592
4593 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4594 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004595 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004596 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004597 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004598 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 samplingRate,
4600 format,
4601 channels,
4602 acoustics,
4603 status);
4604
4605 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4606 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4607 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07004608 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004609 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004611 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07004613 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4614 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004615 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004616 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004617 }
4618
Dima Zavin799a70e2011-04-18 16:57:27 -07004619 if (inStream != NULL) {
4620 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4621
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004622 int id = nextUniqueId();
4623 // Start record thread
4624 // RecorThread require both input and output device indication to forward to audio
4625 // pre processing modules
4626 uint32_t device = (*pDevices) | primaryOutputDevice_l();
4627 thread = new RecordThread(this,
4628 input,
4629 reqSamplingRate,
4630 reqChannels,
4631 id,
4632 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004633 mRecordThreads.add(id, thread);
4634 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4635 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4636 if (pFormat) *pFormat = format;
4637 if (pChannels) *pChannels = reqChannels;
4638
Dima Zavin799a70e2011-04-18 16:57:27 -07004639 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004640
4641 // notify client processes of the new input creation
4642 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4643 return id;
4644 }
4645
4646 return 0;
4647}
4648
4649status_t AudioFlinger::closeInput(int input)
4650{
4651 // keep strong reference on the record thread so that
4652 // it is not destroyed while exit() is executed
4653 sp <RecordThread> thread;
4654 {
4655 Mutex::Autolock _l(mLock);
4656 thread = checkRecordThread_l(input);
4657 if (thread == NULL) {
4658 return BAD_VALUE;
4659 }
4660
4661 LOGV("closeInput() %d", input);
4662 void *param2 = 0;
4663 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4664 mRecordThreads.removeItem(input);
4665 }
4666 thread->exit();
4667
Dima Zavin799a70e2011-04-18 16:57:27 -07004668 AudioStreamIn *in = thread->getInput();
4669 in->hwDev->close_input_stream(in->hwDev, in->stream);
4670 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004671
4672 return NO_ERROR;
4673}
4674
4675status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4676{
4677 Mutex::Autolock _l(mLock);
4678 MixerThread *dstThread = checkMixerThread_l(output);
4679 if (dstThread == NULL) {
4680 LOGW("setStreamOutput() bad output id %d", output);
4681 return BAD_VALUE;
4682 }
4683
4684 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4685 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4686
4687 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4688 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4689 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004690 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004691 MixerThread *srcThread = (MixerThread *)thread;
4692 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004693 }
Eric Laurentde070132010-07-13 04:45:46 -07004694 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695
4696 return NO_ERROR;
4697}
4698
4699
4700int AudioFlinger::newAudioSessionId()
4701{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004702 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004703}
4704
4705// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4706AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4707{
4708 PlaybackThread *thread = NULL;
4709 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4710 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4711 }
4712 return thread;
4713}
4714
4715// checkMixerThread_l() must be called with AudioFlinger::mLock held
4716AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4717{
4718 PlaybackThread *thread = checkPlaybackThread_l(output);
4719 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004720 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 thread = NULL;
4722 }
4723 }
4724 return (MixerThread *)thread;
4725}
4726
4727// checkRecordThread_l() must be called with AudioFlinger::mLock held
4728AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4729{
4730 RecordThread *thread = NULL;
4731 if (mRecordThreads.indexOfKey(input) >= 0) {
4732 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4733 }
4734 return thread;
4735}
4736
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004737uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004738{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004739 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740}
4741
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004742AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
4743{
4744 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4745 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4746 if (thread->getOutput()->hwDev == mPrimaryHardwareDev) {
4747 return thread;
4748 }
4749 }
4750 return NULL;
4751}
4752
4753uint32_t AudioFlinger::primaryOutputDevice_l()
4754{
4755 PlaybackThread *thread = primaryPlaybackThread_l();
4756
4757 if (thread == NULL) {
4758 return 0;
4759 }
4760
4761 return thread->device();
4762}
4763
4764
Mathias Agopian65ab4712010-07-14 17:59:35 -07004765// ----------------------------------------------------------------------------
4766// Effect management
4767// ----------------------------------------------------------------------------
4768
4769
Mathias Agopian65ab4712010-07-14 17:59:35 -07004770status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4771{
4772 Mutex::Autolock _l(mLock);
4773 return EffectQueryNumberEffects(numEffects);
4774}
4775
4776status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4777{
4778 Mutex::Autolock _l(mLock);
4779 return EffectQueryEffect(index, descriptor);
4780}
4781
4782status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4783{
4784 Mutex::Autolock _l(mLock);
4785 return EffectGetDescriptor(pUuid, descriptor);
4786}
4787
4788
4789// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4790static const effect_uuid_t VISUALIZATION_UUID_ =
4791 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4792
4793sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4794 effect_descriptor_t *pDesc,
4795 const sp<IEffectClient>& effectClient,
4796 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004797 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004798 int sessionId,
4799 status_t *status,
4800 int *id,
4801 int *enabled)
4802{
4803 status_t lStatus = NO_ERROR;
4804 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004805 effect_descriptor_t desc;
4806 sp<Client> client;
4807 wp<Client> wclient;
4808
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004809 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
4810 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004811
4812 if (pDesc == NULL) {
4813 lStatus = BAD_VALUE;
4814 goto Exit;
4815 }
4816
Eric Laurent84e9a102010-09-23 16:10:16 -07004817 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07004818 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004819 lStatus = PERMISSION_DENIED;
4820 goto Exit;
4821 }
4822
Dima Zavinfce7a472011-04-19 22:30:36 -07004823 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07004824 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07004825 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004826 lStatus = PERMISSION_DENIED;
4827 goto Exit;
4828 }
4829
4830 // check recording permission for visualizer
4831 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4832 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4833 !recordingAllowed()) {
4834 lStatus = PERMISSION_DENIED;
4835 goto Exit;
4836 }
4837
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004838 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004839 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004840 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07004841 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07004842 lStatus = BAD_VALUE;
4843 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07004844 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004845 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004846 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07004847 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004848 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07004849 }
4850 }
4851
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852 {
4853 Mutex::Autolock _l(mLock);
4854
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855
4856 if (!EffectIsNullUuid(&pDesc->uuid)) {
4857 // if uuid is specified, request effect descriptor
4858 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4859 if (lStatus < 0) {
4860 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4861 goto Exit;
4862 }
4863 } else {
4864 // if uuid is not specified, look for an available implementation
4865 // of the required type in effect factory
4866 if (EffectIsNullUuid(&pDesc->type)) {
4867 LOGW("createEffect() no effect type");
4868 lStatus = BAD_VALUE;
4869 goto Exit;
4870 }
4871 uint32_t numEffects = 0;
4872 effect_descriptor_t d;
4873 bool found = false;
4874
4875 lStatus = EffectQueryNumberEffects(&numEffects);
4876 if (lStatus < 0) {
4877 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4878 goto Exit;
4879 }
4880 for (uint32_t i = 0; i < numEffects; i++) {
4881 lStatus = EffectQueryEffect(i, &desc);
4882 if (lStatus < 0) {
4883 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4884 continue;
4885 }
4886 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4887 // If matching type found save effect descriptor. If the session is
4888 // 0 and the effect is not auxiliary, continue enumeration in case
4889 // an auxiliary version of this effect type is available
4890 found = true;
4891 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07004892 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4894 break;
4895 }
4896 }
4897 }
4898 if (!found) {
4899 lStatus = BAD_VALUE;
4900 LOGW("createEffect() effect not found");
4901 goto Exit;
4902 }
4903 // For same effect type, chose auxiliary version over insert version if
4904 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07004905 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004906 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4907 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4908 }
4909 }
4910
4911 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004912 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4914 lStatus = INVALID_OPERATION;
4915 goto Exit;
4916 }
4917
Mathias Agopian65ab4712010-07-14 17:59:35 -07004918 // return effect descriptor
4919 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4920
4921 // If output is not specified try to find a matching audio session ID in one of the
4922 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004923 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4924 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004925 // Note: io is never 0 when creating an effect on an input
4926 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004927 // look for the thread where the specified audio session is present
4928 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4929 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004930 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07004931 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004934 if (io == 0) {
4935 for (size_t i = 0; i < mRecordThreads.size(); i++) {
4936 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4937 io = mRecordThreads.keyAt(i);
4938 break;
4939 }
4940 }
4941 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004942 // If no output thread contains the requested session ID, default to
4943 // first output. The effect chain will be moved to the correct output
4944 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004945 if (io == 0 && mPlaybackThreads.size()) {
4946 io = mPlaybackThreads.keyAt(0);
4947 }
4948 LOGV("createEffect() got io %d for effect %s", io, desc.name);
4949 }
4950 ThreadBase *thread = checkRecordThread_l(io);
4951 if (thread == NULL) {
4952 thread = checkPlaybackThread_l(io);
4953 if (thread == NULL) {
4954 LOGE("createEffect() unknown output thread");
4955 lStatus = BAD_VALUE;
4956 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07004957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004959
Mathias Agopian65ab4712010-07-14 17:59:35 -07004960 wclient = mClients.valueFor(pid);
4961
4962 if (wclient != NULL) {
4963 client = wclient.promote();
4964 } else {
4965 client = new Client(this, pid);
4966 mClients.add(pid, client);
4967 }
4968
4969 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07004970 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4971 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004972 if (handle != 0 && id != NULL) {
4973 *id = handle->id();
4974 }
4975 }
4976
4977Exit:
4978 if(status) {
4979 *status = lStatus;
4980 }
4981 return handle;
4982}
4983
Eric Laurentde070132010-07-13 04:45:46 -07004984status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4985{
4986 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4987 session, srcOutput, dstOutput);
4988 Mutex::Autolock _l(mLock);
4989 if (srcOutput == dstOutput) {
4990 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4991 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004992 }
Eric Laurentde070132010-07-13 04:45:46 -07004993 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4994 if (srcThread == NULL) {
4995 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4996 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004997 }
Eric Laurentde070132010-07-13 04:45:46 -07004998 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4999 if (dstThread == NULL) {
5000 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5001 return BAD_VALUE;
5002 }
5003
5004 Mutex::Autolock _dl(dstThread->mLock);
5005 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07005006 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005007
Mathias Agopian65ab4712010-07-14 17:59:35 -07005008 return NO_ERROR;
5009}
5010
Eric Laurentde070132010-07-13 04:45:46 -07005011// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
5012status_t AudioFlinger::moveEffectChain_l(int session,
5013 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005014 AudioFlinger::PlaybackThread *dstThread,
5015 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005016{
5017 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
5018 session, srcThread, dstThread);
5019
5020 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
5021 if (chain == 0) {
5022 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
5023 session, srcThread);
5024 return INVALID_OPERATION;
5025 }
5026
Eric Laurent39e94f82010-07-28 01:32:47 -07005027 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005028 // so that a new chain is created with correct parameters when first effect is added. This is
5029 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
5030 // removed.
5031 srcThread->removeEffectChain_l(chain);
5032
5033 // transfer all effects one by one so that new effect chain is created on new thread with
5034 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005035 int dstOutput = dstThread->id();
5036 sp<EffectChain> dstChain;
5037 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07005038 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5039 while (effect != 0) {
5040 srcThread->removeEffect_l(effect);
5041 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07005042 // if the move request is not received from audio policy manager, the effect must be
5043 // re-registered with the new strategy and output
5044 if (dstChain == 0) {
5045 dstChain = effect->chain().promote();
5046 if (dstChain == 0) {
5047 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5048 srcThread->addEffect_l(effect);
5049 return NO_INIT;
5050 }
5051 strategy = dstChain->strategy();
5052 }
5053 if (reRegister) {
5054 AudioSystem::unregisterEffect(effect->id());
5055 AudioSystem::registerEffect(&effect->desc(),
5056 dstOutput,
5057 strategy,
5058 session,
5059 effect->id());
5060 }
Eric Laurentde070132010-07-13 04:45:46 -07005061 effect = chain->getEffectFromId_l(0);
5062 }
5063
5064 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005065}
5066
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005067
Mathias Agopian65ab4712010-07-14 17:59:35 -07005068// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005069sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070 const sp<AudioFlinger::Client>& client,
5071 const sp<IEffectClient>& effectClient,
5072 int32_t priority,
5073 int sessionId,
5074 effect_descriptor_t *desc,
5075 int *enabled,
5076 status_t *status
5077 )
5078{
5079 sp<EffectModule> effect;
5080 sp<EffectHandle> handle;
5081 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005082 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005083 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 bool effectCreated = false;
5085 bool effectRegistered = false;
5086
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005087 lStatus = initCheck();
5088 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005089 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005090 goto Exit;
5091 }
5092
5093 // Do not allow effects with session ID 0 on direct output or duplicating threads
5094 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005095 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005096 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5097 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005098 lStatus = BAD_VALUE;
5099 goto Exit;
5100 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005101 // Only Pre processor effects are allowed on input threads and only on input threads
5102 if ((mType == RECORD &&
5103 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5104 (mType != RECORD &&
5105 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5106 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5107 desc->name, desc->flags, mType);
5108 lStatus = BAD_VALUE;
5109 goto Exit;
5110 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111
5112 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5113
5114 { // scope for mLock
5115 Mutex::Autolock _l(mLock);
5116
5117 // check for existing effect chain with the requested audio session
5118 chain = getEffectChain_l(sessionId);
5119 if (chain == 0) {
5120 // create a new chain for this session
5121 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5122 chain = new EffectChain(this, sessionId);
5123 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005124 chain->setStrategy(getStrategyForSession_l(sessionId));
5125 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005126 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005127 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005128 }
5129
5130 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5131
5132 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005133 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005134 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005135 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136 if (lStatus != NO_ERROR) {
5137 goto Exit;
5138 }
5139 effectRegistered = true;
5140 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005141 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005142 lStatus = effect->status();
5143 if (lStatus != NO_ERROR) {
5144 goto Exit;
5145 }
Eric Laurentcab11242010-07-15 12:50:15 -07005146 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005147 if (lStatus != NO_ERROR) {
5148 goto Exit;
5149 }
5150 effectCreated = true;
5151
5152 effect->setDevice(mDevice);
5153 effect->setMode(mAudioFlinger->getMode());
5154 }
5155 // create effect handle and connect it to effect module
5156 handle = new EffectHandle(effect, client, effectClient, priority);
5157 lStatus = effect->addHandle(handle);
5158 if (enabled) {
5159 *enabled = (int)effect->isEnabled();
5160 }
5161 }
5162
5163Exit:
5164 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005165 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005167 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168 }
5169 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005170 AudioSystem::unregisterEffect(effect->id());
5171 }
5172 if (chainCreated) {
5173 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 }
5175 handle.clear();
5176 }
5177
5178 if(status) {
5179 *status = lStatus;
5180 }
5181 return handle;
5182}
5183
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005184sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5185{
5186 sp<EffectModule> effect;
5187
5188 sp<EffectChain> chain = getEffectChain_l(sessionId);
5189 if (chain != 0) {
5190 effect = chain->getEffectFromId_l(effectId);
5191 }
5192 return effect;
5193}
5194
Eric Laurentde070132010-07-13 04:45:46 -07005195// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5196// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005197status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005198{
5199 // check for existing effect chain with the requested audio session
5200 int sessionId = effect->sessionId();
5201 sp<EffectChain> chain = getEffectChain_l(sessionId);
5202 bool chainCreated = false;
5203
5204 if (chain == 0) {
5205 // create a new chain for this session
5206 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5207 chain = new EffectChain(this, sessionId);
5208 addEffectChain_l(chain);
5209 chain->setStrategy(getStrategyForSession_l(sessionId));
5210 chainCreated = true;
5211 }
5212 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5213
5214 if (chain->getEffectFromId_l(effect->id()) != 0) {
5215 LOGW("addEffect_l() %p effect %s already present in chain %p",
5216 this, effect->desc().name, chain.get());
5217 return BAD_VALUE;
5218 }
5219
5220 status_t status = chain->addEffect_l(effect);
5221 if (status != NO_ERROR) {
5222 if (chainCreated) {
5223 removeEffectChain_l(chain);
5224 }
5225 return status;
5226 }
5227
5228 effect->setDevice(mDevice);
5229 effect->setMode(mAudioFlinger->getMode());
5230 return NO_ERROR;
5231}
5232
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005233void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005234
5235 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005236 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005237 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5238 detachAuxEffect_l(effect->id());
5239 }
5240
5241 sp<EffectChain> chain = effect->chain().promote();
5242 if (chain != 0) {
5243 // remove effect chain if removing last effect
5244 if (chain->removeEffect_l(effect) == 0) {
5245 removeEffectChain_l(chain);
5246 }
5247 } else {
5248 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5249 }
5250}
5251
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005252void AudioFlinger::ThreadBase::lockEffectChains_l(
5253 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5254{
5255 effectChains = mEffectChains;
5256 for (size_t i = 0; i < mEffectChains.size(); i++) {
5257 mEffectChains[i]->lock();
5258 }
5259}
5260
5261void AudioFlinger::ThreadBase::unlockEffectChains(
5262 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5263{
5264 for (size_t i = 0; i < effectChains.size(); i++) {
5265 effectChains[i]->unlock();
5266 }
5267}
5268
5269sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5270{
5271 Mutex::Autolock _l(mLock);
5272 return getEffectChain_l(sessionId);
5273}
5274
5275sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5276{
5277 sp<EffectChain> chain;
5278
5279 size_t size = mEffectChains.size();
5280 for (size_t i = 0; i < size; i++) {
5281 if (mEffectChains[i]->sessionId() == sessionId) {
5282 chain = mEffectChains[i];
5283 break;
5284 }
5285 }
5286 return chain;
5287}
5288
5289void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5290{
5291 Mutex::Autolock _l(mLock);
5292 size_t size = mEffectChains.size();
5293 for (size_t i = 0; i < size; i++) {
5294 mEffectChains[i]->setMode_l(mode);
5295 }
5296}
5297
5298void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurentde070132010-07-13 04:45:46 -07005299 const wp<EffectHandle>& handle) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005300 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005301 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302 // delete the effect module if removing last handle on it
5303 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07005304 removeEffect_l(effect);
5305 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306 }
5307}
5308
5309status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5310{
5311 int session = chain->sessionId();
5312 int16_t *buffer = mMixBuffer;
5313 bool ownsBuffer = false;
5314
5315 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5316 if (session > 0) {
5317 // Only one effect chain can be present in direct output thread and it uses
5318 // the mix buffer as input
5319 if (mType != DIRECT) {
5320 size_t numSamples = mFrameCount * mChannelCount;
5321 buffer = new int16_t[numSamples];
5322 memset(buffer, 0, numSamples * sizeof(int16_t));
5323 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5324 ownsBuffer = true;
5325 }
5326
5327 // Attach all tracks with same session ID to this chain.
5328 for (size_t i = 0; i < mTracks.size(); ++i) {
5329 sp<Track> track = mTracks[i];
5330 if (session == track->sessionId()) {
5331 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5332 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005333 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005334 }
5335 }
5336
5337 // indicate all active tracks in the chain
5338 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5339 sp<Track> track = mActiveTracks[i].promote();
5340 if (track == 0) continue;
5341 if (session == track->sessionId()) {
5342 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005343 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005344 }
5345 }
5346 }
5347
5348 chain->setInBuffer(buffer, ownsBuffer);
5349 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005350 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005351 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005352 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5353 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005355 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5356 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005357 // Effect chain for other sessions are inserted at beginning of effect
5358 // chains list to be processed before output mix effects. Relative order between other
5359 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005360 size_t size = mEffectChains.size();
5361 size_t i = 0;
5362 for (i = 0; i < size; i++) {
5363 if (mEffectChains[i]->sessionId() < session) break;
5364 }
5365 mEffectChains.insertAt(chain, i);
5366
5367 return NO_ERROR;
5368}
5369
5370size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5371{
5372 int session = chain->sessionId();
5373
5374 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5375
5376 for (size_t i = 0; i < mEffectChains.size(); i++) {
5377 if (chain == mEffectChains[i]) {
5378 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005379 // detach all active tracks from the chain
5380 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5381 sp<Track> track = mActiveTracks[i].promote();
5382 if (track == 0) continue;
5383 if (session == track->sessionId()) {
5384 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5385 chain.get(), session);
5386 chain->decActiveTrackCnt();
5387 }
5388 }
5389
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 // detach all tracks with same session ID from this chain
5391 for (size_t i = 0; i < mTracks.size(); ++i) {
5392 sp<Track> track = mTracks[i];
5393 if (session == track->sessionId()) {
5394 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005395 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396 }
5397 }
Eric Laurentde070132010-07-13 04:45:46 -07005398 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005399 }
5400 }
5401 return mEffectChains.size();
5402}
5403
Eric Laurentde070132010-07-13 04:45:46 -07005404status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5405 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005406{
5407 Mutex::Autolock _l(mLock);
5408 return attachAuxEffect_l(track, EffectId);
5409}
5410
Eric Laurentde070132010-07-13 04:45:46 -07005411status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5412 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005413{
5414 status_t status = NO_ERROR;
5415
5416 if (EffectId == 0) {
5417 track->setAuxBuffer(0, NULL);
5418 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005419 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5420 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005421 if (effect != 0) {
5422 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5423 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5424 } else {
5425 status = INVALID_OPERATION;
5426 }
5427 } else {
5428 status = BAD_VALUE;
5429 }
5430 }
5431 return status;
5432}
5433
5434void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5435{
5436 for (size_t i = 0; i < mTracks.size(); ++i) {
5437 sp<Track> track = mTracks[i];
5438 if (track->auxEffectId() == effectId) {
5439 attachAuxEffect_l(track, 0);
5440 }
5441 }
5442}
5443
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005444status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5445{
5446 // only one chain per input thread
5447 if (mEffectChains.size() != 0) {
5448 return INVALID_OPERATION;
5449 }
5450 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5451
5452 chain->setInBuffer(NULL);
5453 chain->setOutBuffer(NULL);
5454
5455 mEffectChains.add(chain);
5456
5457 return NO_ERROR;
5458}
5459
5460size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5461{
5462 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5463 LOGW_IF(mEffectChains.size() != 1,
5464 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5465 chain.get(), mEffectChains.size(), this);
5466 if (mEffectChains.size() == 1) {
5467 mEffectChains.removeAt(0);
5468 }
5469 return 0;
5470}
5471
Mathias Agopian65ab4712010-07-14 17:59:35 -07005472// ----------------------------------------------------------------------------
5473// EffectModule implementation
5474// ----------------------------------------------------------------------------
5475
5476#undef LOG_TAG
5477#define LOG_TAG "AudioFlinger::EffectModule"
5478
5479AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5480 const wp<AudioFlinger::EffectChain>& chain,
5481 effect_descriptor_t *desc,
5482 int id,
5483 int sessionId)
5484 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5485 mStatus(NO_INIT), mState(IDLE)
5486{
5487 LOGV("Constructor %p", this);
5488 int lStatus;
5489 sp<ThreadBase> thread = mThread.promote();
5490 if (thread == 0) {
5491 return;
5492 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493
5494 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5495
5496 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005497 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498
5499 if (mStatus != NO_ERROR) {
5500 return;
5501 }
5502 lStatus = init();
5503 if (lStatus < 0) {
5504 mStatus = lStatus;
5505 goto Error;
5506 }
5507
5508 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5509 return;
5510Error:
5511 EffectRelease(mEffectInterface);
5512 mEffectInterface = NULL;
5513 LOGV("Constructor Error %d", mStatus);
5514}
5515
5516AudioFlinger::EffectModule::~EffectModule()
5517{
5518 LOGV("Destructor %p", this);
5519 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005520 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5521 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
5522 sp<ThreadBase> thread = mThread.promote();
5523 if (thread != 0) {
5524 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5525 }
5526 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005527 // release effect engine
5528 EffectRelease(mEffectInterface);
5529 }
5530}
5531
5532status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5533{
5534 status_t status;
5535
5536 Mutex::Autolock _l(mLock);
5537 // First handle in mHandles has highest priority and controls the effect module
5538 int priority = handle->priority();
5539 size_t size = mHandles.size();
5540 sp<EffectHandle> h;
5541 size_t i;
5542 for (i = 0; i < size; i++) {
5543 h = mHandles[i].promote();
5544 if (h == 0) continue;
5545 if (h->priority() <= priority) break;
5546 }
5547 // if inserted in first place, move effect control from previous owner to this handle
5548 if (i == 0) {
5549 if (h != 0) {
5550 h->setControl(false, true);
5551 }
5552 handle->setControl(true, false);
5553 status = NO_ERROR;
5554 } else {
5555 status = ALREADY_EXISTS;
5556 }
5557 mHandles.insertAt(handle, i);
5558 return status;
5559}
5560
5561size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5562{
5563 Mutex::Autolock _l(mLock);
5564 size_t size = mHandles.size();
5565 size_t i;
5566 for (i = 0; i < size; i++) {
5567 if (mHandles[i] == handle) break;
5568 }
5569 if (i == size) {
5570 return size;
5571 }
5572 mHandles.removeAt(i);
5573 size = mHandles.size();
5574 // if removed from first place, move effect control from this handle to next in line
5575 if (i == 0 && size != 0) {
5576 sp<EffectHandle> h = mHandles[0].promote();
5577 if (h != 0) {
5578 h->setControl(true, true);
5579 }
5580 }
5581
Eric Laurentec437d82011-07-26 20:54:46 -07005582 // Prevent calls to process() and other functions on effect interface from now on.
5583 // The effect engine will be released by the destructor when the last strong reference on
5584 // this object is released which can happen after next process is called.
5585 if (size == 0) {
5586 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07005587 }
5588
Mathias Agopian65ab4712010-07-14 17:59:35 -07005589 return size;
5590}
5591
5592void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5593{
5594 // keep a strong reference on this EffectModule to avoid calling the
5595 // destructor before we exit
5596 sp<EffectModule> keep(this);
5597 {
5598 sp<ThreadBase> thread = mThread.promote();
5599 if (thread != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005600 thread->disconnectEffect(keep, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005601 }
5602 }
5603}
5604
5605void AudioFlinger::EffectModule::updateState() {
5606 Mutex::Autolock _l(mLock);
5607
5608 switch (mState) {
5609 case RESTART:
5610 reset_l();
5611 // FALL THROUGH
5612
5613 case STARTING:
5614 // clear auxiliary effect input buffer for next accumulation
5615 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5616 memset(mConfig.inputCfg.buffer.raw,
5617 0,
5618 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5619 }
5620 start_l();
5621 mState = ACTIVE;
5622 break;
5623 case STOPPING:
5624 stop_l();
5625 mDisableWaitCnt = mMaxDisableWaitCnt;
5626 mState = STOPPED;
5627 break;
5628 case STOPPED:
5629 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5630 // turn off sequence.
5631 if (--mDisableWaitCnt == 0) {
5632 reset_l();
5633 mState = IDLE;
5634 }
5635 break;
Eric Laurentec437d82011-07-26 20:54:46 -07005636 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07005637 break;
5638 }
5639}
5640
5641void AudioFlinger::EffectModule::process()
5642{
5643 Mutex::Autolock _l(mLock);
5644
Eric Laurentec437d82011-07-26 20:54:46 -07005645 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646 mConfig.inputCfg.buffer.raw == NULL ||
5647 mConfig.outputCfg.buffer.raw == NULL) {
5648 return;
5649 }
5650
Eric Laurent8f45bd72010-08-31 13:50:07 -07005651 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005652 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5653 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5654 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5655 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005656 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657 }
5658
5659 // do the actual processing in the effect engine
5660 int ret = (*mEffectInterface)->process(mEffectInterface,
5661 &mConfig.inputCfg.buffer,
5662 &mConfig.outputCfg.buffer);
5663
5664 // force transition to IDLE state when engine is ready
5665 if (mState == STOPPED && ret == -ENODATA) {
5666 mDisableWaitCnt = 1;
5667 }
5668
5669 // clear auxiliary effect input buffer for next accumulation
5670 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005671 memset(mConfig.inputCfg.buffer.raw, 0,
5672 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673 }
5674 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005675 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5676 // If an insert effect is idle and input buffer is different from output buffer,
5677 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005678 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07005679 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005680 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5681 int16_t *in = mConfig.inputCfg.buffer.s16;
5682 int16_t *out = mConfig.outputCfg.buffer.s16;
5683 for (size_t i = 0; i < frameCnt; i++) {
5684 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005685 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005686 }
5687 }
5688}
5689
5690void AudioFlinger::EffectModule::reset_l()
5691{
5692 if (mEffectInterface == NULL) {
5693 return;
5694 }
5695 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5696}
5697
5698status_t AudioFlinger::EffectModule::configure()
5699{
5700 uint32_t channels;
5701 if (mEffectInterface == NULL) {
5702 return NO_INIT;
5703 }
5704
5705 sp<ThreadBase> thread = mThread.promote();
5706 if (thread == 0) {
5707 return DEAD_OBJECT;
5708 }
5709
5710 // TODO: handle configuration of effects replacing track process
5711 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005712 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005713 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07005714 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005715 }
5716
5717 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005718 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719 } else {
5720 mConfig.inputCfg.channels = channels;
5721 }
5722 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07005723 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5724 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005725 mConfig.inputCfg.samplingRate = thread->sampleRate();
5726 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5727 mConfig.inputCfg.bufferProvider.cookie = NULL;
5728 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5729 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5730 mConfig.outputCfg.bufferProvider.cookie = NULL;
5731 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5732 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5733 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5734 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07005735 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07005736 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 // - in other sessions:
5738 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5739 // other effect: overwrites output buffer: input buffer == output buffer
5740 // Auxiliary effect:
5741 // accumulates in output buffer: input buffer != output buffer
5742 // Therefore: accumulate <=> input buffer != output buffer
5743 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5744 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5745 } else {
5746 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5747 }
5748 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5749 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5750 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5751 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5752
Eric Laurentde070132010-07-13 04:45:46 -07005753 LOGV("configure() %p thread %p buffer %p framecount %d",
5754 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5755
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005757 uint32_t size = sizeof(int);
5758 status_t status = (*mEffectInterface)->command(mEffectInterface,
5759 EFFECT_CMD_CONFIGURE,
5760 sizeof(effect_config_t),
5761 &mConfig,
5762 &size,
5763 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 if (status == 0) {
5765 status = cmdStatus;
5766 }
5767
5768 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5769 (1000 * mConfig.outputCfg.buffer.frameCount);
5770
5771 return status;
5772}
5773
5774status_t AudioFlinger::EffectModule::init()
5775{
5776 Mutex::Autolock _l(mLock);
5777 if (mEffectInterface == NULL) {
5778 return NO_INIT;
5779 }
5780 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005781 uint32_t size = sizeof(status_t);
5782 status_t status = (*mEffectInterface)->command(mEffectInterface,
5783 EFFECT_CMD_INIT,
5784 0,
5785 NULL,
5786 &size,
5787 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005788 if (status == 0) {
5789 status = cmdStatus;
5790 }
5791 return status;
5792}
5793
5794status_t AudioFlinger::EffectModule::start_l()
5795{
5796 if (mEffectInterface == NULL) {
5797 return NO_INIT;
5798 }
5799 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005800 uint32_t size = sizeof(status_t);
5801 status_t status = (*mEffectInterface)->command(mEffectInterface,
5802 EFFECT_CMD_ENABLE,
5803 0,
5804 NULL,
5805 &size,
5806 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 if (status == 0) {
5808 status = cmdStatus;
5809 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005810 if (status == 0 &&
5811 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5812 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
5813 sp<ThreadBase> thread = mThread.promote();
5814 if (thread != 0) {
5815 thread->stream()->add_audio_effect(thread->stream(), mEffectInterface);
5816 }
5817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005818 return status;
5819}
5820
Eric Laurentec437d82011-07-26 20:54:46 -07005821status_t AudioFlinger::EffectModule::stop()
5822{
5823 Mutex::Autolock _l(mLock);
5824 return stop_l();
5825}
5826
Mathias Agopian65ab4712010-07-14 17:59:35 -07005827status_t AudioFlinger::EffectModule::stop_l()
5828{
5829 if (mEffectInterface == NULL) {
5830 return NO_INIT;
5831 }
5832 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005833 uint32_t size = sizeof(status_t);
5834 status_t status = (*mEffectInterface)->command(mEffectInterface,
5835 EFFECT_CMD_DISABLE,
5836 0,
5837 NULL,
5838 &size,
5839 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840 if (status == 0) {
5841 status = cmdStatus;
5842 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005843 if (status == 0 &&
5844 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5845 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
5846 sp<ThreadBase> thread = mThread.promote();
5847 if (thread != 0) {
5848 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5849 }
5850 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005851 return status;
5852}
5853
Eric Laurent25f43952010-07-28 05:40:18 -07005854status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5855 uint32_t cmdSize,
5856 void *pCmdData,
5857 uint32_t *replySize,
5858 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859{
5860 Mutex::Autolock _l(mLock);
5861// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5862
Eric Laurentec437d82011-07-26 20:54:46 -07005863 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 return NO_INIT;
5865 }
Eric Laurent25f43952010-07-28 05:40:18 -07005866 status_t status = (*mEffectInterface)->command(mEffectInterface,
5867 cmdCode,
5868 cmdSize,
5869 pCmdData,
5870 replySize,
5871 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07005873 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005874 for (size_t i = 1; i < mHandles.size(); i++) {
5875 sp<EffectHandle> h = mHandles[i].promote();
5876 if (h != 0) {
5877 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5878 }
5879 }
5880 }
5881 return status;
5882}
5883
5884status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5885{
5886 Mutex::Autolock _l(mLock);
5887 LOGV("setEnabled %p enabled %d", this, enabled);
5888
5889 if (enabled != isEnabled()) {
5890 switch (mState) {
5891 // going from disabled to enabled
5892 case IDLE:
5893 mState = STARTING;
5894 break;
5895 case STOPPED:
5896 mState = RESTART;
5897 break;
5898 case STOPPING:
5899 mState = ACTIVE;
5900 break;
5901
5902 // going from enabled to disabled
5903 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005904 mState = STOPPED;
5905 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005906 case STARTING:
5907 mState = IDLE;
5908 break;
5909 case ACTIVE:
5910 mState = STOPPING;
5911 break;
Eric Laurentec437d82011-07-26 20:54:46 -07005912 case DESTROYED:
5913 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005914 }
5915 for (size_t i = 1; i < mHandles.size(); i++) {
5916 sp<EffectHandle> h = mHandles[i].promote();
5917 if (h != 0) {
5918 h->setEnabled(enabled);
5919 }
5920 }
5921 }
5922 return NO_ERROR;
5923}
5924
5925bool AudioFlinger::EffectModule::isEnabled()
5926{
5927 switch (mState) {
5928 case RESTART:
5929 case STARTING:
5930 case ACTIVE:
5931 return true;
5932 case IDLE:
5933 case STOPPING:
5934 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07005935 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07005936 default:
5937 return false;
5938 }
5939}
5940
Eric Laurent8f45bd72010-08-31 13:50:07 -07005941bool AudioFlinger::EffectModule::isProcessEnabled()
5942{
5943 switch (mState) {
5944 case RESTART:
5945 case ACTIVE:
5946 case STOPPING:
5947 case STOPPED:
5948 return true;
5949 case IDLE:
5950 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07005951 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005952 default:
5953 return false;
5954 }
5955}
5956
Mathias Agopian65ab4712010-07-14 17:59:35 -07005957status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5958{
5959 Mutex::Autolock _l(mLock);
5960 status_t status = NO_ERROR;
5961
5962 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5963 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07005964 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07005965 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5966 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005967 status_t cmdStatus;
5968 uint32_t volume[2];
5969 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07005970 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 volume[0] = *left;
5972 volume[1] = *right;
5973 if (controller) {
5974 pVolume = volume;
5975 }
Eric Laurent25f43952010-07-28 05:40:18 -07005976 status = (*mEffectInterface)->command(mEffectInterface,
5977 EFFECT_CMD_SET_VOLUME,
5978 size,
5979 volume,
5980 &size,
5981 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5983 *left = volume[0];
5984 *right = volume[1];
5985 }
5986 }
5987 return status;
5988}
5989
5990status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5991{
5992 Mutex::Autolock _l(mLock);
5993 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005994 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5995 // audio pre processing modules on RecordThread can receive both output and
5996 // input device indication in the same call
5997 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
5998 if (dev) {
5999 status_t cmdStatus;
6000 uint32_t size = sizeof(status_t);
6001
6002 status = (*mEffectInterface)->command(mEffectInterface,
6003 EFFECT_CMD_SET_DEVICE,
6004 sizeof(uint32_t),
6005 &dev,
6006 &size,
6007 &cmdStatus);
6008 if (status == NO_ERROR) {
6009 status = cmdStatus;
6010 }
6011 }
6012 dev = device & AUDIO_DEVICE_IN_ALL;
6013 if (dev) {
6014 status_t cmdStatus;
6015 uint32_t size = sizeof(status_t);
6016
6017 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6018 EFFECT_CMD_SET_INPUT_DEVICE,
6019 sizeof(uint32_t),
6020 &dev,
6021 &size,
6022 &cmdStatus);
6023 if (status2 == NO_ERROR) {
6024 status2 = cmdStatus;
6025 }
6026 if (status == NO_ERROR) {
6027 status = status2;
6028 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006029 }
6030 }
6031 return status;
6032}
6033
6034status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6035{
6036 Mutex::Autolock _l(mLock);
6037 status_t status = NO_ERROR;
6038 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006039 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006040 uint32_t size = sizeof(status_t);
6041 status = (*mEffectInterface)->command(mEffectInterface,
6042 EFFECT_CMD_SET_AUDIO_MODE,
6043 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006044 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006045 &size,
6046 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006047 if (status == NO_ERROR) {
6048 status = cmdStatus;
6049 }
6050 }
6051 return status;
6052}
6053
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6055{
6056 const size_t SIZE = 256;
6057 char buffer[SIZE];
6058 String8 result;
6059
6060 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6061 result.append(buffer);
6062
6063 bool locked = tryLock(mLock);
6064 // failed to lock - AudioFlinger is probably deadlocked
6065 if (!locked) {
6066 result.append("\t\tCould not lock Fx mutex:\n");
6067 }
6068
6069 result.append("\t\tSession Status State Engine:\n");
6070 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6071 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6072 result.append(buffer);
6073
6074 result.append("\t\tDescriptor:\n");
6075 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6076 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6077 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6078 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6079 result.append(buffer);
6080 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6081 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6082 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6083 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6084 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006085 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006086 mDescriptor.apiVersion,
6087 mDescriptor.flags);
6088 result.append(buffer);
6089 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6090 mDescriptor.name);
6091 result.append(buffer);
6092 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6093 mDescriptor.implementor);
6094 result.append(buffer);
6095
6096 result.append("\t\t- Input configuration:\n");
6097 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6098 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6099 (uint32_t)mConfig.inputCfg.buffer.raw,
6100 mConfig.inputCfg.buffer.frameCount,
6101 mConfig.inputCfg.samplingRate,
6102 mConfig.inputCfg.channels,
6103 mConfig.inputCfg.format);
6104 result.append(buffer);
6105
6106 result.append("\t\t- Output configuration:\n");
6107 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6108 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6109 (uint32_t)mConfig.outputCfg.buffer.raw,
6110 mConfig.outputCfg.buffer.frameCount,
6111 mConfig.outputCfg.samplingRate,
6112 mConfig.outputCfg.channels,
6113 mConfig.outputCfg.format);
6114 result.append(buffer);
6115
6116 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6117 result.append(buffer);
6118 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6119 for (size_t i = 0; i < mHandles.size(); ++i) {
6120 sp<EffectHandle> handle = mHandles[i].promote();
6121 if (handle != 0) {
6122 handle->dump(buffer, SIZE);
6123 result.append(buffer);
6124 }
6125 }
6126
6127 result.append("\n");
6128
6129 write(fd, result.string(), result.length());
6130
6131 if (locked) {
6132 mLock.unlock();
6133 }
6134
6135 return NO_ERROR;
6136}
6137
6138// ----------------------------------------------------------------------------
6139// EffectHandle implementation
6140// ----------------------------------------------------------------------------
6141
6142#undef LOG_TAG
6143#define LOG_TAG "AudioFlinger::EffectHandle"
6144
6145AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6146 const sp<AudioFlinger::Client>& client,
6147 const sp<IEffectClient>& effectClient,
6148 int32_t priority)
6149 : BnEffect(),
6150 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
6151{
6152 LOGV("constructor %p", this);
6153
6154 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6155 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6156 if (mCblkMemory != 0) {
6157 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6158
6159 if (mCblk) {
6160 new(mCblk) effect_param_cblk_t();
6161 mBuffer = (uint8_t *)mCblk + bufOffset;
6162 }
6163 } else {
6164 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6165 return;
6166 }
6167}
6168
6169AudioFlinger::EffectHandle::~EffectHandle()
6170{
6171 LOGV("Destructor %p", this);
6172 disconnect();
6173}
6174
6175status_t AudioFlinger::EffectHandle::enable()
6176{
6177 if (!mHasControl) return INVALID_OPERATION;
6178 if (mEffect == 0) return DEAD_OBJECT;
6179
6180 return mEffect->setEnabled(true);
6181}
6182
6183status_t AudioFlinger::EffectHandle::disable()
6184{
6185 if (!mHasControl) return INVALID_OPERATION;
6186 if (mEffect == NULL) return DEAD_OBJECT;
6187
6188 return mEffect->setEnabled(false);
6189}
6190
6191void AudioFlinger::EffectHandle::disconnect()
6192{
6193 if (mEffect == 0) {
6194 return;
6195 }
6196 mEffect->disconnect(this);
6197 // release sp on module => module destructor can be called now
6198 mEffect.clear();
6199 if (mCblk) {
6200 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6201 }
6202 mCblkMemory.clear(); // and free the shared memory
6203 if (mClient != 0) {
6204 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6205 mClient.clear();
6206 }
6207}
6208
Eric Laurent25f43952010-07-28 05:40:18 -07006209status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6210 uint32_t cmdSize,
6211 void *pCmdData,
6212 uint32_t *replySize,
6213 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214{
Eric Laurent25f43952010-07-28 05:40:18 -07006215// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6216// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217
6218 // only get parameter command is permitted for applications not controlling the effect
6219 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6220 return INVALID_OPERATION;
6221 }
6222 if (mEffect == 0) return DEAD_OBJECT;
6223
6224 // handle commands that are not forwarded transparently to effect engine
6225 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6226 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6227 // no risk to block the whole media server process or mixer threads is we are stuck here
6228 Mutex::Autolock _l(mCblk->lock);
6229 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6230 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6231 mCblk->serverIndex = 0;
6232 mCblk->clientIndex = 0;
6233 return BAD_VALUE;
6234 }
6235 status_t status = NO_ERROR;
6236 while (mCblk->serverIndex < mCblk->clientIndex) {
6237 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006238 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006239 int *p = (int *)(mBuffer + mCblk->serverIndex);
6240 int size = *p++;
6241 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6242 LOGW("command(): invalid parameter block size");
6243 break;
6244 }
6245 effect_param_t *param = (effect_param_t *)p;
6246 if (param->psize == 0 || param->vsize == 0) {
6247 LOGW("command(): null parameter or value size");
6248 mCblk->serverIndex += size;
6249 continue;
6250 }
Eric Laurent25f43952010-07-28 05:40:18 -07006251 uint32_t psize = sizeof(effect_param_t) +
6252 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6253 param->vsize;
6254 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6255 psize,
6256 p,
6257 &rsize,
6258 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006259 // stop at first error encountered
6260 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006262 *(int *)pReplyData = reply;
6263 break;
6264 } else if (reply != NO_ERROR) {
6265 *(int *)pReplyData = reply;
6266 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006267 }
6268 mCblk->serverIndex += size;
6269 }
6270 mCblk->serverIndex = 0;
6271 mCblk->clientIndex = 0;
6272 return status;
6273 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006274 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006275 return enable();
6276 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006277 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006278 return disable();
6279 }
6280
6281 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6282}
6283
6284sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6285 return mCblkMemory;
6286}
6287
6288void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6289{
6290 LOGV("setControl %p control %d", this, hasControl);
6291
6292 mHasControl = hasControl;
6293 if (signal && mEffectClient != 0) {
6294 mEffectClient->controlStatusChanged(hasControl);
6295 }
6296}
6297
Eric Laurent25f43952010-07-28 05:40:18 -07006298void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6299 uint32_t cmdSize,
6300 void *pCmdData,
6301 uint32_t replySize,
6302 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303{
6304 if (mEffectClient != 0) {
6305 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6306 }
6307}
6308
6309
6310
6311void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6312{
6313 if (mEffectClient != 0) {
6314 mEffectClient->enableStatusChanged(enabled);
6315 }
6316}
6317
6318status_t AudioFlinger::EffectHandle::onTransact(
6319 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6320{
6321 return BnEffect::onTransact(code, data, reply, flags);
6322}
6323
6324
6325void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6326{
6327 bool locked = tryLock(mCblk->lock);
6328
6329 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6330 (mClient == NULL) ? getpid() : mClient->pid(),
6331 mPriority,
6332 mHasControl,
6333 !locked,
6334 mCblk->clientIndex,
6335 mCblk->serverIndex
6336 );
6337
6338 if (locked) {
6339 mCblk->lock.unlock();
6340 }
6341}
6342
6343#undef LOG_TAG
6344#define LOG_TAG "AudioFlinger::EffectChain"
6345
6346AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6347 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006348 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6349 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6350 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006351{
Dima Zavinfce7a472011-04-19 22:30:36 -07006352 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006353}
6354
6355AudioFlinger::EffectChain::~EffectChain()
6356{
6357 if (mOwnInBuffer) {
6358 delete mInBuffer;
6359 }
6360
6361}
6362
Eric Laurentcab11242010-07-15 12:50:15 -07006363// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6364sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006365{
6366 sp<EffectModule> effect;
6367 size_t size = mEffects.size();
6368
6369 for (size_t i = 0; i < size; i++) {
6370 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6371 effect = mEffects[i];
6372 break;
6373 }
6374 }
6375 return effect;
6376}
6377
Eric Laurentcab11242010-07-15 12:50:15 -07006378// getEffectFromId_l() must be called with PlaybackThread::mLock held
6379sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006380{
6381 sp<EffectModule> effect;
6382 size_t size = mEffects.size();
6383
6384 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006385 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6386 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006387 effect = mEffects[i];
6388 break;
6389 }
6390 }
6391 return effect;
6392}
6393
6394// Must be called with EffectChain::mLock locked
6395void AudioFlinger::EffectChain::process_l()
6396{
Eric Laurentdac69112010-09-28 14:09:57 -07006397 sp<ThreadBase> thread = mThread.promote();
6398 if (thread == 0) {
6399 LOGW("process_l(): cannot promote mixer thread");
6400 return;
6401 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006402 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6403 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07006404 bool tracksOnSession = false;
6405 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07006406 tracksOnSession = (trackCnt() != 0);
6407 }
6408
6409 // if no track is active, input buffer must be cleared here as the mixer process
6410 // will not do it
6411 if (tracksOnSession &&
6412 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006413 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07006414 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07006415 }
6416
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006418 // do not process effect if no track is present in same audio session
6419 if (isGlobalSession || tracksOnSession) {
6420 for (size_t i = 0; i < size; i++) {
6421 mEffects[i]->process();
6422 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006423 }
6424 for (size_t i = 0; i < size; i++) {
6425 mEffects[i]->updateState();
6426 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427}
6428
Eric Laurentcab11242010-07-15 12:50:15 -07006429// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006430status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006431{
6432 effect_descriptor_t desc = effect->desc();
6433 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6434
6435 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006436 effect->setChain(this);
6437 sp<ThreadBase> thread = mThread.promote();
6438 if (thread == 0) {
6439 return NO_INIT;
6440 }
6441 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442
6443 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6444 // Auxiliary effects are inserted at the beginning of mEffects vector as
6445 // they are processed first and accumulated in chain input buffer
6446 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006447
Mathias Agopian65ab4712010-07-14 17:59:35 -07006448 // the input buffer for auxiliary effect contains mono samples in
6449 // 32 bit format. This is to avoid saturation in AudoMixer
6450 // accumulation stage. Saturation is done in EffectModule::process() before
6451 // calling the process in effect engine
6452 size_t numSamples = thread->frameCount();
6453 int32_t *buffer = new int32_t[numSamples];
6454 memset(buffer, 0, numSamples * sizeof(int32_t));
6455 effect->setInBuffer((int16_t *)buffer);
6456 // auxiliary effects output samples to chain input buffer for further processing
6457 // by insert effects
6458 effect->setOutBuffer(mInBuffer);
6459 } else {
6460 // Insert effects are inserted at the end of mEffects vector as they are processed
6461 // after track and auxiliary effects.
6462 // Insert effect order as a function of indicated preference:
6463 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6464 // another effect is present
6465 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6466 // last effect claiming first position
6467 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6468 // first effect claiming last position
6469 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6470 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6471 // already present
6472
6473 int size = (int)mEffects.size();
6474 int idx_insert = size;
6475 int idx_insert_first = -1;
6476 int idx_insert_last = -1;
6477
6478 for (int i = 0; i < size; i++) {
6479 effect_descriptor_t d = mEffects[i]->desc();
6480 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6481 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6482 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6483 // check invalid effect chaining combinations
6484 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6485 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006486 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006487 return INVALID_OPERATION;
6488 }
6489 // remember position of first insert effect and by default
6490 // select this as insert position for new effect
6491 if (idx_insert == size) {
6492 idx_insert = i;
6493 }
6494 // remember position of last insert effect claiming
6495 // first position
6496 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6497 idx_insert_first = i;
6498 }
6499 // remember position of first insert effect claiming
6500 // last position
6501 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6502 idx_insert_last == -1) {
6503 idx_insert_last = i;
6504 }
6505 }
6506 }
6507
6508 // modify idx_insert from first position if needed
6509 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6510 if (idx_insert_last != -1) {
6511 idx_insert = idx_insert_last;
6512 } else {
6513 idx_insert = size;
6514 }
6515 } else {
6516 if (idx_insert_first != -1) {
6517 idx_insert = idx_insert_first + 1;
6518 }
6519 }
6520
6521 // always read samples from chain input buffer
6522 effect->setInBuffer(mInBuffer);
6523
6524 // if last effect in the chain, output samples to chain
6525 // output buffer, otherwise to chain input buffer
6526 if (idx_insert == size) {
6527 if (idx_insert != 0) {
6528 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6529 mEffects[idx_insert-1]->configure();
6530 }
6531 effect->setOutBuffer(mOutBuffer);
6532 } else {
6533 effect->setOutBuffer(mInBuffer);
6534 }
6535 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006536
Eric Laurentcab11242010-07-15 12:50:15 -07006537 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538 }
6539 effect->configure();
6540 return NO_ERROR;
6541}
6542
Eric Laurentcab11242010-07-15 12:50:15 -07006543// removeEffect_l() must be called with PlaybackThread::mLock held
6544size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545{
6546 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006547 int size = (int)mEffects.size();
6548 int i;
6549 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6550
6551 for (i = 0; i < size; i++) {
6552 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07006553 // calling stop here will remove pre-processing effect from the audio HAL.
6554 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
6555 // the middle of a read from audio HAL
6556 mEffects[i]->stop();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6558 delete[] effect->inBuffer();
6559 } else {
6560 if (i == size - 1 && i != 0) {
6561 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6562 mEffects[i - 1]->configure();
6563 }
6564 }
6565 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006566 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567 break;
6568 }
6569 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570
6571 return mEffects.size();
6572}
6573
Eric Laurentcab11242010-07-15 12:50:15 -07006574// setDevice_l() must be called with PlaybackThread::mLock held
6575void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006576{
6577 size_t size = mEffects.size();
6578 for (size_t i = 0; i < size; i++) {
6579 mEffects[i]->setDevice(device);
6580 }
6581}
6582
Eric Laurentcab11242010-07-15 12:50:15 -07006583// setMode_l() must be called with PlaybackThread::mLock held
6584void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006585{
6586 size_t size = mEffects.size();
6587 for (size_t i = 0; i < size; i++) {
6588 mEffects[i]->setMode(mode);
6589 }
6590}
6591
Eric Laurentcab11242010-07-15 12:50:15 -07006592// setVolume_l() must be called with PlaybackThread::mLock held
6593bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006594{
6595 uint32_t newLeft = *left;
6596 uint32_t newRight = *right;
6597 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006598 int ctrlIdx = -1;
6599 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600
Eric Laurentcab11242010-07-15 12:50:15 -07006601 // first update volume controller
6602 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006603 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006604 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6605 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006606 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006607 break;
6608 }
6609 }
6610
6611 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006612 if (hasControl) {
6613 *left = mNewLeftVolume;
6614 *right = mNewRightVolume;
6615 }
6616 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006617 }
6618
6619 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006620 mLeftVolume = newLeft;
6621 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006622
6623 // second get volume update from volume controller
6624 if (ctrlIdx >= 0) {
6625 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006626 mNewLeftVolume = newLeft;
6627 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628 }
6629 // then indicate volume to all other effects in chain.
6630 // Pass altered volume to effects before volume controller
6631 // and requested volume to effects after controller
6632 uint32_t lVol = newLeft;
6633 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006634
Mathias Agopian65ab4712010-07-14 17:59:35 -07006635 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006636 if ((int)i == ctrlIdx) continue;
6637 // this also works for ctrlIdx == -1 when there is no volume controller
6638 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639 lVol = *left;
6640 rVol = *right;
6641 }
6642 mEffects[i]->setVolume(&lVol, &rVol, false);
6643 }
6644 *left = newLeft;
6645 *right = newRight;
6646
6647 return hasControl;
6648}
6649
Mathias Agopian65ab4712010-07-14 17:59:35 -07006650status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6651{
6652 const size_t SIZE = 256;
6653 char buffer[SIZE];
6654 String8 result;
6655
6656 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6657 result.append(buffer);
6658
6659 bool locked = tryLock(mLock);
6660 // failed to lock - AudioFlinger is probably deadlocked
6661 if (!locked) {
6662 result.append("\tCould not lock mutex:\n");
6663 }
6664
Eric Laurentcab11242010-07-15 12:50:15 -07006665 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6666 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 mEffects.size(),
6668 (uint32_t)mInBuffer,
6669 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006670 mActiveTrackCnt);
6671 result.append(buffer);
6672 write(fd, result.string(), result.size());
6673
6674 for (size_t i = 0; i < mEffects.size(); ++i) {
6675 sp<EffectModule> effect = mEffects[i];
6676 if (effect != 0) {
6677 effect->dump(fd, args);
6678 }
6679 }
6680
6681 if (locked) {
6682 mLock.unlock();
6683 }
6684
6685 return NO_ERROR;
6686}
6687
6688#undef LOG_TAG
6689#define LOG_TAG "AudioFlinger"
6690
6691// ----------------------------------------------------------------------------
6692
6693status_t AudioFlinger::onTransact(
6694 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6695{
6696 return BnAudioFlinger::onTransact(code, data, reply, flags);
6697}
6698
Mathias Agopian65ab4712010-07-14 17:59:35 -07006699}; // namespace android