blob: cb1f9213413547dafa2a401246d5cd91656a6a72 [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 }
3910 // enable changes in effect chain
3911 unlockEffectChains(effectChains);
3912
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913 buffer.frameCount = mFrameCount;
3914 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3915 size_t framesOut = buffer.frameCount;
3916 if (mResampler == 0) {
3917 // no resampling
3918 while (framesOut) {
3919 size_t framesIn = mFrameCount - mRsmpInIndex;
3920 if (framesIn) {
3921 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3922 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3923 if (framesIn > framesOut)
3924 framesIn = framesOut;
3925 mRsmpInIndex += framesIn;
3926 framesOut -= framesIn;
3927 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07003928 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929 memcpy(dst, src, framesIn * mFrameSize);
3930 } else {
3931 int16_t *src16 = (int16_t *)src;
3932 int16_t *dst16 = (int16_t *)dst;
3933 if (mChannelCount == 1) {
3934 while (framesIn--) {
3935 *dst16++ = *src16;
3936 *dst16++ = *src16++;
3937 }
3938 } else {
3939 while (framesIn--) {
3940 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3941 src16 += 2;
3942 }
3943 }
3944 }
3945 }
3946 if (framesOut && mFrameCount == mRsmpInIndex) {
3947 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07003948 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003949 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950 framesOut = 0;
3951 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07003952 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953 mRsmpInIndex = 0;
3954 }
3955 if (mBytesRead < 0) {
3956 LOGE("Error reading audio input");
3957 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3958 // Force input into standby so that it tries to
3959 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07003960 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003961 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962 }
3963 mRsmpInIndex = mFrameCount;
3964 framesOut = 0;
3965 buffer.frameCount = 0;
3966 }
3967 }
3968 }
3969 } else {
3970 // resampling
3971
3972 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3973 // alter output frame count as if we were expecting stereo samples
3974 if (mChannelCount == 1 && mReqChannelCount == 1) {
3975 framesOut >>= 1;
3976 }
3977 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3978 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3979 // are 32 bit aligned which should be always true.
3980 if (mChannelCount == 2 && mReqChannelCount == 1) {
3981 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3982 // the resampler always outputs stereo samples: do post stereo to mono conversion
3983 int16_t *src = (int16_t *)mRsmpOutBuffer;
3984 int16_t *dst = buffer.i16;
3985 while (framesOut--) {
3986 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3987 src += 2;
3988 }
3989 } else {
3990 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3991 }
3992
3993 }
3994 mActiveTrack->releaseBuffer(&buffer);
3995 mActiveTrack->overflow();
3996 }
3997 // client isn't retrieving buffers fast enough
3998 else {
Eric Laurent44d98482010-09-30 16:12:31 -07003999 if (!mActiveTrack->setOverflow()) {
4000 nsecs_t now = systemTime();
4001 if ((now - lastWarning) > kWarningThrottle) {
4002 LOGW("RecordThread: buffer overflow");
4003 lastWarning = now;
4004 }
4005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006 // Release the processor for a while before asking for a new buffer.
4007 // This will give the application more chance to read from the buffer and
4008 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004009 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004010 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004011 } else {
4012 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004014 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 }
4016
4017 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004018 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019 }
4020 mActiveTrack.clear();
4021
4022 mStartStopCond.broadcast();
4023
4024 LOGV("RecordThread %p exiting", this);
4025 return false;
4026}
4027
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004028
4029sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4030 const sp<AudioFlinger::Client>& client,
4031 uint32_t sampleRate,
4032 int format,
4033 int channelMask,
4034 int frameCount,
4035 uint32_t flags,
4036 int sessionId,
4037 status_t *status)
4038{
4039 sp<RecordTrack> track;
4040 status_t lStatus;
4041
4042 lStatus = initCheck();
4043 if (lStatus != NO_ERROR) {
4044 LOGE("Audio driver not initialized.");
4045 goto Exit;
4046 }
4047
4048 { // scope for mLock
4049 Mutex::Autolock _l(mLock);
4050
4051 track = new RecordTrack(this, client, sampleRate,
4052 format, channelMask, frameCount, flags, sessionId);
4053
4054 if (track->getCblk() == NULL) {
4055 lStatus = NO_MEMORY;
4056 goto Exit;
4057 }
4058
4059 mTrack = track.get();
4060
4061 }
4062 lStatus = NO_ERROR;
4063
4064Exit:
4065 if (status) {
4066 *status = lStatus;
4067 }
4068 return track;
4069}
4070
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4072{
4073 LOGV("RecordThread::start");
4074 sp <ThreadBase> strongMe = this;
4075 status_t status = NO_ERROR;
4076 {
4077 AutoMutex lock(&mLock);
4078 if (mActiveTrack != 0) {
4079 if (recordTrack != mActiveTrack.get()) {
4080 status = -EBUSY;
4081 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4082 mActiveTrack->mState = TrackBase::ACTIVE;
4083 }
4084 return status;
4085 }
4086
4087 recordTrack->mState = TrackBase::IDLE;
4088 mActiveTrack = recordTrack;
4089 mLock.unlock();
4090 status_t status = AudioSystem::startInput(mId);
4091 mLock.lock();
4092 if (status != NO_ERROR) {
4093 mActiveTrack.clear();
4094 return status;
4095 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096 mRsmpInIndex = mFrameCount;
4097 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004098 if (mResampler != NULL) {
4099 mResampler->reset();
4100 }
4101 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 // signal thread to start
4103 LOGV("Signal record thread");
4104 mWaitWorkCV.signal();
4105 // do not wait for mStartStopCond if exiting
4106 if (mExiting) {
4107 mActiveTrack.clear();
4108 status = INVALID_OPERATION;
4109 goto startError;
4110 }
4111 mStartStopCond.wait(mLock);
4112 if (mActiveTrack == 0) {
4113 LOGV("Record failed to start");
4114 status = BAD_VALUE;
4115 goto startError;
4116 }
4117 LOGV("Record started OK");
4118 return status;
4119 }
4120startError:
4121 AudioSystem::stopInput(mId);
4122 return status;
4123}
4124
4125void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4126 LOGV("RecordThread::stop");
4127 sp <ThreadBase> strongMe = this;
4128 {
4129 AutoMutex lock(&mLock);
4130 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4131 mActiveTrack->mState = TrackBase::PAUSING;
4132 // do not wait for mStartStopCond if exiting
4133 if (mExiting) {
4134 return;
4135 }
4136 mStartStopCond.wait(mLock);
4137 // if we have been restarted, recordTrack == mActiveTrack.get() here
4138 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4139 mLock.unlock();
4140 AudioSystem::stopInput(mId);
4141 mLock.lock();
4142 LOGV("Record stopped OK");
4143 }
4144 }
4145 }
4146}
4147
4148status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4149{
4150 const size_t SIZE = 256;
4151 char buffer[SIZE];
4152 String8 result;
4153 pid_t pid = 0;
4154
4155 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4156 result.append(buffer);
4157
4158 if (mActiveTrack != 0) {
4159 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004160 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004161 mActiveTrack->dump(buffer, SIZE);
4162 result.append(buffer);
4163
4164 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4165 result.append(buffer);
4166 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4167 result.append(buffer);
4168 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4169 result.append(buffer);
4170 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4171 result.append(buffer);
4172 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4173 result.append(buffer);
4174
4175
4176 } else {
4177 result.append("No record client\n");
4178 }
4179 write(fd, result.string(), result.size());
4180
4181 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004182 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183
4184 return NO_ERROR;
4185}
4186
4187status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4188{
4189 size_t framesReq = buffer->frameCount;
4190 size_t framesReady = mFrameCount - mRsmpInIndex;
4191 int channelCount;
4192
4193 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004194 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004195 if (mBytesRead < 0) {
4196 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4197 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4198 // Force input into standby so that it tries to
4199 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004200 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004201 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004202 }
4203 buffer->raw = 0;
4204 buffer->frameCount = 0;
4205 return NOT_ENOUGH_DATA;
4206 }
4207 mRsmpInIndex = 0;
4208 framesReady = mFrameCount;
4209 }
4210
4211 if (framesReq > framesReady) {
4212 framesReq = framesReady;
4213 }
4214
4215 if (mChannelCount == 1 && mReqChannelCount == 2) {
4216 channelCount = 1;
4217 } else {
4218 channelCount = 2;
4219 }
4220 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4221 buffer->frameCount = framesReq;
4222 return NO_ERROR;
4223}
4224
4225void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4226{
4227 mRsmpInIndex += buffer->frameCount;
4228 buffer->frameCount = 0;
4229}
4230
4231bool AudioFlinger::RecordThread::checkForNewParameters_l()
4232{
4233 bool reconfig = false;
4234
4235 while (!mNewParameters.isEmpty()) {
4236 status_t status = NO_ERROR;
4237 String8 keyValuePair = mNewParameters[0];
4238 AudioParameter param = AudioParameter(keyValuePair);
4239 int value;
4240 int reqFormat = mFormat;
4241 int reqSamplingRate = mReqSampleRate;
4242 int reqChannelCount = mReqChannelCount;
4243
4244 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4245 reqSamplingRate = value;
4246 reconfig = true;
4247 }
4248 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4249 reqFormat = value;
4250 reconfig = true;
4251 }
4252 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004253 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004254 reconfig = true;
4255 }
4256 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4257 // do not accept frame count changes if tracks are open as the track buffer
4258 // size depends on frame count and correct behavior would not be garantied
4259 // if frame count is changed after track creation
4260 if (mActiveTrack != 0) {
4261 status = INVALID_OPERATION;
4262 } else {
4263 reconfig = true;
4264 }
4265 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004266 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4267 // forward device change to effects that have requested to be
4268 // aware of attached audio device.
4269 for (size_t i = 0; i < mEffectChains.size(); i++) {
4270 mEffectChains[i]->setDevice_l(value);
4271 }
4272 // store input device and output device but do not forward output device to audio HAL.
4273 // Note that status is ignored by the caller for output device
4274 // (see AudioFlinger::setParameters()
4275 if (value & AUDIO_DEVICE_OUT_ALL) {
4276 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4277 status = BAD_VALUE;
4278 } else {
4279 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4280 }
4281 mDevice |= (uint32_t)value;
4282 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004283 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004284 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004285 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004286 mInput->stream->common.standby(&mInput->stream->common);
4287 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 }
4289 if (reconfig) {
4290 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004291 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004292 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004293 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4294 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004295 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 status = NO_ERROR;
4297 }
4298 if (status == NO_ERROR) {
4299 readInputParameters();
4300 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4301 }
4302 }
4303 }
4304
4305 mNewParameters.removeAt(0);
4306
4307 mParamStatus = status;
4308 mParamCond.signal();
4309 mWaitWorkCV.wait(mLock);
4310 }
4311 return reconfig;
4312}
4313
4314String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4315{
Dima Zavinfce7a472011-04-19 22:30:36 -07004316 char *s;
4317 String8 out_s8;
4318
Dima Zavin799a70e2011-04-18 16:57:27 -07004319 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004320 out_s8 = String8(s);
4321 free(s);
4322 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004323}
4324
4325void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4326 AudioSystem::OutputDescriptor desc;
4327 void *param2 = 0;
4328
4329 switch (event) {
4330 case AudioSystem::INPUT_OPENED:
4331 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004332 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333 desc.samplingRate = mSampleRate;
4334 desc.format = mFormat;
4335 desc.frameCount = mFrameCount;
4336 desc.latency = 0;
4337 param2 = &desc;
4338 break;
4339
4340 case AudioSystem::INPUT_CLOSED:
4341 default:
4342 break;
4343 }
4344 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4345}
4346
4347void AudioFlinger::RecordThread::readInputParameters()
4348{
4349 if (mRsmpInBuffer) delete mRsmpInBuffer;
4350 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4351 if (mResampler) delete mResampler;
4352 mResampler = 0;
4353
Dima Zavin799a70e2011-04-18 16:57:27 -07004354 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004355 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4356 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004357 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4358 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4359 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004360 mFrameCount = mInputBytes / mFrameSize;
4361 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4362
4363 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4364 {
4365 int channelCount;
4366 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4367 // stereo to mono post process as the resampler always outputs stereo.
4368 if (mChannelCount == 1 && mReqChannelCount == 2) {
4369 channelCount = 1;
4370 } else {
4371 channelCount = 2;
4372 }
4373 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4374 mResampler->setSampleRate(mSampleRate);
4375 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4376 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4377
4378 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4379 if (mChannelCount == 1 && mReqChannelCount == 1) {
4380 mFrameCount >>= 1;
4381 }
4382
4383 }
4384 mRsmpInIndex = mFrameCount;
4385}
4386
4387unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4388{
Dima Zavin799a70e2011-04-18 16:57:27 -07004389 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004390}
4391
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004392uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4393{
4394 Mutex::Autolock _l(mLock);
4395 uint32_t result = 0;
4396 if (getEffectChain_l(sessionId) != 0) {
4397 result = EFFECT_SESSION;
4398 }
4399
4400 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4401 result |= TRACK_SESSION;
4402 }
4403
4404 return result;
4405}
4406
Mathias Agopian65ab4712010-07-14 17:59:35 -07004407// ----------------------------------------------------------------------------
4408
4409int AudioFlinger::openOutput(uint32_t *pDevices,
4410 uint32_t *pSamplingRate,
4411 uint32_t *pFormat,
4412 uint32_t *pChannels,
4413 uint32_t *pLatencyMs,
4414 uint32_t flags)
4415{
4416 status_t status;
4417 PlaybackThread *thread = NULL;
4418 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4419 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4420 uint32_t format = pFormat ? *pFormat : 0;
4421 uint32_t channels = pChannels ? *pChannels : 0;
4422 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004423 audio_stream_out_t *outStream;
4424 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004425
4426 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4427 pDevices ? *pDevices : 0,
4428 samplingRate,
4429 format,
4430 channels,
4431 flags);
4432
4433 if (pDevices == NULL || *pDevices == 0) {
4434 return 0;
4435 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004436
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 Mutex::Autolock _l(mLock);
4438
Dima Zavin799a70e2011-04-18 16:57:27 -07004439 outHwDev = findSuitableHwDev_l(*pDevices);
4440 if (outHwDev == NULL)
4441 return 0;
4442
4443 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4444 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004446 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 samplingRate,
4448 format,
4449 channels,
4450 status);
4451
4452 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004453 if (outStream != NULL) {
4454 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004455 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004456
Dima Zavinfce7a472011-04-19 22:30:36 -07004457 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4458 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4459 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004460 thread = new DirectOutputThread(this, output, id, *pDevices);
4461 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4462 } else {
4463 thread = new MixerThread(this, output, id, *pDevices);
4464 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004465 }
4466 mPlaybackThreads.add(id, thread);
4467
4468 if (pSamplingRate) *pSamplingRate = samplingRate;
4469 if (pFormat) *pFormat = format;
4470 if (pChannels) *pChannels = channels;
4471 if (pLatencyMs) *pLatencyMs = thread->latency();
4472
4473 // notify client processes of the new output creation
4474 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4475 return id;
4476 }
4477
4478 return 0;
4479}
4480
4481int AudioFlinger::openDuplicateOutput(int output1, int output2)
4482{
4483 Mutex::Autolock _l(mLock);
4484 MixerThread *thread1 = checkMixerThread_l(output1);
4485 MixerThread *thread2 = checkMixerThread_l(output2);
4486
4487 if (thread1 == NULL || thread2 == NULL) {
4488 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4489 return 0;
4490 }
4491
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004492 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004493 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4494 thread->addOutputTrack(thread2);
4495 mPlaybackThreads.add(id, thread);
4496 // notify client processes of the new output creation
4497 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4498 return id;
4499}
4500
4501status_t AudioFlinger::closeOutput(int output)
4502{
4503 // keep strong reference on the playback thread so that
4504 // it is not destroyed while exit() is executed
4505 sp <PlaybackThread> thread;
4506 {
4507 Mutex::Autolock _l(mLock);
4508 thread = checkPlaybackThread_l(output);
4509 if (thread == NULL) {
4510 return BAD_VALUE;
4511 }
4512
4513 LOGV("closeOutput() %d", output);
4514
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004515 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004517 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004518 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4519 dupThread->removeOutputTrack((MixerThread *)thread.get());
4520 }
4521 }
4522 }
4523 void *param2 = 0;
4524 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4525 mPlaybackThreads.removeItem(output);
4526 }
4527 thread->exit();
4528
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004529 if (thread->type() != ThreadBase::DUPLICATING) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004530 AudioStreamOut *out = thread->getOutput();
4531 out->hwDev->close_output_stream(out->hwDev, out->stream);
4532 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533 }
4534 return NO_ERROR;
4535}
4536
4537status_t AudioFlinger::suspendOutput(int output)
4538{
4539 Mutex::Autolock _l(mLock);
4540 PlaybackThread *thread = checkPlaybackThread_l(output);
4541
4542 if (thread == NULL) {
4543 return BAD_VALUE;
4544 }
4545
4546 LOGV("suspendOutput() %d", output);
4547 thread->suspend();
4548
4549 return NO_ERROR;
4550}
4551
4552status_t AudioFlinger::restoreOutput(int output)
4553{
4554 Mutex::Autolock _l(mLock);
4555 PlaybackThread *thread = checkPlaybackThread_l(output);
4556
4557 if (thread == NULL) {
4558 return BAD_VALUE;
4559 }
4560
4561 LOGV("restoreOutput() %d", output);
4562
4563 thread->restore();
4564
4565 return NO_ERROR;
4566}
4567
4568int AudioFlinger::openInput(uint32_t *pDevices,
4569 uint32_t *pSamplingRate,
4570 uint32_t *pFormat,
4571 uint32_t *pChannels,
4572 uint32_t acoustics)
4573{
4574 status_t status;
4575 RecordThread *thread = NULL;
4576 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4577 uint32_t format = pFormat ? *pFormat : 0;
4578 uint32_t channels = pChannels ? *pChannels : 0;
4579 uint32_t reqSamplingRate = samplingRate;
4580 uint32_t reqFormat = format;
4581 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004582 audio_stream_in_t *inStream;
4583 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004584
4585 if (pDevices == NULL || *pDevices == 0) {
4586 return 0;
4587 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004588
Mathias Agopian65ab4712010-07-14 17:59:35 -07004589 Mutex::Autolock _l(mLock);
4590
Dima Zavin799a70e2011-04-18 16:57:27 -07004591 inHwDev = findSuitableHwDev_l(*pDevices);
4592 if (inHwDev == NULL)
4593 return 0;
4594
4595 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4596 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004597 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004598 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004599 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004600 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004601 samplingRate,
4602 format,
4603 channels,
4604 acoustics,
4605 status);
4606
4607 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4608 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4609 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07004610 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004611 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004612 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004613 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004614 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07004615 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4616 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004617 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004618 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 }
4620
Dima Zavin799a70e2011-04-18 16:57:27 -07004621 if (inStream != NULL) {
4622 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4623
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004624 int id = nextUniqueId();
4625 // Start record thread
4626 // RecorThread require both input and output device indication to forward to audio
4627 // pre processing modules
4628 uint32_t device = (*pDevices) | primaryOutputDevice_l();
4629 thread = new RecordThread(this,
4630 input,
4631 reqSamplingRate,
4632 reqChannels,
4633 id,
4634 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004635 mRecordThreads.add(id, thread);
4636 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4637 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4638 if (pFormat) *pFormat = format;
4639 if (pChannels) *pChannels = reqChannels;
4640
Dima Zavin799a70e2011-04-18 16:57:27 -07004641 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004642
4643 // notify client processes of the new input creation
4644 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4645 return id;
4646 }
4647
4648 return 0;
4649}
4650
4651status_t AudioFlinger::closeInput(int input)
4652{
4653 // keep strong reference on the record thread so that
4654 // it is not destroyed while exit() is executed
4655 sp <RecordThread> thread;
4656 {
4657 Mutex::Autolock _l(mLock);
4658 thread = checkRecordThread_l(input);
4659 if (thread == NULL) {
4660 return BAD_VALUE;
4661 }
4662
4663 LOGV("closeInput() %d", input);
4664 void *param2 = 0;
4665 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4666 mRecordThreads.removeItem(input);
4667 }
4668 thread->exit();
4669
Dima Zavin799a70e2011-04-18 16:57:27 -07004670 AudioStreamIn *in = thread->getInput();
4671 in->hwDev->close_input_stream(in->hwDev, in->stream);
4672 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673
4674 return NO_ERROR;
4675}
4676
4677status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4678{
4679 Mutex::Autolock _l(mLock);
4680 MixerThread *dstThread = checkMixerThread_l(output);
4681 if (dstThread == NULL) {
4682 LOGW("setStreamOutput() bad output id %d", output);
4683 return BAD_VALUE;
4684 }
4685
4686 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4687 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4688
4689 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4690 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4691 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004692 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004693 MixerThread *srcThread = (MixerThread *)thread;
4694 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004695 }
Eric Laurentde070132010-07-13 04:45:46 -07004696 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004697
4698 return NO_ERROR;
4699}
4700
4701
4702int AudioFlinger::newAudioSessionId()
4703{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004704 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004705}
4706
4707// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4708AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4709{
4710 PlaybackThread *thread = NULL;
4711 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4712 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4713 }
4714 return thread;
4715}
4716
4717// checkMixerThread_l() must be called with AudioFlinger::mLock held
4718AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4719{
4720 PlaybackThread *thread = checkPlaybackThread_l(output);
4721 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004722 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723 thread = NULL;
4724 }
4725 }
4726 return (MixerThread *)thread;
4727}
4728
4729// checkRecordThread_l() must be called with AudioFlinger::mLock held
4730AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4731{
4732 RecordThread *thread = NULL;
4733 if (mRecordThreads.indexOfKey(input) >= 0) {
4734 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4735 }
4736 return thread;
4737}
4738
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004739uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004740{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004741 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004742}
4743
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004744AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
4745{
4746 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4747 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4748 if (thread->getOutput()->hwDev == mPrimaryHardwareDev) {
4749 return thread;
4750 }
4751 }
4752 return NULL;
4753}
4754
4755uint32_t AudioFlinger::primaryOutputDevice_l()
4756{
4757 PlaybackThread *thread = primaryPlaybackThread_l();
4758
4759 if (thread == NULL) {
4760 return 0;
4761 }
4762
4763 return thread->device();
4764}
4765
4766
Mathias Agopian65ab4712010-07-14 17:59:35 -07004767// ----------------------------------------------------------------------------
4768// Effect management
4769// ----------------------------------------------------------------------------
4770
4771
Mathias Agopian65ab4712010-07-14 17:59:35 -07004772status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4773{
4774 Mutex::Autolock _l(mLock);
4775 return EffectQueryNumberEffects(numEffects);
4776}
4777
4778status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4779{
4780 Mutex::Autolock _l(mLock);
4781 return EffectQueryEffect(index, descriptor);
4782}
4783
4784status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4785{
4786 Mutex::Autolock _l(mLock);
4787 return EffectGetDescriptor(pUuid, descriptor);
4788}
4789
4790
4791// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4792static const effect_uuid_t VISUALIZATION_UUID_ =
4793 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4794
4795sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4796 effect_descriptor_t *pDesc,
4797 const sp<IEffectClient>& effectClient,
4798 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004799 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004800 int sessionId,
4801 status_t *status,
4802 int *id,
4803 int *enabled)
4804{
4805 status_t lStatus = NO_ERROR;
4806 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004807 effect_descriptor_t desc;
4808 sp<Client> client;
4809 wp<Client> wclient;
4810
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004811 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
4812 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004813
4814 if (pDesc == NULL) {
4815 lStatus = BAD_VALUE;
4816 goto Exit;
4817 }
4818
Eric Laurent84e9a102010-09-23 16:10:16 -07004819 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07004820 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004821 lStatus = PERMISSION_DENIED;
4822 goto Exit;
4823 }
4824
Dima Zavinfce7a472011-04-19 22:30:36 -07004825 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07004826 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07004827 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004828 lStatus = PERMISSION_DENIED;
4829 goto Exit;
4830 }
4831
4832 // check recording permission for visualizer
4833 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4834 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4835 !recordingAllowed()) {
4836 lStatus = PERMISSION_DENIED;
4837 goto Exit;
4838 }
4839
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004840 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004841 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004842 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07004843 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07004844 lStatus = BAD_VALUE;
4845 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07004846 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004847 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004848 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07004849 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004850 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07004851 }
4852 }
4853
Mathias Agopian65ab4712010-07-14 17:59:35 -07004854 {
4855 Mutex::Autolock _l(mLock);
4856
Mathias Agopian65ab4712010-07-14 17:59:35 -07004857
4858 if (!EffectIsNullUuid(&pDesc->uuid)) {
4859 // if uuid is specified, request effect descriptor
4860 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4861 if (lStatus < 0) {
4862 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4863 goto Exit;
4864 }
4865 } else {
4866 // if uuid is not specified, look for an available implementation
4867 // of the required type in effect factory
4868 if (EffectIsNullUuid(&pDesc->type)) {
4869 LOGW("createEffect() no effect type");
4870 lStatus = BAD_VALUE;
4871 goto Exit;
4872 }
4873 uint32_t numEffects = 0;
4874 effect_descriptor_t d;
4875 bool found = false;
4876
4877 lStatus = EffectQueryNumberEffects(&numEffects);
4878 if (lStatus < 0) {
4879 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4880 goto Exit;
4881 }
4882 for (uint32_t i = 0; i < numEffects; i++) {
4883 lStatus = EffectQueryEffect(i, &desc);
4884 if (lStatus < 0) {
4885 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4886 continue;
4887 }
4888 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4889 // If matching type found save effect descriptor. If the session is
4890 // 0 and the effect is not auxiliary, continue enumeration in case
4891 // an auxiliary version of this effect type is available
4892 found = true;
4893 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07004894 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004895 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4896 break;
4897 }
4898 }
4899 }
4900 if (!found) {
4901 lStatus = BAD_VALUE;
4902 LOGW("createEffect() effect not found");
4903 goto Exit;
4904 }
4905 // For same effect type, chose auxiliary version over insert version if
4906 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07004907 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4909 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4910 }
4911 }
4912
4913 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004914 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004915 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4916 lStatus = INVALID_OPERATION;
4917 goto Exit;
4918 }
4919
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 // return effect descriptor
4921 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4922
4923 // If output is not specified try to find a matching audio session ID in one of the
4924 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004925 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4926 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004927 // Note: io is never 0 when creating an effect on an input
4928 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004929 // look for the thread where the specified audio session is present
4930 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4931 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004932 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07004933 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004934 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004936 if (io == 0) {
4937 for (size_t i = 0; i < mRecordThreads.size(); i++) {
4938 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4939 io = mRecordThreads.keyAt(i);
4940 break;
4941 }
4942 }
4943 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004944 // If no output thread contains the requested session ID, default to
4945 // first output. The effect chain will be moved to the correct output
4946 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004947 if (io == 0 && mPlaybackThreads.size()) {
4948 io = mPlaybackThreads.keyAt(0);
4949 }
4950 LOGV("createEffect() got io %d for effect %s", io, desc.name);
4951 }
4952 ThreadBase *thread = checkRecordThread_l(io);
4953 if (thread == NULL) {
4954 thread = checkPlaybackThread_l(io);
4955 if (thread == NULL) {
4956 LOGE("createEffect() unknown output thread");
4957 lStatus = BAD_VALUE;
4958 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07004959 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004960 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004961
Mathias Agopian65ab4712010-07-14 17:59:35 -07004962 wclient = mClients.valueFor(pid);
4963
4964 if (wclient != NULL) {
4965 client = wclient.promote();
4966 } else {
4967 client = new Client(this, pid);
4968 mClients.add(pid, client);
4969 }
4970
4971 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07004972 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4973 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004974 if (handle != 0 && id != NULL) {
4975 *id = handle->id();
4976 }
4977 }
4978
4979Exit:
4980 if(status) {
4981 *status = lStatus;
4982 }
4983 return handle;
4984}
4985
Eric Laurentde070132010-07-13 04:45:46 -07004986status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4987{
4988 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4989 session, srcOutput, dstOutput);
4990 Mutex::Autolock _l(mLock);
4991 if (srcOutput == dstOutput) {
4992 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4993 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004994 }
Eric Laurentde070132010-07-13 04:45:46 -07004995 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4996 if (srcThread == NULL) {
4997 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4998 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004999 }
Eric Laurentde070132010-07-13 04:45:46 -07005000 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5001 if (dstThread == NULL) {
5002 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5003 return BAD_VALUE;
5004 }
5005
5006 Mutex::Autolock _dl(dstThread->mLock);
5007 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07005008 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005009
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 return NO_ERROR;
5011}
5012
Eric Laurentde070132010-07-13 04:45:46 -07005013// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
5014status_t AudioFlinger::moveEffectChain_l(int session,
5015 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005016 AudioFlinger::PlaybackThread *dstThread,
5017 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005018{
5019 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
5020 session, srcThread, dstThread);
5021
5022 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
5023 if (chain == 0) {
5024 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
5025 session, srcThread);
5026 return INVALID_OPERATION;
5027 }
5028
Eric Laurent39e94f82010-07-28 01:32:47 -07005029 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005030 // so that a new chain is created with correct parameters when first effect is added. This is
5031 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
5032 // removed.
5033 srcThread->removeEffectChain_l(chain);
5034
5035 // transfer all effects one by one so that new effect chain is created on new thread with
5036 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005037 int dstOutput = dstThread->id();
5038 sp<EffectChain> dstChain;
5039 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07005040 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5041 while (effect != 0) {
5042 srcThread->removeEffect_l(effect);
5043 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07005044 // if the move request is not received from audio policy manager, the effect must be
5045 // re-registered with the new strategy and output
5046 if (dstChain == 0) {
5047 dstChain = effect->chain().promote();
5048 if (dstChain == 0) {
5049 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5050 srcThread->addEffect_l(effect);
5051 return NO_INIT;
5052 }
5053 strategy = dstChain->strategy();
5054 }
5055 if (reRegister) {
5056 AudioSystem::unregisterEffect(effect->id());
5057 AudioSystem::registerEffect(&effect->desc(),
5058 dstOutput,
5059 strategy,
5060 session,
5061 effect->id());
5062 }
Eric Laurentde070132010-07-13 04:45:46 -07005063 effect = chain->getEffectFromId_l(0);
5064 }
5065
5066 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005067}
5068
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005069
Mathias Agopian65ab4712010-07-14 17:59:35 -07005070// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005071sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005072 const sp<AudioFlinger::Client>& client,
5073 const sp<IEffectClient>& effectClient,
5074 int32_t priority,
5075 int sessionId,
5076 effect_descriptor_t *desc,
5077 int *enabled,
5078 status_t *status
5079 )
5080{
5081 sp<EffectModule> effect;
5082 sp<EffectHandle> handle;
5083 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005084 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005085 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 bool effectCreated = false;
5087 bool effectRegistered = false;
5088
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005089 lStatus = initCheck();
5090 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005092 goto Exit;
5093 }
5094
5095 // Do not allow effects with session ID 0 on direct output or duplicating threads
5096 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005097 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005098 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5099 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 lStatus = BAD_VALUE;
5101 goto Exit;
5102 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005103 // Only Pre processor effects are allowed on input threads and only on input threads
5104 if ((mType == RECORD &&
5105 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5106 (mType != RECORD &&
5107 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5108 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5109 desc->name, desc->flags, mType);
5110 lStatus = BAD_VALUE;
5111 goto Exit;
5112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113
5114 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5115
5116 { // scope for mLock
5117 Mutex::Autolock _l(mLock);
5118
5119 // check for existing effect chain with the requested audio session
5120 chain = getEffectChain_l(sessionId);
5121 if (chain == 0) {
5122 // create a new chain for this session
5123 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5124 chain = new EffectChain(this, sessionId);
5125 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005126 chain->setStrategy(getStrategyForSession_l(sessionId));
5127 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005128 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005129 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005130 }
5131
5132 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5133
5134 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005135 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005136 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005137 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 if (lStatus != NO_ERROR) {
5139 goto Exit;
5140 }
5141 effectRegistered = true;
5142 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005143 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005144 lStatus = effect->status();
5145 if (lStatus != NO_ERROR) {
5146 goto Exit;
5147 }
Eric Laurentcab11242010-07-15 12:50:15 -07005148 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005149 if (lStatus != NO_ERROR) {
5150 goto Exit;
5151 }
5152 effectCreated = true;
5153
5154 effect->setDevice(mDevice);
5155 effect->setMode(mAudioFlinger->getMode());
5156 }
5157 // create effect handle and connect it to effect module
5158 handle = new EffectHandle(effect, client, effectClient, priority);
5159 lStatus = effect->addHandle(handle);
5160 if (enabled) {
5161 *enabled = (int)effect->isEnabled();
5162 }
5163 }
5164
5165Exit:
5166 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005167 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005169 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 }
5171 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005172 AudioSystem::unregisterEffect(effect->id());
5173 }
5174 if (chainCreated) {
5175 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176 }
5177 handle.clear();
5178 }
5179
5180 if(status) {
5181 *status = lStatus;
5182 }
5183 return handle;
5184}
5185
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005186sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5187{
5188 sp<EffectModule> effect;
5189
5190 sp<EffectChain> chain = getEffectChain_l(sessionId);
5191 if (chain != 0) {
5192 effect = chain->getEffectFromId_l(effectId);
5193 }
5194 return effect;
5195}
5196
Eric Laurentde070132010-07-13 04:45:46 -07005197// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5198// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005199status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005200{
5201 // check for existing effect chain with the requested audio session
5202 int sessionId = effect->sessionId();
5203 sp<EffectChain> chain = getEffectChain_l(sessionId);
5204 bool chainCreated = false;
5205
5206 if (chain == 0) {
5207 // create a new chain for this session
5208 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5209 chain = new EffectChain(this, sessionId);
5210 addEffectChain_l(chain);
5211 chain->setStrategy(getStrategyForSession_l(sessionId));
5212 chainCreated = true;
5213 }
5214 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5215
5216 if (chain->getEffectFromId_l(effect->id()) != 0) {
5217 LOGW("addEffect_l() %p effect %s already present in chain %p",
5218 this, effect->desc().name, chain.get());
5219 return BAD_VALUE;
5220 }
5221
5222 status_t status = chain->addEffect_l(effect);
5223 if (status != NO_ERROR) {
5224 if (chainCreated) {
5225 removeEffectChain_l(chain);
5226 }
5227 return status;
5228 }
5229
5230 effect->setDevice(mDevice);
5231 effect->setMode(mAudioFlinger->getMode());
5232 return NO_ERROR;
5233}
5234
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005235void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005236
5237 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005238 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005239 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5240 detachAuxEffect_l(effect->id());
5241 }
5242
5243 sp<EffectChain> chain = effect->chain().promote();
5244 if (chain != 0) {
5245 // remove effect chain if removing last effect
5246 if (chain->removeEffect_l(effect) == 0) {
5247 removeEffectChain_l(chain);
5248 }
5249 } else {
5250 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5251 }
5252}
5253
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005254void AudioFlinger::ThreadBase::lockEffectChains_l(
5255 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5256{
5257 effectChains = mEffectChains;
5258 for (size_t i = 0; i < mEffectChains.size(); i++) {
5259 mEffectChains[i]->lock();
5260 }
5261}
5262
5263void AudioFlinger::ThreadBase::unlockEffectChains(
5264 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5265{
5266 for (size_t i = 0; i < effectChains.size(); i++) {
5267 effectChains[i]->unlock();
5268 }
5269}
5270
5271sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5272{
5273 Mutex::Autolock _l(mLock);
5274 return getEffectChain_l(sessionId);
5275}
5276
5277sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5278{
5279 sp<EffectChain> chain;
5280
5281 size_t size = mEffectChains.size();
5282 for (size_t i = 0; i < size; i++) {
5283 if (mEffectChains[i]->sessionId() == sessionId) {
5284 chain = mEffectChains[i];
5285 break;
5286 }
5287 }
5288 return chain;
5289}
5290
5291void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5292{
5293 Mutex::Autolock _l(mLock);
5294 size_t size = mEffectChains.size();
5295 for (size_t i = 0; i < size; i++) {
5296 mEffectChains[i]->setMode_l(mode);
5297 }
5298}
5299
5300void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurentde070132010-07-13 04:45:46 -07005301 const wp<EffectHandle>& handle) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005302 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005303 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005304 // delete the effect module if removing last handle on it
5305 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07005306 removeEffect_l(effect);
5307 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005308 }
5309}
5310
5311status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5312{
5313 int session = chain->sessionId();
5314 int16_t *buffer = mMixBuffer;
5315 bool ownsBuffer = false;
5316
5317 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5318 if (session > 0) {
5319 // Only one effect chain can be present in direct output thread and it uses
5320 // the mix buffer as input
5321 if (mType != DIRECT) {
5322 size_t numSamples = mFrameCount * mChannelCount;
5323 buffer = new int16_t[numSamples];
5324 memset(buffer, 0, numSamples * sizeof(int16_t));
5325 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5326 ownsBuffer = true;
5327 }
5328
5329 // Attach all tracks with same session ID to this chain.
5330 for (size_t i = 0; i < mTracks.size(); ++i) {
5331 sp<Track> track = mTracks[i];
5332 if (session == track->sessionId()) {
5333 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5334 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005335 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005336 }
5337 }
5338
5339 // indicate all active tracks in the chain
5340 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5341 sp<Track> track = mActiveTracks[i].promote();
5342 if (track == 0) continue;
5343 if (session == track->sessionId()) {
5344 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005345 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005346 }
5347 }
5348 }
5349
5350 chain->setInBuffer(buffer, ownsBuffer);
5351 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005352 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005353 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005354 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5355 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005357 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5358 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005359 // Effect chain for other sessions are inserted at beginning of effect
5360 // chains list to be processed before output mix effects. Relative order between other
5361 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005362 size_t size = mEffectChains.size();
5363 size_t i = 0;
5364 for (i = 0; i < size; i++) {
5365 if (mEffectChains[i]->sessionId() < session) break;
5366 }
5367 mEffectChains.insertAt(chain, i);
5368
5369 return NO_ERROR;
5370}
5371
5372size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5373{
5374 int session = chain->sessionId();
5375
5376 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5377
5378 for (size_t i = 0; i < mEffectChains.size(); i++) {
5379 if (chain == mEffectChains[i]) {
5380 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005381 // detach all active tracks from the chain
5382 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5383 sp<Track> track = mActiveTracks[i].promote();
5384 if (track == 0) continue;
5385 if (session == track->sessionId()) {
5386 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5387 chain.get(), session);
5388 chain->decActiveTrackCnt();
5389 }
5390 }
5391
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 // detach all tracks with same session ID from this chain
5393 for (size_t i = 0; i < mTracks.size(); ++i) {
5394 sp<Track> track = mTracks[i];
5395 if (session == track->sessionId()) {
5396 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005397 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398 }
5399 }
Eric Laurentde070132010-07-13 04:45:46 -07005400 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005401 }
5402 }
5403 return mEffectChains.size();
5404}
5405
Eric Laurentde070132010-07-13 04:45:46 -07005406status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5407 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408{
5409 Mutex::Autolock _l(mLock);
5410 return attachAuxEffect_l(track, EffectId);
5411}
5412
Eric Laurentde070132010-07-13 04:45:46 -07005413status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5414 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005415{
5416 status_t status = NO_ERROR;
5417
5418 if (EffectId == 0) {
5419 track->setAuxBuffer(0, NULL);
5420 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005421 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5422 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005423 if (effect != 0) {
5424 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5425 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5426 } else {
5427 status = INVALID_OPERATION;
5428 }
5429 } else {
5430 status = BAD_VALUE;
5431 }
5432 }
5433 return status;
5434}
5435
5436void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5437{
5438 for (size_t i = 0; i < mTracks.size(); ++i) {
5439 sp<Track> track = mTracks[i];
5440 if (track->auxEffectId() == effectId) {
5441 attachAuxEffect_l(track, 0);
5442 }
5443 }
5444}
5445
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005446status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5447{
5448 // only one chain per input thread
5449 if (mEffectChains.size() != 0) {
5450 return INVALID_OPERATION;
5451 }
5452 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5453
5454 chain->setInBuffer(NULL);
5455 chain->setOutBuffer(NULL);
5456
5457 mEffectChains.add(chain);
5458
5459 return NO_ERROR;
5460}
5461
5462size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5463{
5464 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5465 LOGW_IF(mEffectChains.size() != 1,
5466 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5467 chain.get(), mEffectChains.size(), this);
5468 if (mEffectChains.size() == 1) {
5469 mEffectChains.removeAt(0);
5470 }
5471 return 0;
5472}
5473
Mathias Agopian65ab4712010-07-14 17:59:35 -07005474// ----------------------------------------------------------------------------
5475// EffectModule implementation
5476// ----------------------------------------------------------------------------
5477
5478#undef LOG_TAG
5479#define LOG_TAG "AudioFlinger::EffectModule"
5480
5481AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5482 const wp<AudioFlinger::EffectChain>& chain,
5483 effect_descriptor_t *desc,
5484 int id,
5485 int sessionId)
5486 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5487 mStatus(NO_INIT), mState(IDLE)
5488{
5489 LOGV("Constructor %p", this);
5490 int lStatus;
5491 sp<ThreadBase> thread = mThread.promote();
5492 if (thread == 0) {
5493 return;
5494 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005495
5496 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5497
5498 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005499 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005500
5501 if (mStatus != NO_ERROR) {
5502 return;
5503 }
5504 lStatus = init();
5505 if (lStatus < 0) {
5506 mStatus = lStatus;
5507 goto Error;
5508 }
5509
5510 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5511 return;
5512Error:
5513 EffectRelease(mEffectInterface);
5514 mEffectInterface = NULL;
5515 LOGV("Constructor Error %d", mStatus);
5516}
5517
5518AudioFlinger::EffectModule::~EffectModule()
5519{
5520 LOGV("Destructor %p", this);
5521 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005522 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5523 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
5524 sp<ThreadBase> thread = mThread.promote();
5525 if (thread != 0) {
5526 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5527 }
5528 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 // release effect engine
5530 EffectRelease(mEffectInterface);
5531 }
5532}
5533
5534status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5535{
5536 status_t status;
5537
5538 Mutex::Autolock _l(mLock);
5539 // First handle in mHandles has highest priority and controls the effect module
5540 int priority = handle->priority();
5541 size_t size = mHandles.size();
5542 sp<EffectHandle> h;
5543 size_t i;
5544 for (i = 0; i < size; i++) {
5545 h = mHandles[i].promote();
5546 if (h == 0) continue;
5547 if (h->priority() <= priority) break;
5548 }
5549 // if inserted in first place, move effect control from previous owner to this handle
5550 if (i == 0) {
5551 if (h != 0) {
5552 h->setControl(false, true);
5553 }
5554 handle->setControl(true, false);
5555 status = NO_ERROR;
5556 } else {
5557 status = ALREADY_EXISTS;
5558 }
5559 mHandles.insertAt(handle, i);
5560 return status;
5561}
5562
5563size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5564{
5565 Mutex::Autolock _l(mLock);
5566 size_t size = mHandles.size();
5567 size_t i;
5568 for (i = 0; i < size; i++) {
5569 if (mHandles[i] == handle) break;
5570 }
5571 if (i == size) {
5572 return size;
5573 }
5574 mHandles.removeAt(i);
5575 size = mHandles.size();
5576 // if removed from first place, move effect control from this handle to next in line
5577 if (i == 0 && size != 0) {
5578 sp<EffectHandle> h = mHandles[0].promote();
5579 if (h != 0) {
5580 h->setControl(true, true);
5581 }
5582 }
5583
Eric Laurentdac69112010-09-28 14:09:57 -07005584 // Release effect engine here so that it is done immediately. Otherwise it will be released
5585 // by the destructor when the last strong reference on the this object is released which can
5586 // happen after next process is called on this effect.
5587 if (size == 0 && mEffectInterface != NULL) {
5588 // release effect engine
5589 EffectRelease(mEffectInterface);
5590 mEffectInterface = NULL;
5591 }
5592
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 return size;
5594}
5595
5596void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5597{
5598 // keep a strong reference on this EffectModule to avoid calling the
5599 // destructor before we exit
5600 sp<EffectModule> keep(this);
5601 {
5602 sp<ThreadBase> thread = mThread.promote();
5603 if (thread != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005604 thread->disconnectEffect(keep, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005605 }
5606 }
5607}
5608
5609void AudioFlinger::EffectModule::updateState() {
5610 Mutex::Autolock _l(mLock);
5611
5612 switch (mState) {
5613 case RESTART:
5614 reset_l();
5615 // FALL THROUGH
5616
5617 case STARTING:
5618 // clear auxiliary effect input buffer for next accumulation
5619 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5620 memset(mConfig.inputCfg.buffer.raw,
5621 0,
5622 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5623 }
5624 start_l();
5625 mState = ACTIVE;
5626 break;
5627 case STOPPING:
5628 stop_l();
5629 mDisableWaitCnt = mMaxDisableWaitCnt;
5630 mState = STOPPED;
5631 break;
5632 case STOPPED:
5633 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5634 // turn off sequence.
5635 if (--mDisableWaitCnt == 0) {
5636 reset_l();
5637 mState = IDLE;
5638 }
5639 break;
5640 default: //IDLE , ACTIVE
5641 break;
5642 }
5643}
5644
5645void AudioFlinger::EffectModule::process()
5646{
5647 Mutex::Autolock _l(mLock);
5648
5649 if (mEffectInterface == NULL ||
5650 mConfig.inputCfg.buffer.raw == NULL ||
5651 mConfig.outputCfg.buffer.raw == NULL) {
5652 return;
5653 }
5654
Eric Laurent8f45bd72010-08-31 13:50:07 -07005655 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5657 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5658 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5659 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005660 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005661 }
5662
5663 // do the actual processing in the effect engine
5664 int ret = (*mEffectInterface)->process(mEffectInterface,
5665 &mConfig.inputCfg.buffer,
5666 &mConfig.outputCfg.buffer);
5667
5668 // force transition to IDLE state when engine is ready
5669 if (mState == STOPPED && ret == -ENODATA) {
5670 mDisableWaitCnt = 1;
5671 }
5672
5673 // clear auxiliary effect input buffer for next accumulation
5674 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005675 memset(mConfig.inputCfg.buffer.raw, 0,
5676 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005677 }
5678 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005679 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5680 // If an insert effect is idle and input buffer is different from output buffer,
5681 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07005683 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005684 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5685 int16_t *in = mConfig.inputCfg.buffer.s16;
5686 int16_t *out = mConfig.outputCfg.buffer.s16;
5687 for (size_t i = 0; i < frameCnt; i++) {
5688 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005689 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 }
5691 }
5692}
5693
5694void AudioFlinger::EffectModule::reset_l()
5695{
5696 if (mEffectInterface == NULL) {
5697 return;
5698 }
5699 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5700}
5701
5702status_t AudioFlinger::EffectModule::configure()
5703{
5704 uint32_t channels;
5705 if (mEffectInterface == NULL) {
5706 return NO_INIT;
5707 }
5708
5709 sp<ThreadBase> thread = mThread.promote();
5710 if (thread == 0) {
5711 return DEAD_OBJECT;
5712 }
5713
5714 // TODO: handle configuration of effects replacing track process
5715 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005716 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005717 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07005718 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005719 }
5720
5721 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005722 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723 } else {
5724 mConfig.inputCfg.channels = channels;
5725 }
5726 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07005727 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5728 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005729 mConfig.inputCfg.samplingRate = thread->sampleRate();
5730 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5731 mConfig.inputCfg.bufferProvider.cookie = NULL;
5732 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5733 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5734 mConfig.outputCfg.bufferProvider.cookie = NULL;
5735 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5736 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5737 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5738 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07005739 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07005740 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005741 // - in other sessions:
5742 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5743 // other effect: overwrites output buffer: input buffer == output buffer
5744 // Auxiliary effect:
5745 // accumulates in output buffer: input buffer != output buffer
5746 // Therefore: accumulate <=> input buffer != output buffer
5747 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5748 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5749 } else {
5750 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5751 }
5752 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5753 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5754 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5755 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5756
Eric Laurentde070132010-07-13 04:45:46 -07005757 LOGV("configure() %p thread %p buffer %p framecount %d",
5758 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5759
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005761 uint32_t size = sizeof(int);
5762 status_t status = (*mEffectInterface)->command(mEffectInterface,
5763 EFFECT_CMD_CONFIGURE,
5764 sizeof(effect_config_t),
5765 &mConfig,
5766 &size,
5767 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005768 if (status == 0) {
5769 status = cmdStatus;
5770 }
5771
5772 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5773 (1000 * mConfig.outputCfg.buffer.frameCount);
5774
5775 return status;
5776}
5777
5778status_t AudioFlinger::EffectModule::init()
5779{
5780 Mutex::Autolock _l(mLock);
5781 if (mEffectInterface == NULL) {
5782 return NO_INIT;
5783 }
5784 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005785 uint32_t size = sizeof(status_t);
5786 status_t status = (*mEffectInterface)->command(mEffectInterface,
5787 EFFECT_CMD_INIT,
5788 0,
5789 NULL,
5790 &size,
5791 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005792 if (status == 0) {
5793 status = cmdStatus;
5794 }
5795 return status;
5796}
5797
5798status_t AudioFlinger::EffectModule::start_l()
5799{
5800 if (mEffectInterface == NULL) {
5801 return NO_INIT;
5802 }
5803 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005804 uint32_t size = sizeof(status_t);
5805 status_t status = (*mEffectInterface)->command(mEffectInterface,
5806 EFFECT_CMD_ENABLE,
5807 0,
5808 NULL,
5809 &size,
5810 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005811 if (status == 0) {
5812 status = cmdStatus;
5813 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005814 if (status == 0 &&
5815 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5816 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
5817 sp<ThreadBase> thread = mThread.promote();
5818 if (thread != 0) {
5819 thread->stream()->add_audio_effect(thread->stream(), mEffectInterface);
5820 }
5821 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005822 return status;
5823}
5824
5825status_t AudioFlinger::EffectModule::stop_l()
5826{
5827 if (mEffectInterface == NULL) {
5828 return NO_INIT;
5829 }
5830 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005831 uint32_t size = sizeof(status_t);
5832 status_t status = (*mEffectInterface)->command(mEffectInterface,
5833 EFFECT_CMD_DISABLE,
5834 0,
5835 NULL,
5836 &size,
5837 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838 if (status == 0) {
5839 status = cmdStatus;
5840 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005841 if (status == 0 &&
5842 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5843 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
5844 sp<ThreadBase> thread = mThread.promote();
5845 if (thread != 0) {
5846 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5847 }
5848 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849 return status;
5850}
5851
Eric Laurent25f43952010-07-28 05:40:18 -07005852status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5853 uint32_t cmdSize,
5854 void *pCmdData,
5855 uint32_t *replySize,
5856 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857{
5858 Mutex::Autolock _l(mLock);
5859// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5860
5861 if (mEffectInterface == NULL) {
5862 return NO_INIT;
5863 }
Eric Laurent25f43952010-07-28 05:40:18 -07005864 status_t status = (*mEffectInterface)->command(mEffectInterface,
5865 cmdCode,
5866 cmdSize,
5867 pCmdData,
5868 replySize,
5869 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005870 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07005871 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005872 for (size_t i = 1; i < mHandles.size(); i++) {
5873 sp<EffectHandle> h = mHandles[i].promote();
5874 if (h != 0) {
5875 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5876 }
5877 }
5878 }
5879 return status;
5880}
5881
5882status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5883{
5884 Mutex::Autolock _l(mLock);
5885 LOGV("setEnabled %p enabled %d", this, enabled);
5886
5887 if (enabled != isEnabled()) {
5888 switch (mState) {
5889 // going from disabled to enabled
5890 case IDLE:
5891 mState = STARTING;
5892 break;
5893 case STOPPED:
5894 mState = RESTART;
5895 break;
5896 case STOPPING:
5897 mState = ACTIVE;
5898 break;
5899
5900 // going from enabled to disabled
5901 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005902 mState = STOPPED;
5903 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 case STARTING:
5905 mState = IDLE;
5906 break;
5907 case ACTIVE:
5908 mState = STOPPING;
5909 break;
5910 }
5911 for (size_t i = 1; i < mHandles.size(); i++) {
5912 sp<EffectHandle> h = mHandles[i].promote();
5913 if (h != 0) {
5914 h->setEnabled(enabled);
5915 }
5916 }
5917 }
5918 return NO_ERROR;
5919}
5920
5921bool AudioFlinger::EffectModule::isEnabled()
5922{
5923 switch (mState) {
5924 case RESTART:
5925 case STARTING:
5926 case ACTIVE:
5927 return true;
5928 case IDLE:
5929 case STOPPING:
5930 case STOPPED:
5931 default:
5932 return false;
5933 }
5934}
5935
Eric Laurent8f45bd72010-08-31 13:50:07 -07005936bool AudioFlinger::EffectModule::isProcessEnabled()
5937{
5938 switch (mState) {
5939 case RESTART:
5940 case ACTIVE:
5941 case STOPPING:
5942 case STOPPED:
5943 return true;
5944 case IDLE:
5945 case STARTING:
5946 default:
5947 return false;
5948 }
5949}
5950
Mathias Agopian65ab4712010-07-14 17:59:35 -07005951status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5952{
5953 Mutex::Autolock _l(mLock);
5954 status_t status = NO_ERROR;
5955
5956 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5957 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07005958 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07005959 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5960 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961 status_t cmdStatus;
5962 uint32_t volume[2];
5963 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07005964 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 volume[0] = *left;
5966 volume[1] = *right;
5967 if (controller) {
5968 pVolume = volume;
5969 }
Eric Laurent25f43952010-07-28 05:40:18 -07005970 status = (*mEffectInterface)->command(mEffectInterface,
5971 EFFECT_CMD_SET_VOLUME,
5972 size,
5973 volume,
5974 &size,
5975 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005976 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5977 *left = volume[0];
5978 *right = volume[1];
5979 }
5980 }
5981 return status;
5982}
5983
5984status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5985{
5986 Mutex::Autolock _l(mLock);
5987 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005988 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
5989 // audio pre processing modules on RecordThread can receive both output and
5990 // input device indication in the same call
5991 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
5992 if (dev) {
5993 status_t cmdStatus;
5994 uint32_t size = sizeof(status_t);
5995
5996 status = (*mEffectInterface)->command(mEffectInterface,
5997 EFFECT_CMD_SET_DEVICE,
5998 sizeof(uint32_t),
5999 &dev,
6000 &size,
6001 &cmdStatus);
6002 if (status == NO_ERROR) {
6003 status = cmdStatus;
6004 }
6005 }
6006 dev = device & AUDIO_DEVICE_IN_ALL;
6007 if (dev) {
6008 status_t cmdStatus;
6009 uint32_t size = sizeof(status_t);
6010
6011 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6012 EFFECT_CMD_SET_INPUT_DEVICE,
6013 sizeof(uint32_t),
6014 &dev,
6015 &size,
6016 &cmdStatus);
6017 if (status2 == NO_ERROR) {
6018 status2 = cmdStatus;
6019 }
6020 if (status == NO_ERROR) {
6021 status = status2;
6022 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006023 }
6024 }
6025 return status;
6026}
6027
6028status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6029{
6030 Mutex::Autolock _l(mLock);
6031 status_t status = NO_ERROR;
6032 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006033 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006034 uint32_t size = sizeof(status_t);
6035 status = (*mEffectInterface)->command(mEffectInterface,
6036 EFFECT_CMD_SET_AUDIO_MODE,
6037 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006038 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006039 &size,
6040 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041 if (status == NO_ERROR) {
6042 status = cmdStatus;
6043 }
6044 }
6045 return status;
6046}
6047
Mathias Agopian65ab4712010-07-14 17:59:35 -07006048status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6049{
6050 const size_t SIZE = 256;
6051 char buffer[SIZE];
6052 String8 result;
6053
6054 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6055 result.append(buffer);
6056
6057 bool locked = tryLock(mLock);
6058 // failed to lock - AudioFlinger is probably deadlocked
6059 if (!locked) {
6060 result.append("\t\tCould not lock Fx mutex:\n");
6061 }
6062
6063 result.append("\t\tSession Status State Engine:\n");
6064 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6065 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6066 result.append(buffer);
6067
6068 result.append("\t\tDescriptor:\n");
6069 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6070 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6071 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6072 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6073 result.append(buffer);
6074 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6075 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6076 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6077 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6078 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006079 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 mDescriptor.apiVersion,
6081 mDescriptor.flags);
6082 result.append(buffer);
6083 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6084 mDescriptor.name);
6085 result.append(buffer);
6086 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6087 mDescriptor.implementor);
6088 result.append(buffer);
6089
6090 result.append("\t\t- Input configuration:\n");
6091 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6092 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6093 (uint32_t)mConfig.inputCfg.buffer.raw,
6094 mConfig.inputCfg.buffer.frameCount,
6095 mConfig.inputCfg.samplingRate,
6096 mConfig.inputCfg.channels,
6097 mConfig.inputCfg.format);
6098 result.append(buffer);
6099
6100 result.append("\t\t- Output configuration:\n");
6101 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6102 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6103 (uint32_t)mConfig.outputCfg.buffer.raw,
6104 mConfig.outputCfg.buffer.frameCount,
6105 mConfig.outputCfg.samplingRate,
6106 mConfig.outputCfg.channels,
6107 mConfig.outputCfg.format);
6108 result.append(buffer);
6109
6110 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6111 result.append(buffer);
6112 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6113 for (size_t i = 0; i < mHandles.size(); ++i) {
6114 sp<EffectHandle> handle = mHandles[i].promote();
6115 if (handle != 0) {
6116 handle->dump(buffer, SIZE);
6117 result.append(buffer);
6118 }
6119 }
6120
6121 result.append("\n");
6122
6123 write(fd, result.string(), result.length());
6124
6125 if (locked) {
6126 mLock.unlock();
6127 }
6128
6129 return NO_ERROR;
6130}
6131
6132// ----------------------------------------------------------------------------
6133// EffectHandle implementation
6134// ----------------------------------------------------------------------------
6135
6136#undef LOG_TAG
6137#define LOG_TAG "AudioFlinger::EffectHandle"
6138
6139AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6140 const sp<AudioFlinger::Client>& client,
6141 const sp<IEffectClient>& effectClient,
6142 int32_t priority)
6143 : BnEffect(),
6144 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
6145{
6146 LOGV("constructor %p", this);
6147
6148 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6149 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6150 if (mCblkMemory != 0) {
6151 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6152
6153 if (mCblk) {
6154 new(mCblk) effect_param_cblk_t();
6155 mBuffer = (uint8_t *)mCblk + bufOffset;
6156 }
6157 } else {
6158 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6159 return;
6160 }
6161}
6162
6163AudioFlinger::EffectHandle::~EffectHandle()
6164{
6165 LOGV("Destructor %p", this);
6166 disconnect();
6167}
6168
6169status_t AudioFlinger::EffectHandle::enable()
6170{
6171 if (!mHasControl) return INVALID_OPERATION;
6172 if (mEffect == 0) return DEAD_OBJECT;
6173
6174 return mEffect->setEnabled(true);
6175}
6176
6177status_t AudioFlinger::EffectHandle::disable()
6178{
6179 if (!mHasControl) return INVALID_OPERATION;
6180 if (mEffect == NULL) return DEAD_OBJECT;
6181
6182 return mEffect->setEnabled(false);
6183}
6184
6185void AudioFlinger::EffectHandle::disconnect()
6186{
6187 if (mEffect == 0) {
6188 return;
6189 }
6190 mEffect->disconnect(this);
6191 // release sp on module => module destructor can be called now
6192 mEffect.clear();
6193 if (mCblk) {
6194 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6195 }
6196 mCblkMemory.clear(); // and free the shared memory
6197 if (mClient != 0) {
6198 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6199 mClient.clear();
6200 }
6201}
6202
Eric Laurent25f43952010-07-28 05:40:18 -07006203status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6204 uint32_t cmdSize,
6205 void *pCmdData,
6206 uint32_t *replySize,
6207 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208{
Eric Laurent25f43952010-07-28 05:40:18 -07006209// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6210// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006211
6212 // only get parameter command is permitted for applications not controlling the effect
6213 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6214 return INVALID_OPERATION;
6215 }
6216 if (mEffect == 0) return DEAD_OBJECT;
6217
6218 // handle commands that are not forwarded transparently to effect engine
6219 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6220 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6221 // no risk to block the whole media server process or mixer threads is we are stuck here
6222 Mutex::Autolock _l(mCblk->lock);
6223 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6224 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6225 mCblk->serverIndex = 0;
6226 mCblk->clientIndex = 0;
6227 return BAD_VALUE;
6228 }
6229 status_t status = NO_ERROR;
6230 while (mCblk->serverIndex < mCblk->clientIndex) {
6231 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006232 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006233 int *p = (int *)(mBuffer + mCblk->serverIndex);
6234 int size = *p++;
6235 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6236 LOGW("command(): invalid parameter block size");
6237 break;
6238 }
6239 effect_param_t *param = (effect_param_t *)p;
6240 if (param->psize == 0 || param->vsize == 0) {
6241 LOGW("command(): null parameter or value size");
6242 mCblk->serverIndex += size;
6243 continue;
6244 }
Eric Laurent25f43952010-07-28 05:40:18 -07006245 uint32_t psize = sizeof(effect_param_t) +
6246 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6247 param->vsize;
6248 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6249 psize,
6250 p,
6251 &rsize,
6252 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006253 // stop at first error encountered
6254 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006255 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006256 *(int *)pReplyData = reply;
6257 break;
6258 } else if (reply != NO_ERROR) {
6259 *(int *)pReplyData = reply;
6260 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006261 }
6262 mCblk->serverIndex += size;
6263 }
6264 mCblk->serverIndex = 0;
6265 mCblk->clientIndex = 0;
6266 return status;
6267 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006268 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006269 return enable();
6270 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006271 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006272 return disable();
6273 }
6274
6275 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6276}
6277
6278sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6279 return mCblkMemory;
6280}
6281
6282void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6283{
6284 LOGV("setControl %p control %d", this, hasControl);
6285
6286 mHasControl = hasControl;
6287 if (signal && mEffectClient != 0) {
6288 mEffectClient->controlStatusChanged(hasControl);
6289 }
6290}
6291
Eric Laurent25f43952010-07-28 05:40:18 -07006292void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6293 uint32_t cmdSize,
6294 void *pCmdData,
6295 uint32_t replySize,
6296 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006297{
6298 if (mEffectClient != 0) {
6299 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6300 }
6301}
6302
6303
6304
6305void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6306{
6307 if (mEffectClient != 0) {
6308 mEffectClient->enableStatusChanged(enabled);
6309 }
6310}
6311
6312status_t AudioFlinger::EffectHandle::onTransact(
6313 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6314{
6315 return BnEffect::onTransact(code, data, reply, flags);
6316}
6317
6318
6319void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6320{
6321 bool locked = tryLock(mCblk->lock);
6322
6323 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6324 (mClient == NULL) ? getpid() : mClient->pid(),
6325 mPriority,
6326 mHasControl,
6327 !locked,
6328 mCblk->clientIndex,
6329 mCblk->serverIndex
6330 );
6331
6332 if (locked) {
6333 mCblk->lock.unlock();
6334 }
6335}
6336
6337#undef LOG_TAG
6338#define LOG_TAG "AudioFlinger::EffectChain"
6339
6340AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6341 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006342 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6343 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6344 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006345{
Dima Zavinfce7a472011-04-19 22:30:36 -07006346 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006347}
6348
6349AudioFlinger::EffectChain::~EffectChain()
6350{
6351 if (mOwnInBuffer) {
6352 delete mInBuffer;
6353 }
6354
6355}
6356
Eric Laurentcab11242010-07-15 12:50:15 -07006357// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6358sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006359{
6360 sp<EffectModule> effect;
6361 size_t size = mEffects.size();
6362
6363 for (size_t i = 0; i < size; i++) {
6364 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6365 effect = mEffects[i];
6366 break;
6367 }
6368 }
6369 return effect;
6370}
6371
Eric Laurentcab11242010-07-15 12:50:15 -07006372// getEffectFromId_l() must be called with PlaybackThread::mLock held
6373sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374{
6375 sp<EffectModule> effect;
6376 size_t size = mEffects.size();
6377
6378 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006379 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6380 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 effect = mEffects[i];
6382 break;
6383 }
6384 }
6385 return effect;
6386}
6387
6388// Must be called with EffectChain::mLock locked
6389void AudioFlinger::EffectChain::process_l()
6390{
Eric Laurentdac69112010-09-28 14:09:57 -07006391 sp<ThreadBase> thread = mThread.promote();
6392 if (thread == 0) {
6393 LOGW("process_l(): cannot promote mixer thread");
6394 return;
6395 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006396 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6397 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07006398 bool tracksOnSession = false;
6399 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07006400 tracksOnSession = (trackCnt() != 0);
6401 }
6402
6403 // if no track is active, input buffer must be cleared here as the mixer process
6404 // will not do it
6405 if (tracksOnSession &&
6406 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006407 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07006408 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07006409 }
6410
Mathias Agopian65ab4712010-07-14 17:59:35 -07006411 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006412 // do not process effect if no track is present in same audio session
6413 if (isGlobalSession || tracksOnSession) {
6414 for (size_t i = 0; i < size; i++) {
6415 mEffects[i]->process();
6416 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006417 }
6418 for (size_t i = 0; i < size; i++) {
6419 mEffects[i]->updateState();
6420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006421}
6422
Eric Laurentcab11242010-07-15 12:50:15 -07006423// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006424status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425{
6426 effect_descriptor_t desc = effect->desc();
6427 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6428
6429 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006430 effect->setChain(this);
6431 sp<ThreadBase> thread = mThread.promote();
6432 if (thread == 0) {
6433 return NO_INIT;
6434 }
6435 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006436
6437 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6438 // Auxiliary effects are inserted at the beginning of mEffects vector as
6439 // they are processed first and accumulated in chain input buffer
6440 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006441
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 // the input buffer for auxiliary effect contains mono samples in
6443 // 32 bit format. This is to avoid saturation in AudoMixer
6444 // accumulation stage. Saturation is done in EffectModule::process() before
6445 // calling the process in effect engine
6446 size_t numSamples = thread->frameCount();
6447 int32_t *buffer = new int32_t[numSamples];
6448 memset(buffer, 0, numSamples * sizeof(int32_t));
6449 effect->setInBuffer((int16_t *)buffer);
6450 // auxiliary effects output samples to chain input buffer for further processing
6451 // by insert effects
6452 effect->setOutBuffer(mInBuffer);
6453 } else {
6454 // Insert effects are inserted at the end of mEffects vector as they are processed
6455 // after track and auxiliary effects.
6456 // Insert effect order as a function of indicated preference:
6457 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6458 // another effect is present
6459 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6460 // last effect claiming first position
6461 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6462 // first effect claiming last position
6463 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6464 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6465 // already present
6466
6467 int size = (int)mEffects.size();
6468 int idx_insert = size;
6469 int idx_insert_first = -1;
6470 int idx_insert_last = -1;
6471
6472 for (int i = 0; i < size; i++) {
6473 effect_descriptor_t d = mEffects[i]->desc();
6474 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6475 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6476 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6477 // check invalid effect chaining combinations
6478 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6479 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006480 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 return INVALID_OPERATION;
6482 }
6483 // remember position of first insert effect and by default
6484 // select this as insert position for new effect
6485 if (idx_insert == size) {
6486 idx_insert = i;
6487 }
6488 // remember position of last insert effect claiming
6489 // first position
6490 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6491 idx_insert_first = i;
6492 }
6493 // remember position of first insert effect claiming
6494 // last position
6495 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6496 idx_insert_last == -1) {
6497 idx_insert_last = i;
6498 }
6499 }
6500 }
6501
6502 // modify idx_insert from first position if needed
6503 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6504 if (idx_insert_last != -1) {
6505 idx_insert = idx_insert_last;
6506 } else {
6507 idx_insert = size;
6508 }
6509 } else {
6510 if (idx_insert_first != -1) {
6511 idx_insert = idx_insert_first + 1;
6512 }
6513 }
6514
6515 // always read samples from chain input buffer
6516 effect->setInBuffer(mInBuffer);
6517
6518 // if last effect in the chain, output samples to chain
6519 // output buffer, otherwise to chain input buffer
6520 if (idx_insert == size) {
6521 if (idx_insert != 0) {
6522 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6523 mEffects[idx_insert-1]->configure();
6524 }
6525 effect->setOutBuffer(mOutBuffer);
6526 } else {
6527 effect->setOutBuffer(mInBuffer);
6528 }
6529 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006530
Eric Laurentcab11242010-07-15 12:50:15 -07006531 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006532 }
6533 effect->configure();
6534 return NO_ERROR;
6535}
6536
Eric Laurentcab11242010-07-15 12:50:15 -07006537// removeEffect_l() must be called with PlaybackThread::mLock held
6538size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006539{
6540 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006541 int size = (int)mEffects.size();
6542 int i;
6543 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6544
6545 for (i = 0; i < size; i++) {
6546 if (effect == mEffects[i]) {
6547 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6548 delete[] effect->inBuffer();
6549 } else {
6550 if (i == size - 1 && i != 0) {
6551 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6552 mEffects[i - 1]->configure();
6553 }
6554 }
6555 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006556 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 break;
6558 }
6559 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006560
6561 return mEffects.size();
6562}
6563
Eric Laurentcab11242010-07-15 12:50:15 -07006564// setDevice_l() must be called with PlaybackThread::mLock held
6565void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566{
6567 size_t size = mEffects.size();
6568 for (size_t i = 0; i < size; i++) {
6569 mEffects[i]->setDevice(device);
6570 }
6571}
6572
Eric Laurentcab11242010-07-15 12:50:15 -07006573// setMode_l() must be called with PlaybackThread::mLock held
6574void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006575{
6576 size_t size = mEffects.size();
6577 for (size_t i = 0; i < size; i++) {
6578 mEffects[i]->setMode(mode);
6579 }
6580}
6581
Eric Laurentcab11242010-07-15 12:50:15 -07006582// setVolume_l() must be called with PlaybackThread::mLock held
6583bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584{
6585 uint32_t newLeft = *left;
6586 uint32_t newRight = *right;
6587 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006588 int ctrlIdx = -1;
6589 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590
Eric Laurentcab11242010-07-15 12:50:15 -07006591 // first update volume controller
6592 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006593 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006594 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6595 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006596 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006597 break;
6598 }
6599 }
6600
6601 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006602 if (hasControl) {
6603 *left = mNewLeftVolume;
6604 *right = mNewRightVolume;
6605 }
6606 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006607 }
6608
6609 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006610 mLeftVolume = newLeft;
6611 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006612
6613 // second get volume update from volume controller
6614 if (ctrlIdx >= 0) {
6615 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006616 mNewLeftVolume = newLeft;
6617 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006618 }
6619 // then indicate volume to all other effects in chain.
6620 // Pass altered volume to effects before volume controller
6621 // and requested volume to effects after controller
6622 uint32_t lVol = newLeft;
6623 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006624
Mathias Agopian65ab4712010-07-14 17:59:35 -07006625 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006626 if ((int)i == ctrlIdx) continue;
6627 // this also works for ctrlIdx == -1 when there is no volume controller
6628 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629 lVol = *left;
6630 rVol = *right;
6631 }
6632 mEffects[i]->setVolume(&lVol, &rVol, false);
6633 }
6634 *left = newLeft;
6635 *right = newRight;
6636
6637 return hasControl;
6638}
6639
Mathias Agopian65ab4712010-07-14 17:59:35 -07006640status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6641{
6642 const size_t SIZE = 256;
6643 char buffer[SIZE];
6644 String8 result;
6645
6646 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6647 result.append(buffer);
6648
6649 bool locked = tryLock(mLock);
6650 // failed to lock - AudioFlinger is probably deadlocked
6651 if (!locked) {
6652 result.append("\tCould not lock mutex:\n");
6653 }
6654
Eric Laurentcab11242010-07-15 12:50:15 -07006655 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6656 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006657 mEffects.size(),
6658 (uint32_t)mInBuffer,
6659 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006660 mActiveTrackCnt);
6661 result.append(buffer);
6662 write(fd, result.string(), result.size());
6663
6664 for (size_t i = 0; i < mEffects.size(); ++i) {
6665 sp<EffectModule> effect = mEffects[i];
6666 if (effect != 0) {
6667 effect->dump(fd, args);
6668 }
6669 }
6670
6671 if (locked) {
6672 mLock.unlock();
6673 }
6674
6675 return NO_ERROR;
6676}
6677
6678#undef LOG_TAG
6679#define LOG_TAG "AudioFlinger"
6680
6681// ----------------------------------------------------------------------------
6682
6683status_t AudioFlinger::onTransact(
6684 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6685{
6686 return BnAudioFlinger::onTransact(code, data, reply, flags);
6687}
6688
Mathias Agopian65ab4712010-07-14 17:59:35 -07006689}; // namespace android