blob: fb508a7741caff3079f73858b777d687bcae8a25 [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>
Glenn Kastenf6b16782011-12-15 09:51:17 -080038#include <cutils/compiler.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070039
40#include <media/AudioTrack.h>
41#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080042#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043
44#include <private/media/AudioTrackShared.h>
45#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070046
Dima Zavin64760242011-05-11 14:15:23 -070047#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070048#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
50#include "AudioMixer.h"
51#include "AudioFlinger.h"
52
Mathias Agopian65ab4712010-07-14 17:59:35 -070053#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070054#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070055#include <audio_effects/effect_ns.h>
56#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070057
Glenn Kasten3b21c502011-12-15 09:52:39 -080058#include <audio_utils/primitives.h>
59
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070060#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070061#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070062// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
63
Mathias Agopian65ab4712010-07-14 17:59:35 -070064// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070065
Eric Laurentde070132010-07-13 04:45:46 -070066
Mathias Agopian65ab4712010-07-14 17:59:35 -070067namespace android {
68
Glenn Kastenec1d6b52011-12-12 09:04:45 -080069static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
70static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070071
72//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
73static const float MAX_GAIN = 4096.0f;
74static const float MAX_GAIN_INT = 0x1000;
75
76// retry counts for buffer fill timeout
77// 50 * ~20msecs = 1 second
78static const int8_t kMaxTrackRetries = 50;
79static const int8_t kMaxTrackStartupRetries = 50;
80// allow less retry attempts on direct output thread.
81// direct outputs can be a scarce resource in audio hardware and should
82// be released as quickly as possible.
83static const int8_t kMaxTrackRetriesDirect = 2;
84
85static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080086static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Glenn Kasten7dede872011-12-13 11:04:14 -080088// don't warn about blocked writes or record buffer overflows more often than this
89static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Eric Laurent7c7f10b2011-06-17 21:29:58 -070091// RecordThread loop sleep time upon application overrun or audio HAL read error
92static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
Glenn Kasten7dede872011-12-13 11:04:14 -080094// maximum time to wait for setParameters to complete
95static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070096
Eric Laurent7cafbb32011-11-22 18:50:29 -080097// minimum sleep time for the mixer thread loop when tracks are active but in underrun
98static const uint32_t kMinThreadSleepTimeUs = 5000;
99// maximum divider applied to the active sleep time in the mixer thread loop
100static const uint32_t kMaxThreadSleepTimeShift = 2;
101
102
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103// ----------------------------------------------------------------------------
104
105static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
107 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
108 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
109 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110}
111
112static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
114 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
115 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
116 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117}
118
Gloria Wang9ee159b2011-02-24 14:51:45 -0800119// To collect the amplifier usage
120static void addBatteryData(uint32_t params) {
121 sp<IBinder> binder =
122 defaultServiceManager()->getService(String16("media.player"));
123 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
124 if (service.get() == NULL) {
125 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
126 return;
127 }
128
129 service->addBatteryData(params);
130}
131
Dima Zavin799a70e2011-04-18 16:57:27 -0700132static int load_audio_interface(const char *if_name, const hw_module_t **mod,
133 audio_hw_device_t **dev)
134{
135 int rc;
136
137 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
138 if (rc)
139 goto out;
140
141 rc = audio_hw_device_open(*mod, dev);
142 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
143 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
144 if (rc)
145 goto out;
146
147 return 0;
148
149out:
150 *mod = NULL;
151 *dev = NULL;
152 return rc;
153}
154
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800155static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700156 "primary",
157 "a2dp",
158 "usb",
159};
160#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
161
Mathias Agopian65ab4712010-07-14 17:59:35 -0700162// ----------------------------------------------------------------------------
163
164AudioFlinger::AudioFlinger()
165 : BnAudioFlinger(),
Glenn Kastene0feee32011-12-13 11:53:26 -0800166 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700167 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700168{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700169}
170
171void AudioFlinger::onFirstRef()
172{
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Eric Laurent93575202011-01-18 18:39:02 -0800175 Mutex::Autolock _l(mLock);
176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700178 mHardwareStatus = AUDIO_HW_IDLE;
179
Dima Zavin799a70e2011-04-18 16:57:27 -0700180 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
181 const hw_module_t *mod;
182 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700183
Dima Zavin799a70e2011-04-18 16:57:27 -0700184 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
185 if (rc)
186 continue;
187
188 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
189 mod->name, mod->id);
190 mAudioHwDevs.push(dev);
191
192 if (!mPrimaryHardwareDev) {
193 mPrimaryHardwareDev = dev;
194 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700195 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700196 }
197 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700198
199 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700200
Dima Zavin799a70e2011-04-18 16:57:27 -0700201 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
202 LOGE("Primary audio interface not found");
203 return;
204 }
205
206 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
207 audio_hw_device_t *dev = mAudioHwDevs[i];
208
209 mHardwareStatus = AUDIO_HW_INIT;
210 rc = dev->init_check(dev);
211 if (rc == 0) {
212 AutoMutex lock(mHardwareLock);
213
214 mMode = AUDIO_MODE_NORMAL;
215 mHardwareStatus = AUDIO_HW_SET_MODE;
216 dev->set_mode(dev, mMode);
217 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
218 dev->set_master_volume(dev, 1.0f);
219 mHardwareStatus = AUDIO_HW_IDLE;
220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700222}
223
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700224status_t AudioFlinger::initCheck() const
225{
226 Mutex::Autolock _l(mLock);
227 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
228 return NO_INIT;
229 return NO_ERROR;
230}
231
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232AudioFlinger::~AudioFlinger()
233{
Dima Zavin799a70e2011-04-18 16:57:27 -0700234 int num_devs = mAudioHwDevs.size();
235
Mathias Agopian65ab4712010-07-14 17:59:35 -0700236 while (!mRecordThreads.isEmpty()) {
237 // closeInput() will remove first entry from mRecordThreads
238 closeInput(mRecordThreads.keyAt(0));
239 }
240 while (!mPlaybackThreads.isEmpty()) {
241 // closeOutput() will remove first entry from mPlaybackThreads
242 closeOutput(mPlaybackThreads.keyAt(0));
243 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700244
245 for (int i = 0; i < num_devs; i++) {
246 audio_hw_device_t *dev = mAudioHwDevs[i];
247 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700248 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700249 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700250}
251
Dima Zavin799a70e2011-04-18 16:57:27 -0700252audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
253{
254 /* first matching HW device is returned */
255 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
256 audio_hw_device_t *dev = mAudioHwDevs[i];
257 if ((dev->get_supported_devices(dev) & devices) == devices)
258 return dev;
259 }
260 return NULL;
261}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700262
263status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
264{
265 const size_t SIZE = 256;
266 char buffer[SIZE];
267 String8 result;
268
269 result.append("Clients:\n");
270 for (size_t i = 0; i < mClients.size(); ++i) {
271 wp<Client> wClient = mClients.valueAt(i);
272 if (wClient != 0) {
273 sp<Client> client = wClient.promote();
274 if (client != 0) {
275 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
276 result.append(buffer);
277 }
278 }
279 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700280
281 result.append("Global session refs:\n");
282 result.append(" session pid cnt\n");
283 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
284 AudioSessionRef *r = mAudioSessionRefs[i];
285 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
286 result.append(buffer);
287 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700288 write(fd, result.string(), result.size());
289 return NO_ERROR;
290}
291
292
293status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
294{
295 const size_t SIZE = 256;
296 char buffer[SIZE];
297 String8 result;
298 int hardwareStatus = mHardwareStatus;
299
300 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
301 result.append(buffer);
302 write(fd, result.string(), result.size());
303 return NO_ERROR;
304}
305
306status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
307{
308 const size_t SIZE = 256;
309 char buffer[SIZE];
310 String8 result;
311 snprintf(buffer, SIZE, "Permission Denial: "
312 "can't dump AudioFlinger from pid=%d, uid=%d\n",
313 IPCThreadState::self()->getCallingPid(),
314 IPCThreadState::self()->getCallingUid());
315 result.append(buffer);
316 write(fd, result.string(), result.size());
317 return NO_ERROR;
318}
319
320static bool tryLock(Mutex& mutex)
321{
322 bool locked = false;
323 for (int i = 0; i < kDumpLockRetries; ++i) {
324 if (mutex.tryLock() == NO_ERROR) {
325 locked = true;
326 break;
327 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800328 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700329 }
330 return locked;
331}
332
333status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
334{
335 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
336 dumpPermissionDenial(fd, args);
337 } else {
338 // get state of hardware lock
339 bool hardwareLocked = tryLock(mHardwareLock);
340 if (!hardwareLocked) {
341 String8 result(kHardwareLockedString);
342 write(fd, result.string(), result.size());
343 } else {
344 mHardwareLock.unlock();
345 }
346
347 bool locked = tryLock(mLock);
348
349 // failed to lock - AudioFlinger is probably deadlocked
350 if (!locked) {
351 String8 result(kDeadlockedString);
352 write(fd, result.string(), result.size());
353 }
354
355 dumpClients(fd, args);
356 dumpInternals(fd, args);
357
358 // dump playback threads
359 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
360 mPlaybackThreads.valueAt(i)->dump(fd, args);
361 }
362
363 // dump record threads
364 for (size_t i = 0; i < mRecordThreads.size(); i++) {
365 mRecordThreads.valueAt(i)->dump(fd, args);
366 }
367
Dima Zavin799a70e2011-04-18 16:57:27 -0700368 // dump all hardware devs
369 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
370 audio_hw_device_t *dev = mAudioHwDevs[i];
371 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700372 }
373 if (locked) mLock.unlock();
374 }
375 return NO_ERROR;
376}
377
378
379// IAudioFlinger interface
380
381
382sp<IAudioTrack> AudioFlinger::createTrack(
383 pid_t pid,
384 int streamType,
385 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700386 uint32_t format,
387 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388 int frameCount,
389 uint32_t flags,
390 const sp<IMemory>& sharedBuffer,
391 int output,
392 int *sessionId,
393 status_t *status)
394{
395 sp<PlaybackThread::Track> track;
396 sp<TrackHandle> trackHandle;
397 sp<Client> client;
398 wp<Client> wclient;
399 status_t lStatus;
400 int lSessionId;
401
Dima Zavinfce7a472011-04-19 22:30:36 -0700402 if (streamType >= AUDIO_STREAM_CNT) {
Glenn Kastend8796012011-10-28 10:31:42 -0700403 LOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 lStatus = BAD_VALUE;
405 goto Exit;
406 }
407
408 {
409 Mutex::Autolock _l(mLock);
410 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700411 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700412 if (thread == NULL) {
413 LOGE("unknown output thread");
414 lStatus = BAD_VALUE;
415 goto Exit;
416 }
417
418 wclient = mClients.valueFor(pid);
419
420 if (wclient != NULL) {
421 client = wclient.promote();
422 } else {
423 client = new Client(this, pid);
424 mClients.add(pid, client);
425 }
426
Steve Block3856b092011-10-20 11:56:00 +0100427 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700428 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700429 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700430 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
431 if (mPlaybackThreads.keyAt(i) != output) {
432 // prevent same audio session on different output threads
433 uint32_t sessions = t->hasAudioSession(*sessionId);
434 if (sessions & PlaybackThread::TRACK_SESSION) {
Glenn Kastend8796012011-10-28 10:31:42 -0700435 LOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700436 lStatus = BAD_VALUE;
437 goto Exit;
438 }
439 // check if an effect with same session ID is waiting for a track to be created
440 if (sessions & PlaybackThread::EFFECT_SESSION) {
441 effectThread = t.get();
442 }
Eric Laurentde070132010-07-13 04:45:46 -0700443 }
444 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700445 lSessionId = *sessionId;
446 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700447 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700448 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700449 if (sessionId != NULL) {
450 *sessionId = lSessionId;
451 }
452 }
Steve Block3856b092011-10-20 11:56:00 +0100453 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700454
455 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700456 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700457
458 // move effect chain to this output thread if an effect on same session was waiting
459 // for a track to be created
460 if (lStatus == NO_ERROR && effectThread != NULL) {
461 Mutex::Autolock _dl(thread->mLock);
462 Mutex::Autolock _sl(effectThread->mLock);
463 moveEffectChain_l(lSessionId, effectThread, thread, true);
464 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700465 }
466 if (lStatus == NO_ERROR) {
467 trackHandle = new TrackHandle(track);
468 } else {
469 // remove local strong reference to Client before deleting the Track so that the Client
470 // destructor is called by the TrackBase destructor with mLock held
471 client.clear();
472 track.clear();
473 }
474
475Exit:
476 if(status) {
477 *status = lStatus;
478 }
479 return trackHandle;
480}
481
482uint32_t AudioFlinger::sampleRate(int output) const
483{
484 Mutex::Autolock _l(mLock);
485 PlaybackThread *thread = checkPlaybackThread_l(output);
486 if (thread == NULL) {
487 LOGW("sampleRate() unknown thread %d", output);
488 return 0;
489 }
490 return thread->sampleRate();
491}
492
493int AudioFlinger::channelCount(int output) const
494{
495 Mutex::Autolock _l(mLock);
496 PlaybackThread *thread = checkPlaybackThread_l(output);
497 if (thread == NULL) {
498 LOGW("channelCount() unknown thread %d", output);
499 return 0;
500 }
501 return thread->channelCount();
502}
503
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700504uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700505{
506 Mutex::Autolock _l(mLock);
507 PlaybackThread *thread = checkPlaybackThread_l(output);
508 if (thread == NULL) {
509 LOGW("format() unknown thread %d", output);
510 return 0;
511 }
512 return thread->format();
513}
514
515size_t AudioFlinger::frameCount(int output) const
516{
517 Mutex::Autolock _l(mLock);
518 PlaybackThread *thread = checkPlaybackThread_l(output);
519 if (thread == NULL) {
520 LOGW("frameCount() unknown thread %d", output);
521 return 0;
522 }
523 return thread->frameCount();
524}
525
526uint32_t AudioFlinger::latency(int output) const
527{
528 Mutex::Autolock _l(mLock);
529 PlaybackThread *thread = checkPlaybackThread_l(output);
530 if (thread == NULL) {
531 LOGW("latency() unknown thread %d", output);
532 return 0;
533 }
534 return thread->latency();
535}
536
537status_t AudioFlinger::setMasterVolume(float value)
538{
Eric Laurenta1884f92011-08-23 08:25:03 -0700539 status_t ret = initCheck();
540 if (ret != NO_ERROR) {
541 return ret;
542 }
543
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 // check calling permissions
545 if (!settingsAllowed()) {
546 return PERMISSION_DENIED;
547 }
548
549 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800550 { // scope for the lock
551 AutoMutex lock(mHardwareLock);
552 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700553 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800554 value = 1.0f;
555 }
556 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700558
Eric Laurent93575202011-01-18 18:39:02 -0800559 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700560 mMasterVolume = value;
561 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
562 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
563
564 return NO_ERROR;
565}
566
567status_t AudioFlinger::setMode(int mode)
568{
Eric Laurenta1884f92011-08-23 08:25:03 -0700569 status_t ret = initCheck();
570 if (ret != NO_ERROR) {
571 return ret;
572 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573
574 // check calling permissions
575 if (!settingsAllowed()) {
576 return PERMISSION_DENIED;
577 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700578 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700579 LOGW("Illegal value: setMode(%d)", mode);
580 return BAD_VALUE;
581 }
582
583 { // scope for the lock
584 AutoMutex lock(mHardwareLock);
585 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700586 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587 mHardwareStatus = AUDIO_HW_IDLE;
588 }
589
590 if (NO_ERROR == ret) {
591 Mutex::Autolock _l(mLock);
592 mMode = mode;
593 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
594 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595 }
596
597 return ret;
598}
599
600status_t AudioFlinger::setMicMute(bool state)
601{
Eric Laurenta1884f92011-08-23 08:25:03 -0700602 status_t ret = initCheck();
603 if (ret != NO_ERROR) {
604 return ret;
605 }
606
Mathias Agopian65ab4712010-07-14 17:59:35 -0700607 // check calling permissions
608 if (!settingsAllowed()) {
609 return PERMISSION_DENIED;
610 }
611
612 AutoMutex lock(mHardwareLock);
613 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700614 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 mHardwareStatus = AUDIO_HW_IDLE;
616 return ret;
617}
618
619bool AudioFlinger::getMicMute() const
620{
Eric Laurenta1884f92011-08-23 08:25:03 -0700621 status_t ret = initCheck();
622 if (ret != NO_ERROR) {
623 return false;
624 }
625
Dima Zavinfce7a472011-04-19 22:30:36 -0700626 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700628 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700629 mHardwareStatus = AUDIO_HW_IDLE;
630 return state;
631}
632
633status_t AudioFlinger::setMasterMute(bool muted)
634{
635 // check calling permissions
636 if (!settingsAllowed()) {
637 return PERMISSION_DENIED;
638 }
639
Eric Laurent93575202011-01-18 18:39:02 -0800640 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700641 mMasterMute = muted;
642 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
643 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
644
645 return NO_ERROR;
646}
647
648float AudioFlinger::masterVolume() const
649{
650 return mMasterVolume;
651}
652
653bool AudioFlinger::masterMute() const
654{
655 return mMasterMute;
656}
657
658status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
659{
660 // check calling permissions
661 if (!settingsAllowed()) {
662 return PERMISSION_DENIED;
663 }
664
Dima Zavinfce7a472011-04-19 22:30:36 -0700665 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Glenn Kastend8796012011-10-28 10:31:42 -0700666 LOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 return BAD_VALUE;
668 }
669
670 AutoMutex lock(mLock);
671 PlaybackThread *thread = NULL;
672 if (output) {
673 thread = checkPlaybackThread_l(output);
674 if (thread == NULL) {
675 return BAD_VALUE;
676 }
677 }
678
679 mStreamTypes[stream].volume = value;
680
681 if (thread == NULL) {
682 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
683 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
684 }
685 } else {
686 thread->setStreamVolume(stream, value);
687 }
688
689 return NO_ERROR;
690}
691
692status_t AudioFlinger::setStreamMute(int stream, bool muted)
693{
694 // check calling permissions
695 if (!settingsAllowed()) {
696 return PERMISSION_DENIED;
697 }
698
Dima Zavinfce7a472011-04-19 22:30:36 -0700699 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
700 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Glenn Kastend8796012011-10-28 10:31:42 -0700701 LOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700702 return BAD_VALUE;
703 }
704
Eric Laurent93575202011-01-18 18:39:02 -0800705 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700706 mStreamTypes[stream].mute = muted;
707 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
708 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
709
710 return NO_ERROR;
711}
712
713float AudioFlinger::streamVolume(int stream, int output) const
714{
Dima Zavinfce7a472011-04-19 22:30:36 -0700715 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700716 return 0.0f;
717 }
718
719 AutoMutex lock(mLock);
720 float volume;
721 if (output) {
722 PlaybackThread *thread = checkPlaybackThread_l(output);
723 if (thread == NULL) {
724 return 0.0f;
725 }
726 volume = thread->streamVolume(stream);
727 } else {
728 volume = mStreamTypes[stream].volume;
729 }
730
731 return volume;
732}
733
734bool AudioFlinger::streamMute(int stream) const
735{
Dima Zavinfce7a472011-04-19 22:30:36 -0700736 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700737 return true;
738 }
739
740 return mStreamTypes[stream].mute;
741}
742
Mathias Agopian65ab4712010-07-14 17:59:35 -0700743status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
744{
745 status_t result;
746
Steve Block3856b092011-10-20 11:56:00 +0100747 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700748 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
749 // check calling permissions
750 if (!settingsAllowed()) {
751 return PERMISSION_DENIED;
752 }
753
Mathias Agopian65ab4712010-07-14 17:59:35 -0700754 // ioHandle == 0 means the parameters are global to the audio hardware interface
755 if (ioHandle == 0) {
756 AutoMutex lock(mHardwareLock);
757 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700758 status_t final_result = NO_ERROR;
759 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
760 audio_hw_device_t *dev = mAudioHwDevs[i];
761 result = dev->set_parameters(dev, keyValuePairs.string());
762 final_result = result ?: final_result;
763 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700765 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
766 AudioParameter param = AudioParameter(keyValuePairs);
767 String8 value;
768 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
769 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700770 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
771 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700772 for (size_t i = 0; i < mRecordThreads.size(); i++) {
773 sp<RecordThread> thread = mRecordThreads.valueAt(i);
774 RecordThread::RecordTrack *track = thread->track();
775 if (track != NULL) {
776 audio_devices_t device = (audio_devices_t)(
777 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700778 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700779 thread->setEffectSuspended(FX_IID_AEC,
780 suspend,
781 track->sessionId());
782 thread->setEffectSuspended(FX_IID_NS,
783 suspend,
784 track->sessionId());
785 }
786 }
Eric Laurentbee53372011-08-29 12:42:48 -0700787 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700788 }
789 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700790 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 }
792
793 // hold a strong ref on thread in case closeOutput() or closeInput() is called
794 // and the thread is exited once the lock is released
795 sp<ThreadBase> thread;
796 {
797 Mutex::Autolock _l(mLock);
798 thread = checkPlaybackThread_l(ioHandle);
799 if (thread == NULL) {
800 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700801 } else if (thread.get() == primaryPlaybackThread_l()) {
802 // indicate output device change to all input threads for pre processing
803 AudioParameter param = AudioParameter(keyValuePairs);
804 int value;
805 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
806 for (size_t i = 0; i < mRecordThreads.size(); i++) {
807 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
808 }
809 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 }
811 }
812 if (thread != NULL) {
813 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700814 return result;
815 }
816 return BAD_VALUE;
817}
818
819String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
820{
Steve Block3856b092011-10-20 11:56:00 +0100821// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
823
824 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700825 String8 out_s8;
826
Dima Zavin799a70e2011-04-18 16:57:27 -0700827 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
828 audio_hw_device_t *dev = mAudioHwDevs[i];
829 char *s = dev->get_parameters(dev, keys.string());
830 out_s8 += String8(s);
831 free(s);
832 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700833 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834 }
835
836 Mutex::Autolock _l(mLock);
837
838 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
839 if (playbackThread != NULL) {
840 return playbackThread->getParameters(keys);
841 }
842 RecordThread *recordThread = checkRecordThread_l(ioHandle);
843 if (recordThread != NULL) {
844 return recordThread->getParameters(keys);
845 }
846 return String8("");
847}
848
849size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
850{
Eric Laurenta1884f92011-08-23 08:25:03 -0700851 status_t ret = initCheck();
852 if (ret != NO_ERROR) {
853 return 0;
854 }
855
Dima Zavin799a70e2011-04-18 16:57:27 -0700856 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857}
858
859unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
860{
861 if (ioHandle == 0) {
862 return 0;
863 }
864
865 Mutex::Autolock _l(mLock);
866
867 RecordThread *recordThread = checkRecordThread_l(ioHandle);
868 if (recordThread != NULL) {
869 return recordThread->getInputFramesLost();
870 }
871 return 0;
872}
873
874status_t AudioFlinger::setVoiceVolume(float value)
875{
Eric Laurenta1884f92011-08-23 08:25:03 -0700876 status_t ret = initCheck();
877 if (ret != NO_ERROR) {
878 return ret;
879 }
880
Mathias Agopian65ab4712010-07-14 17:59:35 -0700881 // check calling permissions
882 if (!settingsAllowed()) {
883 return PERMISSION_DENIED;
884 }
885
886 AutoMutex lock(mHardwareLock);
887 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700888 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 mHardwareStatus = AUDIO_HW_IDLE;
890
891 return ret;
892}
893
894status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
895{
896 status_t status;
897
898 Mutex::Autolock _l(mLock);
899
900 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
901 if (playbackThread != NULL) {
902 return playbackThread->getRenderPosition(halFrames, dspFrames);
903 }
904
905 return BAD_VALUE;
906}
907
908void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
909{
910
911 Mutex::Autolock _l(mLock);
912
913 int pid = IPCThreadState::self()->getCallingPid();
914 if (mNotificationClients.indexOfKey(pid) < 0) {
915 sp<NotificationClient> notificationClient = new NotificationClient(this,
916 client,
917 pid);
Steve Block3856b092011-10-20 11:56:00 +0100918 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700919
920 mNotificationClients.add(pid, notificationClient);
921
922 sp<IBinder> binder = client->asBinder();
923 binder->linkToDeath(notificationClient);
924
925 // the config change is always sent from playback or record threads to avoid deadlock
926 // with AudioSystem::gLock
927 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
928 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
929 }
930
931 for (size_t i = 0; i < mRecordThreads.size(); i++) {
932 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
933 }
934 }
935}
936
937void AudioFlinger::removeNotificationClient(pid_t pid)
938{
939 Mutex::Autolock _l(mLock);
940
941 int index = mNotificationClients.indexOfKey(pid);
942 if (index >= 0) {
943 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100944 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945 mNotificationClients.removeItem(pid);
946 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700947
Steve Block3856b092011-10-20 11:56:00 +0100948 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700949 int num = mAudioSessionRefs.size();
950 bool removed = false;
951 for (int i = 0; i< num; i++) {
952 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100953 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700954 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100955 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700956 mAudioSessionRefs.removeAt(i);
957 delete ref;
958 removed = true;
959 i--;
960 num--;
961 }
962 }
963 if (removed) {
964 purgeStaleEffects_l();
965 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700966}
967
968// audioConfigChanged_l() must be called with AudioFlinger::mLock held
969void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
970{
971 size_t size = mNotificationClients.size();
972 for (size_t i = 0; i < size; i++) {
973 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
974 }
975}
976
977// removeClient_l() must be called with AudioFlinger::mLock held
978void AudioFlinger::removeClient_l(pid_t pid)
979{
Steve Block3856b092011-10-20 11:56:00 +0100980 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700981 mClients.removeItem(pid);
982}
983
984
985// ----------------------------------------------------------------------------
986
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700987AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700988 : Thread(false),
989 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700990 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
991 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700992{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700993 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700994}
995
996AudioFlinger::ThreadBase::~ThreadBase()
997{
998 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700999 // do not lock the mutex in destructor
1000 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001001 if (mPowerManager != 0) {
1002 sp<IBinder> binder = mPowerManager->asBinder();
1003 binder->unlinkToDeath(mDeathRecipient);
1004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001005}
1006
1007void AudioFlinger::ThreadBase::exit()
1008{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001009 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001010 // destroyed in the middle of requestExitAndWait()
1011 sp <ThreadBase> strongMe = this;
1012
Steve Block3856b092011-10-20 11:56:00 +01001013 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001014 {
1015 AutoMutex lock(&mLock);
1016 mExiting = true;
1017 requestExit();
1018 mWaitWorkCV.signal();
1019 }
1020 requestExitAndWait();
1021}
1022
1023uint32_t AudioFlinger::ThreadBase::sampleRate() const
1024{
1025 return mSampleRate;
1026}
1027
1028int AudioFlinger::ThreadBase::channelCount() const
1029{
1030 return (int)mChannelCount;
1031}
1032
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001033uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001034{
1035 return mFormat;
1036}
1037
1038size_t AudioFlinger::ThreadBase::frameCount() const
1039{
1040 return mFrameCount;
1041}
1042
1043status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1044{
1045 status_t status;
1046
Steve Block3856b092011-10-20 11:56:00 +01001047 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048 Mutex::Autolock _l(mLock);
1049
1050 mNewParameters.add(keyValuePairs);
1051 mWaitWorkCV.signal();
1052 // wait condition with timeout in case the thread loop has exited
1053 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001054 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001055 status = mParamStatus;
1056 mWaitWorkCV.signal();
1057 } else {
1058 status = TIMED_OUT;
1059 }
1060 return status;
1061}
1062
1063void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1064{
1065 Mutex::Autolock _l(mLock);
1066 sendConfigEvent_l(event, param);
1067}
1068
1069// sendConfigEvent_l() must be called with ThreadBase::mLock held
1070void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1071{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001072 ConfigEvent configEvent;
1073 configEvent.mEvent = event;
1074 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001075 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001076 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001077 mWaitWorkCV.signal();
1078}
1079
1080void AudioFlinger::ThreadBase::processConfigEvents()
1081{
1082 mLock.lock();
1083 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001084 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001085 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001086 mConfigEvents.removeAt(0);
1087 // release mLock before locking AudioFlinger mLock: lock order is always
1088 // AudioFlinger then ThreadBase to avoid cross deadlock
1089 mLock.unlock();
1090 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001091 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001093 mLock.lock();
1094 }
1095 mLock.unlock();
1096}
1097
1098status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1099{
1100 const size_t SIZE = 256;
1101 char buffer[SIZE];
1102 String8 result;
1103
1104 bool locked = tryLock(mLock);
1105 if (!locked) {
1106 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1107 write(fd, buffer, strlen(buffer));
1108 }
1109
1110 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1113 result.append(buffer);
1114 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1115 result.append(buffer);
1116 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1117 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001118 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1119 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001120 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1123 result.append(buffer);
1124
1125 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1126 result.append(buffer);
1127 result.append(" Index Command");
1128 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1129 snprintf(buffer, SIZE, "\n %02d ", i);
1130 result.append(buffer);
1131 result.append(mNewParameters[i]);
1132 }
1133
1134 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, " Index event param\n");
1137 result.append(buffer);
1138 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001139 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001140 result.append(buffer);
1141 }
1142 result.append("\n");
1143
1144 write(fd, result.string(), result.size());
1145
1146 if (locked) {
1147 mLock.unlock();
1148 }
1149 return NO_ERROR;
1150}
1151
Eric Laurent1d2bff02011-07-24 17:49:51 -07001152status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1153{
1154 const size_t SIZE = 256;
1155 char buffer[SIZE];
1156 String8 result;
1157
1158 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1159 write(fd, buffer, strlen(buffer));
1160
1161 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1162 sp<EffectChain> chain = mEffectChains[i];
1163 if (chain != 0) {
1164 chain->dump(fd, args);
1165 }
1166 }
1167 return NO_ERROR;
1168}
1169
Eric Laurentfeb0db62011-07-22 09:04:31 -07001170void AudioFlinger::ThreadBase::acquireWakeLock()
1171{
1172 Mutex::Autolock _l(mLock);
1173 acquireWakeLock_l();
1174}
1175
1176void AudioFlinger::ThreadBase::acquireWakeLock_l()
1177{
1178 if (mPowerManager == 0) {
1179 // use checkService() to avoid blocking if power service is not up yet
1180 sp<IBinder> binder =
1181 defaultServiceManager()->checkService(String16("power"));
1182 if (binder == 0) {
1183 LOGW("Thread %s cannot connect to the power manager service", mName);
1184 } else {
1185 mPowerManager = interface_cast<IPowerManager>(binder);
1186 binder->linkToDeath(mDeathRecipient);
1187 }
1188 }
1189 if (mPowerManager != 0) {
1190 sp<IBinder> binder = new BBinder();
1191 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1192 binder,
1193 String16(mName));
1194 if (status == NO_ERROR) {
1195 mWakeLockToken = binder;
1196 }
Steve Block3856b092011-10-20 11:56:00 +01001197 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001198 }
1199}
1200
1201void AudioFlinger::ThreadBase::releaseWakeLock()
1202{
1203 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001204 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001205}
1206
1207void AudioFlinger::ThreadBase::releaseWakeLock_l()
1208{
1209 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001210 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001211 if (mPowerManager != 0) {
1212 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1213 }
1214 mWakeLockToken.clear();
1215 }
1216}
1217
1218void AudioFlinger::ThreadBase::clearPowerManager()
1219{
1220 Mutex::Autolock _l(mLock);
1221 releaseWakeLock_l();
1222 mPowerManager.clear();
1223}
1224
1225void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1226{
1227 sp<ThreadBase> thread = mThread.promote();
1228 if (thread != 0) {
1229 thread->clearPowerManager();
1230 }
1231 LOGW("power manager service died !!!");
1232}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001233
Eric Laurent59255e42011-07-27 19:49:51 -07001234void AudioFlinger::ThreadBase::setEffectSuspended(
1235 const effect_uuid_t *type, bool suspend, int sessionId)
1236{
1237 Mutex::Autolock _l(mLock);
1238 setEffectSuspended_l(type, suspend, sessionId);
1239}
1240
1241void AudioFlinger::ThreadBase::setEffectSuspended_l(
1242 const effect_uuid_t *type, bool suspend, int sessionId)
1243{
1244 sp<EffectChain> chain;
1245 chain = getEffectChain_l(sessionId);
1246 if (chain != 0) {
1247 if (type != NULL) {
1248 chain->setEffectSuspended_l(type, suspend);
1249 } else {
1250 chain->setEffectSuspendedAll_l(suspend);
1251 }
1252 }
1253
1254 updateSuspendedSessions_l(type, suspend, sessionId);
1255}
1256
1257void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1258{
1259 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1260 if (index < 0) {
1261 return;
1262 }
1263
1264 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1265 mSuspendedSessions.editValueAt(index);
1266
1267 for (size_t i = 0; i < sessionEffects.size(); i++) {
1268 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1269 for (int j = 0; j < desc->mRefCount; j++) {
1270 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1271 chain->setEffectSuspendedAll_l(true);
1272 } else {
Steve Block3856b092011-10-20 11:56:00 +01001273 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001274 desc->mType.timeLow);
1275 chain->setEffectSuspended_l(&desc->mType, true);
1276 }
1277 }
1278 }
1279}
1280
Eric Laurent59255e42011-07-27 19:49:51 -07001281void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1282 bool suspend,
1283 int sessionId)
1284{
1285 int index = mSuspendedSessions.indexOfKey(sessionId);
1286
1287 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1288
1289 if (suspend) {
1290 if (index >= 0) {
1291 sessionEffects = mSuspendedSessions.editValueAt(index);
1292 } else {
1293 mSuspendedSessions.add(sessionId, sessionEffects);
1294 }
1295 } else {
1296 if (index < 0) {
1297 return;
1298 }
1299 sessionEffects = mSuspendedSessions.editValueAt(index);
1300 }
1301
1302
1303 int key = EffectChain::kKeyForSuspendAll;
1304 if (type != NULL) {
1305 key = type->timeLow;
1306 }
1307 index = sessionEffects.indexOfKey(key);
1308
1309 sp <SuspendedSessionDesc> desc;
1310 if (suspend) {
1311 if (index >= 0) {
1312 desc = sessionEffects.valueAt(index);
1313 } else {
1314 desc = new SuspendedSessionDesc();
1315 if (type != NULL) {
1316 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1317 }
1318 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001319 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001320 }
1321 desc->mRefCount++;
1322 } else {
1323 if (index < 0) {
1324 return;
1325 }
1326 desc = sessionEffects.valueAt(index);
1327 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001328 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001329 sessionEffects.removeItemsAt(index);
1330 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001331 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001332 sessionId);
1333 mSuspendedSessions.removeItem(sessionId);
1334 }
1335 }
1336 }
1337 if (!sessionEffects.isEmpty()) {
1338 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1339 }
1340}
1341
1342void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1343 bool enabled,
1344 int sessionId)
1345{
1346 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001347 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1348}
Eric Laurent59255e42011-07-27 19:49:51 -07001349
Eric Laurenta85a74a2011-10-19 11:44:54 -07001350void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1351 bool enabled,
1352 int sessionId)
1353{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001354 if (mType != RECORD) {
1355 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1356 // another session. This gives the priority to well behaved effect control panels
1357 // and applications not using global effects.
1358 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1359 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1360 }
1361 }
Eric Laurent59255e42011-07-27 19:49:51 -07001362
1363 sp<EffectChain> chain = getEffectChain_l(sessionId);
1364 if (chain != 0) {
1365 chain->checkSuspendOnEffectEnabled(effect, enabled);
1366 }
1367}
1368
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369// ----------------------------------------------------------------------------
1370
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001371AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1372 AudioStreamOut* output,
1373 int id,
1374 uint32_t device)
1375 : ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001376 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001377 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001379 snprintf(mName, kNameLength, "AudioOut_%d", id);
1380
Mathias Agopian65ab4712010-07-14 17:59:35 -07001381 readOutputParameters();
1382
1383 mMasterVolume = mAudioFlinger->masterVolume();
1384 mMasterMute = mAudioFlinger->masterMute();
1385
Dima Zavinfce7a472011-04-19 22:30:36 -07001386 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1388 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001389 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001390 }
1391}
1392
1393AudioFlinger::PlaybackThread::~PlaybackThread()
1394{
1395 delete [] mMixBuffer;
1396}
1397
1398status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1399{
1400 dumpInternals(fd, args);
1401 dumpTracks(fd, args);
1402 dumpEffectChains(fd, args);
1403 return NO_ERROR;
1404}
1405
1406status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1407{
1408 const size_t SIZE = 256;
1409 char buffer[SIZE];
1410 String8 result;
1411
1412 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1413 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001414 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 -07001415 for (size_t i = 0; i < mTracks.size(); ++i) {
1416 sp<Track> track = mTracks[i];
1417 if (track != 0) {
1418 track->dump(buffer, SIZE);
1419 result.append(buffer);
1420 }
1421 }
1422
1423 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1424 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001425 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 -07001426 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1427 wp<Track> wTrack = mActiveTracks[i];
1428 if (wTrack != 0) {
1429 sp<Track> track = wTrack.promote();
1430 if (track != 0) {
1431 track->dump(buffer, SIZE);
1432 result.append(buffer);
1433 }
1434 }
1435 }
1436 write(fd, result.string(), result.size());
1437 return NO_ERROR;
1438}
1439
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1441{
1442 const size_t SIZE = 256;
1443 char buffer[SIZE];
1444 String8 result;
1445
1446 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1447 result.append(buffer);
1448 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1449 result.append(buffer);
1450 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1451 result.append(buffer);
1452 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1453 result.append(buffer);
1454 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1455 result.append(buffer);
1456 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1457 result.append(buffer);
1458 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1459 result.append(buffer);
1460 write(fd, result.string(), result.size());
1461
1462 dumpBase(fd, args);
1463
1464 return NO_ERROR;
1465}
1466
1467// Thread virtuals
1468status_t AudioFlinger::PlaybackThread::readyToRun()
1469{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001470 status_t status = initCheck();
1471 if (status == NO_ERROR) {
1472 LOGI("AudioFlinger's thread %p ready to run", this);
1473 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001476 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477}
1478
1479void AudioFlinger::PlaybackThread::onFirstRef()
1480{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001481 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482}
1483
1484// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1485sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1486 const sp<AudioFlinger::Client>& client,
1487 int streamType,
1488 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001489 uint32_t format,
1490 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001491 int frameCount,
1492 const sp<IMemory>& sharedBuffer,
1493 int sessionId,
1494 status_t *status)
1495{
1496 sp<Track> track;
1497 status_t lStatus;
1498
1499 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001500 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1501 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1502 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1503 "for output %p with format %d",
1504 sampleRate, format, channelMask, mOutput, mFormat);
1505 lStatus = BAD_VALUE;
1506 goto Exit;
1507 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001508 }
1509 } else {
1510 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1511 if (sampleRate > mSampleRate*2) {
1512 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1513 lStatus = BAD_VALUE;
1514 goto Exit;
1515 }
1516 }
1517
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001518 lStatus = initCheck();
1519 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 goto Exit;
1522 }
1523
1524 { // scope for mLock
1525 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001526
1527 // all tracks in same audio session must share the same routing strategy otherwise
1528 // conflicts will happen when tracks are moved from one output to another by audio policy
1529 // manager
1530 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001531 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001532 for (size_t i = 0; i < mTracks.size(); ++i) {
1533 sp<Track> t = mTracks[i];
1534 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001535 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1536 if (sessionId == t->sessionId() && strategy != actual) {
1537 LOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1538 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001539 lStatus = BAD_VALUE;
1540 goto Exit;
1541 }
1542 }
1543 }
1544
Mathias Agopian65ab4712010-07-14 17:59:35 -07001545 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001546 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547 if (track->getCblk() == NULL || track->name() < 0) {
1548 lStatus = NO_MEMORY;
1549 goto Exit;
1550 }
1551 mTracks.add(track);
1552
1553 sp<EffectChain> chain = getEffectChain_l(sessionId);
1554 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001555 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001556 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001557 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001558 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001559 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001560
1561 // invalidate track immediately if the stream type was moved to another thread since
1562 // createTrack() was called by the client process.
1563 if (!mStreamTypes[streamType].valid) {
1564 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1565 this, streamType);
1566 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
1569 lStatus = NO_ERROR;
1570
1571Exit:
1572 if(status) {
1573 *status = lStatus;
1574 }
1575 return track;
1576}
1577
1578uint32_t AudioFlinger::PlaybackThread::latency() const
1579{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001580 Mutex::Autolock _l(mLock);
1581 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001582 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001583 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001584 return 0;
1585 }
1586}
1587
1588status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1589{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 mMasterVolume = value;
1591 return NO_ERROR;
1592}
1593
1594status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1595{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001596 mMasterMute = muted;
1597 return NO_ERROR;
1598}
1599
1600float AudioFlinger::PlaybackThread::masterVolume() const
1601{
1602 return mMasterVolume;
1603}
1604
1605bool AudioFlinger::PlaybackThread::masterMute() const
1606{
1607 return mMasterMute;
1608}
1609
1610status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1611{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 mStreamTypes[stream].volume = value;
1613 return NO_ERROR;
1614}
1615
1616status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1617{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001618 mStreamTypes[stream].mute = muted;
1619 return NO_ERROR;
1620}
1621
1622float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1623{
1624 return mStreamTypes[stream].volume;
1625}
1626
1627bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1628{
1629 return mStreamTypes[stream].mute;
1630}
1631
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632// addTrack_l() must be called with ThreadBase::mLock held
1633status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1634{
1635 status_t status = ALREADY_EXISTS;
1636
1637 // set retry count for buffer fill
1638 track->mRetryCount = kMaxTrackStartupRetries;
1639 if (mActiveTracks.indexOf(track) < 0) {
1640 // the track is newly added, make sure it fills up all its
1641 // buffers before playing. This is to ensure the client will
1642 // effectively get the latency it requested.
1643 track->mFillingUpStatus = Track::FS_FILLING;
1644 track->mResetDone = false;
1645 mActiveTracks.add(track);
1646 if (track->mainBuffer() != mMixBuffer) {
1647 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1648 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001649 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001650 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001651 }
1652 }
1653
1654 status = NO_ERROR;
1655 }
1656
Steve Block3856b092011-10-20 11:56:00 +01001657 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001658 mWaitWorkCV.broadcast();
1659
1660 return status;
1661}
1662
1663// destroyTrack_l() must be called with ThreadBase::mLock held
1664void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1665{
1666 track->mState = TrackBase::TERMINATED;
1667 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001668 removeTrack_l(track);
1669 }
1670}
1671
1672void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1673{
1674 mTracks.remove(track);
1675 deleteTrackName_l(track->name());
1676 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1677 if (chain != 0) {
1678 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001679 }
1680}
1681
1682String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1683{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001684 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001685 char *s;
1686
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001687 Mutex::Autolock _l(mLock);
1688 if (initCheck() != NO_ERROR) {
1689 return out_s8;
1690 }
1691
Dima Zavin799a70e2011-04-18 16:57:27 -07001692 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001693 out_s8 = String8(s);
1694 free(s);
1695 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001696}
1697
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001698// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001699void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1700 AudioSystem::OutputDescriptor desc;
1701 void *param2 = 0;
1702
Steve Block3856b092011-10-20 11:56:00 +01001703 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704
1705 switch (event) {
1706 case AudioSystem::OUTPUT_OPENED:
1707 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001708 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001709 desc.samplingRate = mSampleRate;
1710 desc.format = mFormat;
1711 desc.frameCount = mFrameCount;
1712 desc.latency = latency();
1713 param2 = &desc;
1714 break;
1715
1716 case AudioSystem::STREAM_CONFIG_CHANGED:
1717 param2 = &param;
1718 case AudioSystem::OUTPUT_CLOSED:
1719 default:
1720 break;
1721 }
1722 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1723}
1724
1725void AudioFlinger::PlaybackThread::readOutputParameters()
1726{
Dima Zavin799a70e2011-04-18 16:57:27 -07001727 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001728 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1729 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001730 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1731 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1732 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001733
1734 // FIXME - Current mixer implementation only supports stereo output: Always
1735 // Allocate a stereo buffer even if HW output is mono.
1736 if (mMixBuffer != NULL) delete[] mMixBuffer;
1737 mMixBuffer = new int16_t[mFrameCount * 2];
1738 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1739
Eric Laurentde070132010-07-13 04:45:46 -07001740 // force reconfiguration of effect chains and engines to take new buffer size and audio
1741 // parameters into account
1742 // Note that mLock is not held when readOutputParameters() is called from the constructor
1743 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1744 // matter.
1745 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1746 Vector< sp<EffectChain> > effectChains = mEffectChains;
1747 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001748 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750}
1751
1752status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1753{
1754 if (halFrames == 0 || dspFrames == 0) {
1755 return BAD_VALUE;
1756 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001757 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001758 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 return INVALID_OPERATION;
1760 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001761 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762
Dima Zavin799a70e2011-04-18 16:57:27 -07001763 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001764}
1765
Eric Laurent39e94f82010-07-28 01:32:47 -07001766uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001767{
1768 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001769 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001771 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 }
1773
1774 for (size_t i = 0; i < mTracks.size(); ++i) {
1775 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001776 if (sessionId == track->sessionId() &&
1777 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001778 result |= TRACK_SESSION;
1779 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001780 }
1781 }
1782
Eric Laurent39e94f82010-07-28 01:32:47 -07001783 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001784}
1785
Eric Laurentde070132010-07-13 04:45:46 -07001786uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1787{
Dima Zavinfce7a472011-04-19 22:30:36 -07001788 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001789 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001790 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1791 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001792 }
1793 for (size_t i = 0; i < mTracks.size(); i++) {
1794 sp<Track> track = mTracks[i];
1795 if (sessionId == track->sessionId() &&
1796 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001797 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001798 }
1799 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001800 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001801}
1802
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001804AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1805{
1806 Mutex::Autolock _l(mLock);
1807 return mOutput;
1808}
1809
1810AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1811{
1812 Mutex::Autolock _l(mLock);
1813 AudioStreamOut *output = mOutput;
1814 mOutput = NULL;
1815 return output;
1816}
1817
1818// this method must always be called either with ThreadBase mLock held or inside the thread loop
1819audio_stream_t* AudioFlinger::PlaybackThread::stream()
1820{
1821 if (mOutput == NULL) {
1822 return NULL;
1823 }
1824 return &mOutput->stream->common;
1825}
1826
Eric Laurent162b40b2011-12-05 09:47:19 -08001827uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1828{
1829 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1830 // decoding and transfer time. So sleeping for half of the latency would likely cause
1831 // underruns
1832 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1833 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1834 } else {
1835 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1836 }
1837}
1838
Mathias Agopian65ab4712010-07-14 17:59:35 -07001839// ----------------------------------------------------------------------------
1840
Dima Zavin799a70e2011-04-18 16:57:27 -07001841AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001842 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001843 mAudioMixer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001845 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001846 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1847
1848 // FIXME - Current mixer implementation only supports stereo output
1849 if (mChannelCount == 1) {
1850 LOGE("Invalid audio hardware channel count");
1851 }
1852}
1853
1854AudioFlinger::MixerThread::~MixerThread()
1855{
1856 delete mAudioMixer;
1857}
1858
1859bool AudioFlinger::MixerThread::threadLoop()
1860{
1861 Vector< sp<Track> > tracksToRemove;
1862 uint32_t mixerStatus = MIXER_IDLE;
1863 nsecs_t standbyTime = systemTime();
1864 size_t mixBufferSize = mFrameCount * mFrameSize;
1865 // FIXME: Relaxed timing because of a certain device that can't meet latency
1866 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001867 // increase threshold again due to low power audio mode. The way this warning threshold is
1868 // calculated and its usefulness should be reconsidered anyway.
1869 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001870 nsecs_t lastWarning = 0;
1871 bool longStandbyExit = false;
1872 uint32_t activeSleepTime = activeSleepTimeUs();
1873 uint32_t idleSleepTime = idleSleepTimeUs();
1874 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001875 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001877#ifdef DEBUG_CPU_USAGE
1878 ThreadCpuUsage cpu;
1879 const CentralTendencyStatistics& stats = cpu.statistics();
1880#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001881
Eric Laurentfeb0db62011-07-22 09:04:31 -07001882 acquireWakeLock();
1883
Mathias Agopian65ab4712010-07-14 17:59:35 -07001884 while (!exitPending())
1885 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001886#ifdef DEBUG_CPU_USAGE
1887 cpu.sampleAndEnable();
1888 unsigned n = stats.n();
1889 // cpu.elapsed() is expensive, so don't call it every loop
1890 if ((n & 127) == 1) {
1891 long long elapsed = cpu.elapsed();
1892 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1893 double perLoop = elapsed / (double) n;
1894 double perLoop100 = perLoop * 0.01;
1895 double mean = stats.mean();
1896 double stddev = stats.stddev();
1897 double minimum = stats.minimum();
1898 double maximum = stats.maximum();
1899 cpu.resetStatistics();
1900 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",
1901 elapsed * .000000001, n, perLoop * .000001,
1902 mean * .001,
1903 stddev * .001,
1904 minimum * .001,
1905 maximum * .001,
1906 mean / perLoop100,
1907 stddev / perLoop100,
1908 minimum / perLoop100,
1909 maximum / perLoop100);
1910 }
1911 }
1912#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001913 processConfigEvents();
1914
1915 mixerStatus = MIXER_IDLE;
1916 { // scope for mLock
1917
1918 Mutex::Autolock _l(mLock);
1919
1920 if (checkForNewParameters_l()) {
1921 mixBufferSize = mFrameCount * mFrameSize;
1922 // FIXME: Relaxed timing because of a certain device that can't meet latency
1923 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001924 // increase threshold again due to low power audio mode. The way this warning
1925 // threshold is calculated and its usefulness should be reconsidered anyway.
1926 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 activeSleepTime = activeSleepTimeUs();
1928 idleSleepTime = idleSleepTimeUs();
1929 }
1930
1931 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1932
1933 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08001934 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1935 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001936 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001937 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001938 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001939 mStandby = true;
1940 mBytesWritten = 0;
1941 }
1942
1943 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1944 // we're about to wait, flush the binder command buffer
1945 IPCThreadState::self()->flushCommands();
1946
1947 if (exitPending()) break;
1948
Eric Laurentfeb0db62011-07-22 09:04:31 -07001949 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001950 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001951 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001952 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001953 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001954 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955
1956 if (mMasterMute == false) {
1957 char value[PROPERTY_VALUE_MAX];
1958 property_get("ro.audio.silent", value, "0");
1959 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00001960 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001961 setMasterMute(true);
1962 }
1963 }
1964
1965 standbyTime = systemTime() + kStandbyTimeInNsecs;
1966 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001967 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 continue;
1969 }
1970 }
1971
1972 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1973
1974 // prevent any changes in effect chain list and in each effect chain
1975 // during mixing and effect process as the audio buffers could be deleted
1976 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001977 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001978 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979
Glenn Kastenf6b16782011-12-15 09:51:17 -08001980 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 // mix buffers...
1982 mAudioMixer->process();
1983 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001984 // increase sleep time progressively when application underrun condition clears
1985 if (sleepTimeShift > 0) {
1986 sleepTimeShift--;
1987 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 standbyTime = systemTime() + kStandbyTimeInNsecs;
1989 //TODO: delay standby when effects have a tail
1990 } else {
1991 // If no tracks are ready, sleep once for the duration of an output
1992 // buffer size, then write 0s to the output
1993 if (sleepTime == 0) {
1994 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001995 sleepTime = activeSleepTime >> sleepTimeShift;
1996 if (sleepTime < kMinThreadSleepTimeUs) {
1997 sleepTime = kMinThreadSleepTimeUs;
1998 }
1999 // reduce sleep time in case of consecutive application underruns to avoid
2000 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2001 // duration we would end up writing less data than needed by the audio HAL if
2002 // the condition persists.
2003 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2004 sleepTimeShift++;
2005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 } else {
2007 sleepTime = idleSleepTime;
2008 }
2009 } else if (mBytesWritten != 0 ||
2010 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2011 memset (mMixBuffer, 0, mixBufferSize);
2012 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002013 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002014 }
2015 // TODO add standby time extension fct of effect tail
2016 }
2017
2018 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002019 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002020 }
2021 // sleepTime == 0 means we must write to audio hardware
2022 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002023 for (size_t i = 0; i < effectChains.size(); i ++) {
2024 effectChains[i]->process_l();
2025 }
2026 // enable changes in effect chain
2027 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002028 mLastWriteTime = systemTime();
2029 mInWrite = true;
2030 mBytesWritten += mixBufferSize;
2031
Dima Zavin799a70e2011-04-18 16:57:27 -07002032 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2034 mNumWrites++;
2035 mInWrite = false;
2036 nsecs_t now = systemTime();
2037 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002038 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002039 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002040 if ((now - lastWarning) > kWarningThrottleNs) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002041 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2042 ns2ms(delta), mNumDelayedWrites, this);
2043 lastWarning = now;
2044 }
2045 if (mStandby) {
2046 longStandbyExit = true;
2047 }
2048 }
2049 mStandby = false;
2050 } else {
2051 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002052 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002053 usleep(sleepTime);
2054 }
2055
2056 // finally let go of all our tracks, without the lock held
2057 // since we can't guarantee the destructors won't acquire that
2058 // same lock.
2059 tracksToRemove.clear();
2060
2061 // Effect chains will be actually deleted here if they were removed from
2062 // mEffectChains list during mixing or effects processing
2063 effectChains.clear();
2064 }
2065
2066 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002067 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002068 }
2069
Eric Laurentfeb0db62011-07-22 09:04:31 -07002070 releaseWakeLock();
2071
Steve Block3856b092011-10-20 11:56:00 +01002072 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002073 return false;
2074}
2075
2076// prepareTracks_l() must be called with ThreadBase::mLock held
2077uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2078{
2079
2080 uint32_t mixerStatus = MIXER_IDLE;
2081 // find out which tracks need to be processed
2082 size_t count = activeTracks.size();
2083 size_t mixedTracks = 0;
2084 size_t tracksWithEffect = 0;
2085
2086 float masterVolume = mMasterVolume;
2087 bool masterMute = mMasterMute;
2088
Eric Laurent571d49c2010-08-11 05:20:11 -07002089 if (masterMute) {
2090 masterVolume = 0;
2091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002092 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002093 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002094 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002095 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002096 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002097 masterVolume = (float)((v + (1 << 23)) >> 24);
2098 chain.clear();
2099 }
2100
2101 for (size_t i=0 ; i<count ; i++) {
2102 sp<Track> t = activeTracks[i].promote();
2103 if (t == 0) continue;
2104
2105 Track* const track = t.get();
2106 audio_track_cblk_t* cblk = track->cblk();
2107
2108 // The first time a track is added we wait
2109 // for all its buffers to be filled before processing it
2110 mAudioMixer->setActiveTrack(track->name());
Eric Laurenta47b69c2011-11-08 18:10:16 -08002111 // make sure that we have enough frames to mix one full buffer.
2112 // enforce this condition only once to enable draining the buffer in case the client
2113 // app does not call stop() and relies on underrun to stop:
2114 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2115 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002116 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002117 if (!track->isStopped() && !track->isPausing() &&
2118 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002119 if (t->sampleRate() == (int)mSampleRate) {
2120 minFrames = mFrameCount;
2121 } else {
Eric Laurent071ccd52011-12-22 16:08:41 -08002122 // +1 for rounding and +1 for additional sample needed for interpolation
2123 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1 + 1;
2124 // add frames already consumed but not yet released by the resampler
2125 // because cblk->framesReady() will include these frames
2126 minFrames += mAudioMixer->getUnreleasedFrames(track->name());
2127 // the minimum track buffer size is normally twice the number of frames necessary
2128 // to fill one buffer and the resampler should not leave more than one buffer worth
2129 // of unreleased frames after each pass, but just in case...
2130 LOG_ASSERT(minFrames <= cblk->frameCount);
Eric Laurent3dbe3202011-11-03 12:16:05 -07002131 }
2132 }
2133 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002134 !track->isPaused() && !track->isTerminated())
2135 {
Steve Block3856b092011-10-20 11:56:00 +01002136 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002137
2138 mixedTracks++;
2139
2140 // track->mainBuffer() != mMixBuffer means there is an effect chain
2141 // connected to the track
2142 chain.clear();
2143 if (track->mainBuffer() != mMixBuffer) {
2144 chain = getEffectChain_l(track->sessionId());
2145 // Delegate volume control to effect in track effect chain if needed
2146 if (chain != 0) {
2147 tracksWithEffect++;
2148 } else {
2149 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2150 track->name(), track->sessionId());
2151 }
2152 }
2153
2154
2155 int param = AudioMixer::VOLUME;
2156 if (track->mFillingUpStatus == Track::FS_FILLED) {
2157 // no ramp for the first volume setting
2158 track->mFillingUpStatus = Track::FS_ACTIVE;
2159 if (track->mState == TrackBase::RESUMING) {
2160 track->mState = TrackBase::ACTIVE;
2161 param = AudioMixer::RAMP_VOLUME;
2162 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002163 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 } else if (cblk->server != 0) {
2165 // If the track is stopped before the first frame was mixed,
2166 // do not apply ramp
2167 param = AudioMixer::RAMP_VOLUME;
2168 }
2169
2170 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002171 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002172 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002173 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002174 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002175 if (track->isPausing()) {
2176 track->setPaused();
2177 }
2178 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002179
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 // read original volumes with volume control
2181 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002182 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002183 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2184 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185
Eric Laurente0aed6d2010-09-10 17:44:44 -07002186 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002188 // Delegate volume control to effect in track effect chain if needed
2189 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2190 // Do not ramp volume if volume is controlled by effect
2191 param = AudioMixer::VOLUME;
2192 track->mHasVolumeController = true;
2193 } else {
2194 // force no volume ramp when volume controller was just disabled or removed
2195 // from effect chain to avoid volume spike
2196 if (track->mHasVolumeController) {
2197 param = AudioMixer::VOLUME;
2198 }
2199 track->mHasVolumeController = false;
2200 }
2201
2202 // Convert volumes from 8.24 to 4.12 format
2203 int16_t left, right, aux;
2204 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2205 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2206 left = int16_t(v_clamped);
2207 v_clamped = (vr + (1 << 11)) >> 12;
2208 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2209 right = int16_t(v_clamped);
2210
2211 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2212 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213
Mathias Agopian65ab4712010-07-14 17:59:35 -07002214 // XXX: these things DON'T need to be done each time
2215 mAudioMixer->setBufferProvider(track);
Glenn Kasten1c48c3c2011-12-15 14:54:01 -08002216 mAudioMixer->enable();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217
2218 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2219 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2220 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2221 mAudioMixer->setParameter(
2222 AudioMixer::TRACK,
2223 AudioMixer::FORMAT, (void *)track->format());
2224 mAudioMixer->setParameter(
2225 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002226 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002227 mAudioMixer->setParameter(
2228 AudioMixer::RESAMPLE,
2229 AudioMixer::SAMPLE_RATE,
2230 (void *)(cblk->sampleRate));
2231 mAudioMixer->setParameter(
2232 AudioMixer::TRACK,
2233 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2234 mAudioMixer->setParameter(
2235 AudioMixer::TRACK,
2236 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2237
2238 // reset retry count
2239 track->mRetryCount = kMaxTrackRetries;
2240 mixerStatus = MIXER_TRACKS_READY;
2241 } else {
Steve Block3856b092011-10-20 11:56:00 +01002242 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 if (track->isStopped()) {
2244 track->reset();
2245 }
2246 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2247 // We have consumed all the buffers of this track.
2248 // Remove it from the list of active tracks.
2249 tracksToRemove->add(track);
2250 } else {
2251 // No buffers for this track. Give it a few chances to
2252 // fill a buffer, then remove it from active list.
2253 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002254 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002256 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002257 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002258 } else if (mixerStatus != MIXER_TRACKS_READY) {
2259 mixerStatus = MIXER_TRACKS_ENABLED;
2260 }
2261 }
Glenn Kasten1c48c3c2011-12-15 14:54:01 -08002262 mAudioMixer->disable();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 }
2264 }
2265
2266 // remove all the tracks that need to be...
2267 count = tracksToRemove->size();
Glenn Kastenf6b16782011-12-15 09:51:17 -08002268 if (CC_UNLIKELY(count)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002269 for (size_t i=0 ; i<count ; i++) {
2270 const sp<Track>& track = tracksToRemove->itemAt(i);
2271 mActiveTracks.remove(track);
2272 if (track->mainBuffer() != mMixBuffer) {
2273 chain = getEffectChain_l(track->sessionId());
2274 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002275 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002276 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002277 }
2278 }
2279 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002280 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 }
2282 }
2283 }
2284
2285 // mix buffer must be cleared if all tracks are connected to an
2286 // effect chain as in this case the mixer will not write to
2287 // mix buffer and track effects will accumulate into it
2288 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2289 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2290 }
2291
2292 return mixerStatus;
2293}
2294
2295void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2296{
Steve Block3856b092011-10-20 11:56:00 +01002297 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002298 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002300
Mathias Agopian65ab4712010-07-14 17:59:35 -07002301 size_t size = mTracks.size();
2302 for (size_t i = 0; i < size; i++) {
2303 sp<Track> t = mTracks[i];
2304 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002305 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 }
2308 }
2309}
2310
Eric Laurent9f6530f2011-08-30 10:18:54 -07002311void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2312{
Steve Block3856b092011-10-20 11:56:00 +01002313 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002314 this, streamType, valid);
2315 Mutex::Autolock _l(mLock);
2316
2317 mStreamTypes[streamType].valid = valid;
2318}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002319
2320// getTrackName_l() must be called with ThreadBase::mLock held
2321int AudioFlinger::MixerThread::getTrackName_l()
2322{
2323 return mAudioMixer->getTrackName();
2324}
2325
2326// deleteTrackName_l() must be called with ThreadBase::mLock held
2327void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2328{
Steve Block3856b092011-10-20 11:56:00 +01002329 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002330 mAudioMixer->deleteTrackName(name);
2331}
2332
2333// checkForNewParameters_l() must be called with ThreadBase::mLock held
2334bool AudioFlinger::MixerThread::checkForNewParameters_l()
2335{
2336 bool reconfig = false;
2337
2338 while (!mNewParameters.isEmpty()) {
2339 status_t status = NO_ERROR;
2340 String8 keyValuePair = mNewParameters[0];
2341 AudioParameter param = AudioParameter(keyValuePair);
2342 int value;
2343
2344 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2345 reconfig = true;
2346 }
2347 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002348 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349 status = BAD_VALUE;
2350 } else {
2351 reconfig = true;
2352 }
2353 }
2354 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002355 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002356 status = BAD_VALUE;
2357 } else {
2358 reconfig = true;
2359 }
2360 }
2361 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2362 // do not accept frame count changes if tracks are open as the track buffer
Glenn Kasten362c4e62011-12-14 10:28:06 -08002363 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002364 // if frame count is changed after track creation
2365 if (!mTracks.isEmpty()) {
2366 status = INVALID_OPERATION;
2367 } else {
2368 reconfig = true;
2369 }
2370 }
2371 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002372 // when changing the audio output device, call addBatteryData to notify
2373 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002374 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002375 uint32_t params = 0;
2376 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002377 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002378 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2379 }
2380
2381 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002382 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002383 // check if any other device (except speaker) is on
2384 if (value & deviceWithoutSpeaker ) {
2385 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2386 }
2387
2388 if (params != 0) {
2389 addBatteryData(params);
2390 }
2391 }
2392
Mathias Agopian65ab4712010-07-14 17:59:35 -07002393 // forward device change to effects that have requested to be
2394 // aware of attached audio device.
2395 mDevice = (uint32_t)value;
2396 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002397 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398 }
2399 }
2400
2401 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002402 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002403 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002404 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002405 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002406 mStandby = true;
2407 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002408 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002409 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002410 }
2411 if (status == NO_ERROR && reconfig) {
2412 delete mAudioMixer;
2413 readOutputParameters();
2414 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2415 for (size_t i = 0; i < mTracks.size() ; i++) {
2416 int name = getTrackName_l();
2417 if (name < 0) break;
2418 mTracks[i]->mName = name;
2419 // limit track sample rate to 2 x new output sample rate
2420 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2421 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2422 }
2423 }
2424 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2425 }
2426 }
2427
2428 mNewParameters.removeAt(0);
2429
2430 mParamStatus = status;
2431 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002432 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2433 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002434 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002435 }
2436 return reconfig;
2437}
2438
2439status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2440{
2441 const size_t SIZE = 256;
2442 char buffer[SIZE];
2443 String8 result;
2444
2445 PlaybackThread::dumpInternals(fd, args);
2446
2447 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2448 result.append(buffer);
2449 write(fd, result.string(), result.size());
2450 return NO_ERROR;
2451}
2452
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2454{
Eric Laurent60e18242010-07-29 06:50:24 -07002455 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456}
2457
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002458uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2459{
2460 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2461}
2462
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002464AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 : PlaybackThread(audioFlinger, output, id, device)
2466{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002467 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468}
2469
2470AudioFlinger::DirectOutputThread::~DirectOutputThread()
2471{
2472}
2473
Mathias Agopian65ab4712010-07-14 17:59:35 -07002474static inline
2475int32_t mul(int16_t in, int16_t v)
2476{
2477#if defined(__arm__) && !defined(__thumb__)
2478 int32_t out;
2479 asm( "smulbb %[out], %[in], %[v] \n"
2480 : [out]"=r"(out)
2481 : [in]"%r"(in), [v]"r"(v)
2482 : );
2483 return out;
2484#else
2485 return in * int32_t(v);
2486#endif
2487}
2488
2489void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2490{
2491 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002492 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 return;
2494 }
2495
2496 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002497 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498 size_t count = mFrameCount * mChannelCount;
2499 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2500 int16_t *dst = mMixBuffer + count-1;
2501 while(count--) {
2502 *dst-- = (int16_t)(*src--^0x80) << 8;
2503 }
2504 }
2505
2506 size_t frameCount = mFrameCount;
2507 int16_t *out = mMixBuffer;
2508 if (ramp) {
2509 if (mChannelCount == 1) {
2510 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2511 int32_t vlInc = d / (int32_t)frameCount;
2512 int32_t vl = ((int32_t)mLeftVolShort << 16);
2513 do {
2514 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2515 out++;
2516 vl += vlInc;
2517 } while (--frameCount);
2518
2519 } else {
2520 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2521 int32_t vlInc = d / (int32_t)frameCount;
2522 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2523 int32_t vrInc = d / (int32_t)frameCount;
2524 int32_t vl = ((int32_t)mLeftVolShort << 16);
2525 int32_t vr = ((int32_t)mRightVolShort << 16);
2526 do {
2527 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2528 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2529 out += 2;
2530 vl += vlInc;
2531 vr += vrInc;
2532 } while (--frameCount);
2533 }
2534 } else {
2535 if (mChannelCount == 1) {
2536 do {
2537 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2538 out++;
2539 } while (--frameCount);
2540 } else {
2541 do {
2542 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2543 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2544 out += 2;
2545 } while (--frameCount);
2546 }
2547 }
2548
2549 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002550 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002551 size_t count = mFrameCount * mChannelCount;
2552 int16_t *src = mMixBuffer;
2553 uint8_t *dst = (uint8_t *)mMixBuffer;
2554 while(count--) {
2555 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2556 }
2557 }
2558
2559 mLeftVolShort = leftVol;
2560 mRightVolShort = rightVol;
2561}
2562
2563bool AudioFlinger::DirectOutputThread::threadLoop()
2564{
2565 uint32_t mixerStatus = MIXER_IDLE;
2566 sp<Track> trackToRemove;
2567 sp<Track> activeTrack;
2568 nsecs_t standbyTime = systemTime();
2569 int8_t *curBuf;
2570 size_t mixBufferSize = mFrameCount*mFrameSize;
2571 uint32_t activeSleepTime = activeSleepTimeUs();
2572 uint32_t idleSleepTime = idleSleepTimeUs();
2573 uint32_t sleepTime = idleSleepTime;
2574 // use shorter standby delay as on normal output to release
2575 // hardware resources as soon as possible
2576 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2577
Eric Laurentfeb0db62011-07-22 09:04:31 -07002578 acquireWakeLock();
2579
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 while (!exitPending())
2581 {
2582 bool rampVolume;
2583 uint16_t leftVol;
2584 uint16_t rightVol;
2585 Vector< sp<EffectChain> > effectChains;
2586
2587 processConfigEvents();
2588
2589 mixerStatus = MIXER_IDLE;
2590
2591 { // scope for the mLock
2592
2593 Mutex::Autolock _l(mLock);
2594
2595 if (checkForNewParameters_l()) {
2596 mixBufferSize = mFrameCount*mFrameSize;
2597 activeSleepTime = activeSleepTimeUs();
2598 idleSleepTime = idleSleepTimeUs();
2599 standbyDelay = microseconds(activeSleepTime*2);
2600 }
2601
2602 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002603 if (CC_UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2604 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002605 // wait until we have something to do...
2606 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002607 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002608 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609 mStandby = true;
2610 mBytesWritten = 0;
2611 }
2612
2613 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2614 // we're about to wait, flush the binder command buffer
2615 IPCThreadState::self()->flushCommands();
2616
2617 if (exitPending()) break;
2618
Eric Laurentfeb0db62011-07-22 09:04:31 -07002619 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002620 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002622 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002623 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624
2625 if (mMasterMute == false) {
2626 char value[PROPERTY_VALUE_MAX];
2627 property_get("ro.audio.silent", value, "0");
2628 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00002629 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 setMasterMute(true);
2631 }
2632 }
2633
2634 standbyTime = systemTime() + standbyDelay;
2635 sleepTime = idleSleepTime;
2636 continue;
2637 }
2638 }
2639
2640 effectChains = mEffectChains;
2641
2642 // find out which tracks need to be processed
2643 if (mActiveTracks.size() != 0) {
2644 sp<Track> t = mActiveTracks[0].promote();
2645 if (t == 0) continue;
2646
2647 Track* const track = t.get();
2648 audio_track_cblk_t* cblk = track->cblk();
2649
2650 // The first time a track is added we wait
2651 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002652 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653 !track->isPaused() && !track->isTerminated())
2654 {
Steve Block3856b092011-10-20 11:56:00 +01002655 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002656
2657 if (track->mFillingUpStatus == Track::FS_FILLED) {
2658 track->mFillingUpStatus = Track::FS_ACTIVE;
2659 mLeftVolFloat = mRightVolFloat = 0;
2660 mLeftVolShort = mRightVolShort = 0;
2661 if (track->mState == TrackBase::RESUMING) {
2662 track->mState = TrackBase::ACTIVE;
2663 rampVolume = true;
2664 }
2665 } else if (cblk->server != 0) {
2666 // If the track is stopped before the first frame was mixed,
2667 // do not apply ramp
2668 rampVolume = true;
2669 }
2670 // compute volume for this track
2671 float left, right;
2672 if (track->isMuted() || mMasterMute || track->isPausing() ||
2673 mStreamTypes[track->type()].mute) {
2674 left = right = 0;
2675 if (track->isPausing()) {
2676 track->setPaused();
2677 }
2678 } else {
2679 float typeVolume = mStreamTypes[track->type()].volume;
2680 float v = mMasterVolume * typeVolume;
2681 float v_clamped = v * cblk->volume[0];
2682 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2683 left = v_clamped/MAX_GAIN;
2684 v_clamped = v * cblk->volume[1];
2685 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2686 right = v_clamped/MAX_GAIN;
2687 }
2688
2689 if (left != mLeftVolFloat || right != mRightVolFloat) {
2690 mLeftVolFloat = left;
2691 mRightVolFloat = right;
2692
2693 // If audio HAL implements volume control,
2694 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002695 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 left = 1.0f;
2697 right = 1.0f;
2698 }
2699
2700 // Convert volumes from float to 8.24
2701 uint32_t vl = (uint32_t)(left * (1 << 24));
2702 uint32_t vr = (uint32_t)(right * (1 << 24));
2703
2704 // Delegate volume control to effect in track effect chain if needed
2705 // only one effect chain can be present on DirectOutputThread, so if
2706 // there is one, the track is connected to it
2707 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002708 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002709 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002710 rampVolume = false;
2711 }
2712 }
2713
2714 // Convert volumes from 8.24 to 4.12 format
2715 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2716 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2717 leftVol = (uint16_t)v_clamped;
2718 v_clamped = (vr + (1 << 11)) >> 12;
2719 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2720 rightVol = (uint16_t)v_clamped;
2721 } else {
2722 leftVol = mLeftVolShort;
2723 rightVol = mRightVolShort;
2724 rampVolume = false;
2725 }
2726
2727 // reset retry count
2728 track->mRetryCount = kMaxTrackRetriesDirect;
2729 activeTrack = t;
2730 mixerStatus = MIXER_TRACKS_READY;
2731 } else {
Steve Block3856b092011-10-20 11:56:00 +01002732 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002733 if (track->isStopped()) {
2734 track->reset();
2735 }
2736 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2737 // We have consumed all the buffers of this track.
2738 // Remove it from the list of active tracks.
2739 trackToRemove = track;
2740 } else {
2741 // No buffers for this track. Give it a few chances to
2742 // fill a buffer, then remove it from active list.
2743 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002744 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745 trackToRemove = track;
2746 } else {
2747 mixerStatus = MIXER_TRACKS_ENABLED;
2748 }
2749 }
2750 }
2751 }
2752
2753 // remove all the tracks that need to be...
Glenn Kastenf6b16782011-12-15 09:51:17 -08002754 if (CC_UNLIKELY(trackToRemove != 0)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002755 mActiveTracks.remove(trackToRemove);
2756 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002757 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002758 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002759 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 }
2761 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002762 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002763 }
2764 }
2765
Eric Laurentde070132010-07-13 04:45:46 -07002766 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002767 }
2768
Glenn Kastenf6b16782011-12-15 09:51:17 -08002769 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002770 AudioBufferProvider::Buffer buffer;
2771 size_t frameCount = mFrameCount;
2772 curBuf = (int8_t *)mMixBuffer;
2773 // output audio to hardware
2774 while (frameCount) {
2775 buffer.frameCount = frameCount;
2776 activeTrack->getNextBuffer(&buffer);
Glenn Kastenf6b16782011-12-15 09:51:17 -08002777 if (CC_UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002778 memset(curBuf, 0, frameCount * mFrameSize);
2779 break;
2780 }
2781 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2782 frameCount -= buffer.frameCount;
2783 curBuf += buffer.frameCount * mFrameSize;
2784 activeTrack->releaseBuffer(&buffer);
2785 }
2786 sleepTime = 0;
2787 standbyTime = systemTime() + standbyDelay;
2788 } else {
2789 if (sleepTime == 0) {
2790 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2791 sleepTime = activeSleepTime;
2792 } else {
2793 sleepTime = idleSleepTime;
2794 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002795 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2797 sleepTime = 0;
2798 }
2799 }
2800
2801 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002802 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803 }
2804 // sleepTime == 0 means we must write to audio hardware
2805 if (sleepTime == 0) {
2806 if (mixerStatus == MIXER_TRACKS_READY) {
2807 applyVolume(leftVol, rightVol, rampVolume);
2808 }
2809 for (size_t i = 0; i < effectChains.size(); i ++) {
2810 effectChains[i]->process_l();
2811 }
Eric Laurentde070132010-07-13 04:45:46 -07002812 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002813
2814 mLastWriteTime = systemTime();
2815 mInWrite = true;
2816 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002817 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2819 mNumWrites++;
2820 mInWrite = false;
2821 mStandby = false;
2822 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002823 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002824 usleep(sleepTime);
2825 }
2826
2827 // finally let go of removed track, without the lock held
2828 // since we can't guarantee the destructors won't acquire that
2829 // same lock.
2830 trackToRemove.clear();
2831 activeTrack.clear();
2832
2833 // Effect chains will be actually deleted here if they were removed from
2834 // mEffectChains list during mixing or effects processing
2835 effectChains.clear();
2836 }
2837
2838 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002839 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840 }
2841
Eric Laurentfeb0db62011-07-22 09:04:31 -07002842 releaseWakeLock();
2843
Steve Block3856b092011-10-20 11:56:00 +01002844 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002845 return false;
2846}
2847
2848// getTrackName_l() must be called with ThreadBase::mLock held
2849int AudioFlinger::DirectOutputThread::getTrackName_l()
2850{
2851 return 0;
2852}
2853
2854// deleteTrackName_l() must be called with ThreadBase::mLock held
2855void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2856{
2857}
2858
2859// checkForNewParameters_l() must be called with ThreadBase::mLock held
2860bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2861{
2862 bool reconfig = false;
2863
2864 while (!mNewParameters.isEmpty()) {
2865 status_t status = NO_ERROR;
2866 String8 keyValuePair = mNewParameters[0];
2867 AudioParameter param = AudioParameter(keyValuePair);
2868 int value;
2869
2870 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2871 // do not accept frame count changes if tracks are open as the track buffer
2872 // size depends on frame count and correct behavior would not be garantied
2873 // if frame count is changed after track creation
2874 if (!mTracks.isEmpty()) {
2875 status = INVALID_OPERATION;
2876 } else {
2877 reconfig = true;
2878 }
2879 }
2880 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002881 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002882 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002883 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002884 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885 mStandby = true;
2886 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002887 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002888 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002889 }
2890 if (status == NO_ERROR && reconfig) {
2891 readOutputParameters();
2892 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2893 }
2894 }
2895
2896 mNewParameters.removeAt(0);
2897
2898 mParamStatus = status;
2899 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002900 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2901 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002902 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002903 }
2904 return reconfig;
2905}
2906
2907uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2908{
2909 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002910 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002911 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002912 } else {
2913 time = 10000;
2914 }
2915 return time;
2916}
2917
2918uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2919{
2920 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002921 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002922 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 } else {
2924 time = 10000;
2925 }
2926 return time;
2927}
2928
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002929uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2930{
2931 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002932 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002933 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2934 } else {
2935 time = 10000;
2936 }
2937 return time;
2938}
2939
2940
Mathias Agopian65ab4712010-07-14 17:59:35 -07002941// ----------------------------------------------------------------------------
2942
2943AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2944 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2945{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002946 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 addOutputTrack(mainThread);
2948}
2949
2950AudioFlinger::DuplicatingThread::~DuplicatingThread()
2951{
2952 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2953 mOutputTracks[i]->destroy();
2954 }
2955 mOutputTracks.clear();
2956}
2957
2958bool AudioFlinger::DuplicatingThread::threadLoop()
2959{
2960 Vector< sp<Track> > tracksToRemove;
2961 uint32_t mixerStatus = MIXER_IDLE;
2962 nsecs_t standbyTime = systemTime();
2963 size_t mixBufferSize = mFrameCount*mFrameSize;
2964 SortedVector< sp<OutputTrack> > outputTracks;
2965 uint32_t writeFrames = 0;
2966 uint32_t activeSleepTime = activeSleepTimeUs();
2967 uint32_t idleSleepTime = idleSleepTimeUs();
2968 uint32_t sleepTime = idleSleepTime;
2969 Vector< sp<EffectChain> > effectChains;
2970
Eric Laurentfeb0db62011-07-22 09:04:31 -07002971 acquireWakeLock();
2972
Mathias Agopian65ab4712010-07-14 17:59:35 -07002973 while (!exitPending())
2974 {
2975 processConfigEvents();
2976
2977 mixerStatus = MIXER_IDLE;
2978 { // scope for the mLock
2979
2980 Mutex::Autolock _l(mLock);
2981
2982 if (checkForNewParameters_l()) {
2983 mixBufferSize = mFrameCount*mFrameSize;
2984 updateWaitTime();
2985 activeSleepTime = activeSleepTimeUs();
2986 idleSleepTime = idleSleepTimeUs();
2987 }
2988
2989 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2990
2991 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2992 outputTracks.add(mOutputTracks[i]);
2993 }
2994
2995 // put audio hardware into standby after short delay
Glenn Kastenf6b16782011-12-15 09:51:17 -08002996 if (CC_UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2997 mSuspended)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002998 if (!mStandby) {
2999 for (size_t i = 0; i < outputTracks.size(); i++) {
3000 outputTracks[i]->stop();
3001 }
3002 mStandby = true;
3003 mBytesWritten = 0;
3004 }
3005
3006 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3007 // we're about to wait, flush the binder command buffer
3008 IPCThreadState::self()->flushCommands();
3009 outputTracks.clear();
3010
3011 if (exitPending()) break;
3012
Eric Laurentfeb0db62011-07-22 09:04:31 -07003013 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003014 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003015 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003016 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003017 acquireWakeLock_l();
3018
Mathias Agopian65ab4712010-07-14 17:59:35 -07003019 if (mMasterMute == false) {
3020 char value[PROPERTY_VALUE_MAX];
3021 property_get("ro.audio.silent", value, "0");
3022 if (atoi(value)) {
Steve Blockb8a80522011-12-20 16:23:08 +00003023 ALOGD("Silence is golden");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003024 setMasterMute(true);
3025 }
3026 }
3027
3028 standbyTime = systemTime() + kStandbyTimeInNsecs;
3029 sleepTime = idleSleepTime;
3030 continue;
3031 }
3032 }
3033
3034 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3035
3036 // prevent any changes in effect chain list and in each effect chain
3037 // during mixing and effect process as the audio buffers could be deleted
3038 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003039 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003040 }
3041
Glenn Kastenf6b16782011-12-15 09:51:17 -08003042 if (CC_LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003043 // mix buffers...
3044 if (outputsReady(outputTracks)) {
3045 mAudioMixer->process();
3046 } else {
3047 memset(mMixBuffer, 0, mixBufferSize);
3048 }
3049 sleepTime = 0;
3050 writeFrames = mFrameCount;
3051 } else {
3052 if (sleepTime == 0) {
3053 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3054 sleepTime = activeSleepTime;
3055 } else {
3056 sleepTime = idleSleepTime;
3057 }
3058 } else if (mBytesWritten != 0) {
3059 // flush remaining overflow buffers in output tracks
3060 for (size_t i = 0; i < outputTracks.size(); i++) {
3061 if (outputTracks[i]->isActive()) {
3062 sleepTime = 0;
3063 writeFrames = 0;
3064 memset(mMixBuffer, 0, mixBufferSize);
3065 break;
3066 }
3067 }
3068 }
3069 }
3070
3071 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003072 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003073 }
3074 // sleepTime == 0 means we must write to audio hardware
3075 if (sleepTime == 0) {
3076 for (size_t i = 0; i < effectChains.size(); i ++) {
3077 effectChains[i]->process_l();
3078 }
3079 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003080 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003081
3082 standbyTime = systemTime() + kStandbyTimeInNsecs;
3083 for (size_t i = 0; i < outputTracks.size(); i++) {
3084 outputTracks[i]->write(mMixBuffer, writeFrames);
3085 }
3086 mStandby = false;
3087 mBytesWritten += mixBufferSize;
3088 } else {
3089 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003090 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 usleep(sleepTime);
3092 }
3093
3094 // finally let go of all our tracks, without the lock held
3095 // since we can't guarantee the destructors won't acquire that
3096 // same lock.
3097 tracksToRemove.clear();
3098 outputTracks.clear();
3099
3100 // Effect chains will be actually deleted here if they were removed from
3101 // mEffectChains list during mixing or effects processing
3102 effectChains.clear();
3103 }
3104
Eric Laurentfeb0db62011-07-22 09:04:31 -07003105 releaseWakeLock();
3106
Mathias Agopian65ab4712010-07-14 17:59:35 -07003107 return false;
3108}
3109
3110void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3111{
3112 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3113 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3114 this,
3115 mSampleRate,
3116 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003117 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 frameCount);
3119 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003120 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003122 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123 updateWaitTime();
3124 }
3125}
3126
3127void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3128{
3129 Mutex::Autolock _l(mLock);
3130 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3131 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3132 mOutputTracks[i]->destroy();
3133 mOutputTracks.removeAt(i);
3134 updateWaitTime();
3135 return;
3136 }
3137 }
Steve Block3856b092011-10-20 11:56:00 +01003138 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003139}
3140
3141void AudioFlinger::DuplicatingThread::updateWaitTime()
3142{
3143 mWaitTimeMs = UINT_MAX;
3144 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3145 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3146 if (strong != NULL) {
3147 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3148 if (waitTimeMs < mWaitTimeMs) {
3149 mWaitTimeMs = waitTimeMs;
3150 }
3151 }
3152 }
3153}
3154
3155
3156bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3157{
3158 for (size_t i = 0; i < outputTracks.size(); i++) {
3159 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3160 if (thread == 0) {
3161 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3162 return false;
3163 }
3164 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3165 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003166 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003167 return false;
3168 }
3169 }
3170 return true;
3171}
3172
3173uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3174{
3175 return (mWaitTimeMs * 1000) / 2;
3176}
3177
3178// ----------------------------------------------------------------------------
3179
3180// TrackBase constructor must be called with AudioFlinger::mLock held
3181AudioFlinger::ThreadBase::TrackBase::TrackBase(
3182 const wp<ThreadBase>& thread,
3183 const sp<Client>& client,
3184 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003185 uint32_t format,
3186 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003187 int frameCount,
3188 uint32_t flags,
3189 const sp<IMemory>& sharedBuffer,
3190 int sessionId)
3191 : RefBase(),
3192 mThread(thread),
3193 mClient(client),
3194 mCblk(0),
3195 mFrameCount(0),
3196 mState(IDLE),
3197 mClientTid(-1),
3198 mFormat(format),
3199 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3200 mSessionId(sessionId)
3201{
Steve Block3856b092011-10-20 11:56:00 +01003202 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003203
Steve Blockb8a80522011-12-20 16:23:08 +00003204 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003205 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003206 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003207 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3208 if (sharedBuffer == 0) {
3209 size += bufferSize;
3210 }
3211
3212 if (client != NULL) {
3213 mCblkMemory = client->heap()->allocate(size);
3214 if (mCblkMemory != 0) {
3215 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3216 if (mCblk) { // construct the shared structure in-place.
3217 new(mCblk) audio_track_cblk_t();
3218 // clear all buffers
3219 mCblk->frameCount = frameCount;
3220 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003221 mChannelCount = channelCount;
3222 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003223 if (sharedBuffer == 0) {
3224 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3225 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3226 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003227 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003228 mCblk->flags = CBLK_UNDERRUN_ON;
3229 } else {
3230 mBuffer = sharedBuffer->pointer();
3231 }
3232 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3233 }
3234 } else {
3235 LOGE("not enough memory for AudioTrack size=%u", size);
3236 client->heap()->dump("AudioTrack");
3237 return;
3238 }
3239 } else {
3240 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
Glenn Kasten4a6f0282012-01-06 15:03:11 -08003241 // construct the shared structure in-place.
Mathias Agopian65ab4712010-07-14 17:59:35 -07003242 new(mCblk) audio_track_cblk_t();
3243 // clear all buffers
3244 mCblk->frameCount = frameCount;
3245 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003246 mChannelCount = channelCount;
3247 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003248 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3249 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3250 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003251 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003252 mCblk->flags = CBLK_UNDERRUN_ON;
3253 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003254 }
3255}
3256
3257AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3258{
3259 if (mCblk) {
3260 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3261 if (mClient == NULL) {
3262 delete mCblk;
3263 }
3264 }
3265 mCblkMemory.clear(); // and free the shared memory
3266 if (mClient != NULL) {
3267 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3268 mClient.clear();
3269 }
3270}
3271
3272void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3273{
Glenn Kastene0feee32011-12-13 11:53:26 -08003274 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003275 mFrameCount = buffer->frameCount;
3276 step();
3277 buffer->frameCount = 0;
3278}
3279
3280bool AudioFlinger::ThreadBase::TrackBase::step() {
3281 bool result;
3282 audio_track_cblk_t* cblk = this->cblk();
3283
3284 result = cblk->stepServer(mFrameCount);
3285 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003286 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287 mFlags |= STEPSERVER_FAILED;
3288 }
3289 return result;
3290}
3291
3292void AudioFlinger::ThreadBase::TrackBase::reset() {
3293 audio_track_cblk_t* cblk = this->cblk();
3294
3295 cblk->user = 0;
3296 cblk->server = 0;
3297 cblk->userBase = 0;
3298 cblk->serverBase = 0;
3299 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003300 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003301}
3302
3303sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3304{
3305 return mCblkMemory;
3306}
3307
3308int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3309 return (int)mCblk->sampleRate;
3310}
3311
3312int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003313 return (const int)mChannelCount;
3314}
3315
3316uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3317 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003318}
3319
3320void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3321 audio_track_cblk_t* cblk = this->cblk();
3322 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3323 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3324
3325 // Check validity of returned pointer in case the track control block would have been corrupted.
3326 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3327 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3328 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 -07003329 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003331 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 return 0;
3333 }
3334
3335 return bufferStart;
3336}
3337
3338// ----------------------------------------------------------------------------
3339
3340// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3341AudioFlinger::PlaybackThread::Track::Track(
3342 const wp<ThreadBase>& thread,
3343 const sp<Client>& client,
3344 int streamType,
3345 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003346 uint32_t format,
3347 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003348 int frameCount,
3349 const sp<IMemory>& sharedBuffer,
3350 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003351 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003352 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3353 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003354{
3355 if (mCblk != NULL) {
3356 sp<ThreadBase> baseThread = thread.promote();
3357 if (baseThread != 0) {
3358 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3359 mName = playbackThread->getTrackName_l();
3360 mMainBuffer = playbackThread->mixBuffer();
3361 }
Steve Block3856b092011-10-20 11:56:00 +01003362 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 if (mName < 0) {
3364 LOGE("no more track names available");
3365 }
3366 mVolume[0] = 1.0f;
3367 mVolume[1] = 1.0f;
3368 mStreamType = streamType;
3369 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3370 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003371 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003372 }
3373}
3374
3375AudioFlinger::PlaybackThread::Track::~Track()
3376{
Steve Block3856b092011-10-20 11:56:00 +01003377 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003378 sp<ThreadBase> thread = mThread.promote();
3379 if (thread != 0) {
3380 Mutex::Autolock _l(thread->mLock);
3381 mState = TERMINATED;
3382 }
3383}
3384
3385void AudioFlinger::PlaybackThread::Track::destroy()
3386{
3387 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3388 // by removing it from mTracks vector, so there is a risk that this Tracks's
3389 // desctructor is called. As the destructor needs to lock mLock,
3390 // we must acquire a strong reference on this Track before locking mLock
3391 // here so that the destructor is called only when exiting this function.
3392 // On the other hand, as long as Track::destroy() is only called by
3393 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3394 // this Track with its member mTrack.
3395 sp<Track> keep(this);
3396 { // scope for mLock
3397 sp<ThreadBase> thread = mThread.promote();
3398 if (thread != 0) {
3399 if (!isOutputTrack()) {
3400 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003401 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003402 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003403 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003404
3405 // to track the speaker usage
3406 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003407 }
3408 AudioSystem::releaseOutput(thread->id());
3409 }
3410 Mutex::Autolock _l(thread->mLock);
3411 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3412 playbackThread->destroyTrack_l(this);
3413 }
3414 }
3415}
3416
3417void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3418{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003419 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 -07003420 mName - AudioMixer::TRACK0,
3421 (mClient == NULL) ? getpid() : mClient->pid(),
3422 mStreamType,
3423 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003424 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003425 mSessionId,
3426 mFrameCount,
3427 mState,
3428 mMute,
3429 mFillingUpStatus,
3430 mCblk->sampleRate,
3431 mCblk->volume[0],
3432 mCblk->volume[1],
3433 mCblk->server,
3434 mCblk->user,
3435 (int)mMainBuffer,
3436 (int)mAuxBuffer);
3437}
3438
3439status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3440{
3441 audio_track_cblk_t* cblk = this->cblk();
3442 uint32_t framesReady;
3443 uint32_t framesReq = buffer->frameCount;
3444
3445 // Check if last stepServer failed, try to step now
3446 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3447 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003448 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3450 }
3451
3452 framesReady = cblk->framesReady();
3453
Glenn Kastenf6b16782011-12-15 09:51:17 -08003454 if (CC_LIKELY(framesReady)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003455 uint32_t s = cblk->server;
3456 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3457
3458 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3459 if (framesReq > framesReady) {
3460 framesReq = framesReady;
3461 }
3462 if (s + framesReq > bufferEnd) {
3463 framesReq = bufferEnd - s;
3464 }
3465
3466 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003467 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003468
3469 buffer->frameCount = framesReq;
3470 return NO_ERROR;
3471 }
3472
3473getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003474 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003476 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003477 return NOT_ENOUGH_DATA;
3478}
3479
3480bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003481 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003482
3483 if (mCblk->framesReady() >= mCblk->frameCount ||
3484 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3485 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003486 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003487 return true;
3488 }
3489 return false;
3490}
3491
3492status_t AudioFlinger::PlaybackThread::Track::start()
3493{
3494 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003495 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003496 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497 sp<ThreadBase> thread = mThread.promote();
3498 if (thread != 0) {
3499 Mutex::Autolock _l(thread->mLock);
3500 int state = mState;
3501 // here the track could be either new, or restarted
3502 // in both cases "unstop" the track
3503 if (mState == PAUSED) {
3504 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003505 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003506 } else {
3507 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003508 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003509 }
3510
3511 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3512 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003513 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003514 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003515 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003517
3518 // to track the speaker usage
3519 if (status == NO_ERROR) {
3520 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003522 }
3523 if (status == NO_ERROR) {
3524 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3525 playbackThread->addTrack_l(this);
3526 } else {
3527 mState = state;
3528 }
3529 } else {
3530 status = BAD_VALUE;
3531 }
3532 return status;
3533}
3534
3535void AudioFlinger::PlaybackThread::Track::stop()
3536{
Steve Block3856b092011-10-20 11:56:00 +01003537 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003538 sp<ThreadBase> thread = mThread.promote();
3539 if (thread != 0) {
3540 Mutex::Autolock _l(thread->mLock);
3541 int state = mState;
3542 if (mState > STOPPED) {
3543 mState = STOPPED;
3544 // If the track is not active (PAUSED and buffers full), flush buffers
3545 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3546 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3547 reset();
3548 }
Steve Block3856b092011-10-20 11:56:00 +01003549 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003550 }
3551 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3552 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003553 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003554 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003555 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003556 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003557
3558 // to track the speaker usage
3559 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 }
3561 }
3562}
3563
3564void AudioFlinger::PlaybackThread::Track::pause()
3565{
Steve Block3856b092011-10-20 11:56:00 +01003566 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003567 sp<ThreadBase> thread = mThread.promote();
3568 if (thread != 0) {
3569 Mutex::Autolock _l(thread->mLock);
3570 if (mState == ACTIVE || mState == RESUMING) {
3571 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003572 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 if (!isOutputTrack()) {
3574 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003575 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003576 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003577 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003578 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003579
3580 // to track the speaker usage
3581 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003582 }
3583 }
3584 }
3585}
3586
3587void AudioFlinger::PlaybackThread::Track::flush()
3588{
Steve Block3856b092011-10-20 11:56:00 +01003589 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590 sp<ThreadBase> thread = mThread.promote();
3591 if (thread != 0) {
3592 Mutex::Autolock _l(thread->mLock);
3593 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3594 return;
3595 }
3596 // No point remaining in PAUSED state after a flush => go to
3597 // STOPPED state
3598 mState = STOPPED;
3599
Eric Laurent38ccae22011-03-28 18:37:07 -07003600 // do not reset the track if it is still in the process of being stopped or paused.
3601 // this will be done by prepareTracks_l() when the track is stopped.
3602 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3603 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3604 reset();
3605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606 }
3607}
3608
3609void AudioFlinger::PlaybackThread::Track::reset()
3610{
3611 // Do not reset twice to avoid discarding data written just after a flush and before
3612 // the audioflinger thread detects the track is stopped.
3613 if (!mResetDone) {
3614 TrackBase::reset();
3615 // Force underrun condition to avoid false underrun callback until first data is
3616 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003617 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3618 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 mFillingUpStatus = FS_FILLING;
3620 mResetDone = true;
3621 }
3622}
3623
3624void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3625{
3626 mMute = muted;
3627}
3628
3629void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3630{
3631 mVolume[0] = left;
3632 mVolume[1] = right;
3633}
3634
3635status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3636{
3637 status_t status = DEAD_OBJECT;
3638 sp<ThreadBase> thread = mThread.promote();
3639 if (thread != 0) {
3640 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3641 status = playbackThread->attachAuxEffect(this, EffectId);
3642 }
3643 return status;
3644}
3645
3646void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3647{
3648 mAuxEffectId = EffectId;
3649 mAuxBuffer = buffer;
3650}
3651
3652// ----------------------------------------------------------------------------
3653
3654// RecordTrack constructor must be called with AudioFlinger::mLock held
3655AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3656 const wp<ThreadBase>& thread,
3657 const sp<Client>& client,
3658 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003659 uint32_t format,
3660 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661 int frameCount,
3662 uint32_t flags,
3663 int sessionId)
3664 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003665 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003666 mOverflow(false)
3667{
3668 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003669 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003670 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003671 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003672 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003673 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003674 } else {
3675 mCblk->frameSize = sizeof(int8_t);
3676 }
3677 }
3678}
3679
3680AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3681{
3682 sp<ThreadBase> thread = mThread.promote();
3683 if (thread != 0) {
3684 AudioSystem::releaseInput(thread->id());
3685 }
3686}
3687
3688status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3689{
3690 audio_track_cblk_t* cblk = this->cblk();
3691 uint32_t framesAvail;
3692 uint32_t framesReq = buffer->frameCount;
3693
3694 // Check if last stepServer failed, try to step now
3695 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3696 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003697 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003698 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3699 }
3700
3701 framesAvail = cblk->framesAvailable_l();
3702
Glenn Kastenf6b16782011-12-15 09:51:17 -08003703 if (CC_LIKELY(framesAvail)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003704 uint32_t s = cblk->server;
3705 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3706
3707 if (framesReq > framesAvail) {
3708 framesReq = framesAvail;
3709 }
3710 if (s + framesReq > bufferEnd) {
3711 framesReq = bufferEnd - s;
3712 }
3713
3714 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003715 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003716
3717 buffer->frameCount = framesReq;
3718 return NO_ERROR;
3719 }
3720
3721getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003722 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003723 buffer->frameCount = 0;
3724 return NOT_ENOUGH_DATA;
3725}
3726
3727status_t AudioFlinger::RecordThread::RecordTrack::start()
3728{
3729 sp<ThreadBase> thread = mThread.promote();
3730 if (thread != 0) {
3731 RecordThread *recordThread = (RecordThread *)thread.get();
3732 return recordThread->start(this);
3733 } else {
3734 return BAD_VALUE;
3735 }
3736}
3737
3738void AudioFlinger::RecordThread::RecordTrack::stop()
3739{
3740 sp<ThreadBase> thread = mThread.promote();
3741 if (thread != 0) {
3742 RecordThread *recordThread = (RecordThread *)thread.get();
3743 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003744 TrackBase::reset();
3745 // Force overerrun condition to avoid false overrun callback until first data is
3746 // read from buffer
3747 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003748 }
3749}
3750
3751void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3752{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003753 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003754 (mClient == NULL) ? getpid() : mClient->pid(),
3755 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003756 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003757 mSessionId,
3758 mFrameCount,
3759 mState,
3760 mCblk->sampleRate,
3761 mCblk->server,
3762 mCblk->user);
3763}
3764
3765
3766// ----------------------------------------------------------------------------
3767
3768AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3769 const wp<ThreadBase>& thread,
3770 DuplicatingThread *sourceThread,
3771 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003772 uint32_t format,
3773 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003774 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003775 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776 mActive(false), mSourceThread(sourceThread)
3777{
3778
3779 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3780 if (mCblk != NULL) {
3781 mCblk->flags |= CBLK_DIRECTION_OUT;
3782 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3783 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3784 mOutBuffer.frameCount = 0;
3785 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003786 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003787 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3788 mCblk, mBuffer, mCblk->buffers,
3789 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003790 } else {
3791 LOGW("Error creating output track on thread %p", playbackThread);
3792 }
3793}
3794
3795AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3796{
3797 clearBufferQueue();
3798}
3799
3800status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3801{
3802 status_t status = Track::start();
3803 if (status != NO_ERROR) {
3804 return status;
3805 }
3806
3807 mActive = true;
3808 mRetryCount = 127;
3809 return status;
3810}
3811
3812void AudioFlinger::PlaybackThread::OutputTrack::stop()
3813{
3814 Track::stop();
3815 clearBufferQueue();
3816 mOutBuffer.frameCount = 0;
3817 mActive = false;
3818}
3819
3820bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3821{
3822 Buffer *pInBuffer;
3823 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003824 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003825 bool outputBufferFull = false;
3826 inBuffer.frameCount = frames;
3827 inBuffer.i16 = data;
3828
3829 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3830
3831 if (!mActive && frames != 0) {
3832 start();
3833 sp<ThreadBase> thread = mThread.promote();
3834 if (thread != 0) {
3835 MixerThread *mixerThread = (MixerThread *)thread.get();
3836 if (mCblk->frameCount > frames){
3837 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3838 uint32_t startFrames = (mCblk->frameCount - frames);
3839 pInBuffer = new Buffer;
3840 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3841 pInBuffer->frameCount = startFrames;
3842 pInBuffer->i16 = pInBuffer->mBuffer;
3843 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3844 mBufferQueue.add(pInBuffer);
3845 } else {
3846 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3847 }
3848 }
3849 }
3850 }
3851
3852 while (waitTimeLeftMs) {
3853 // First write pending buffers, then new data
3854 if (mBufferQueue.size()) {
3855 pInBuffer = mBufferQueue.itemAt(0);
3856 } else {
3857 pInBuffer = &inBuffer;
3858 }
3859
3860 if (pInBuffer->frameCount == 0) {
3861 break;
3862 }
3863
3864 if (mOutBuffer.frameCount == 0) {
3865 mOutBuffer.frameCount = pInBuffer->frameCount;
3866 nsecs_t startTime = systemTime();
3867 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003868 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003869 outputBufferFull = true;
3870 break;
3871 }
3872 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3873 if (waitTimeLeftMs >= waitTimeMs) {
3874 waitTimeLeftMs -= waitTimeMs;
3875 } else {
3876 waitTimeLeftMs = 0;
3877 }
3878 }
3879
3880 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3881 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3882 mCblk->stepUser(outFrames);
3883 pInBuffer->frameCount -= outFrames;
3884 pInBuffer->i16 += outFrames * channelCount;
3885 mOutBuffer.frameCount -= outFrames;
3886 mOutBuffer.i16 += outFrames * channelCount;
3887
3888 if (pInBuffer->frameCount == 0) {
3889 if (mBufferQueue.size()) {
3890 mBufferQueue.removeAt(0);
3891 delete [] pInBuffer->mBuffer;
3892 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003893 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 } else {
3895 break;
3896 }
3897 }
3898 }
3899
3900 // If we could not write all frames, allocate a buffer and queue it for next time.
3901 if (inBuffer.frameCount) {
3902 sp<ThreadBase> thread = mThread.promote();
3903 if (thread != 0 && !thread->standby()) {
3904 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3905 pInBuffer = new Buffer;
3906 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3907 pInBuffer->frameCount = inBuffer.frameCount;
3908 pInBuffer->i16 = pInBuffer->mBuffer;
3909 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3910 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003911 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912 } else {
3913 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3914 }
3915 }
3916 }
3917
3918 // Calling write() with a 0 length buffer, means that no more data will be written:
3919 // If no more buffers are pending, fill output track buffer to make sure it is started
3920 // by output mixer.
3921 if (frames == 0 && mBufferQueue.size() == 0) {
3922 if (mCblk->user < mCblk->frameCount) {
3923 frames = mCblk->frameCount - mCblk->user;
3924 pInBuffer = new Buffer;
3925 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3926 pInBuffer->frameCount = frames;
3927 pInBuffer->i16 = pInBuffer->mBuffer;
3928 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3929 mBufferQueue.add(pInBuffer);
3930 } else if (mActive) {
3931 stop();
3932 }
3933 }
3934
3935 return outputBufferFull;
3936}
3937
3938status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3939{
3940 int active;
3941 status_t result;
3942 audio_track_cblk_t* cblk = mCblk;
3943 uint32_t framesReq = buffer->frameCount;
3944
Steve Block3856b092011-10-20 11:56:00 +01003945// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946 buffer->frameCount = 0;
3947
3948 uint32_t framesAvail = cblk->framesAvailable();
3949
3950
3951 if (framesAvail == 0) {
3952 Mutex::Autolock _l(cblk->lock);
3953 goto start_loop_here;
3954 while (framesAvail == 0) {
3955 active = mActive;
Glenn Kastenf6b16782011-12-15 09:51:17 -08003956 if (CC_UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003957 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958 return AudioTrack::NO_MORE_BUFFERS;
3959 }
3960 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3961 if (result != NO_ERROR) {
3962 return AudioTrack::NO_MORE_BUFFERS;
3963 }
3964 // read the server count again
3965 start_loop_here:
3966 framesAvail = cblk->framesAvailable_l();
3967 }
3968 }
3969
3970// if (framesAvail < framesReq) {
3971// return AudioTrack::NO_MORE_BUFFERS;
3972// }
3973
3974 if (framesReq > framesAvail) {
3975 framesReq = framesAvail;
3976 }
3977
3978 uint32_t u = cblk->user;
3979 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3980
3981 if (u + framesReq > bufferEnd) {
3982 framesReq = bufferEnd - u;
3983 }
3984
3985 buffer->frameCount = framesReq;
3986 buffer->raw = (void *)cblk->buffer(u);
3987 return NO_ERROR;
3988}
3989
3990
3991void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3992{
3993 size_t size = mBufferQueue.size();
3994 Buffer *pBuffer;
3995
3996 for (size_t i = 0; i < size; i++) {
3997 pBuffer = mBufferQueue.itemAt(i);
3998 delete [] pBuffer->mBuffer;
3999 delete pBuffer;
4000 }
4001 mBufferQueue.clear();
4002}
4003
4004// ----------------------------------------------------------------------------
4005
4006AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4007 : RefBase(),
4008 mAudioFlinger(audioFlinger),
4009 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4010 mPid(pid)
4011{
4012 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4013}
4014
4015// Client destructor must be called with AudioFlinger::mLock held
4016AudioFlinger::Client::~Client()
4017{
4018 mAudioFlinger->removeClient_l(mPid);
4019}
4020
4021const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4022{
4023 return mMemoryDealer;
4024}
4025
4026// ----------------------------------------------------------------------------
4027
4028AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4029 const sp<IAudioFlingerClient>& client,
4030 pid_t pid)
4031 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4032{
4033}
4034
4035AudioFlinger::NotificationClient::~NotificationClient()
4036{
4037 mClient.clear();
4038}
4039
4040void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4041{
4042 sp<NotificationClient> keep(this);
4043 {
4044 mAudioFlinger->removeNotificationClient(mPid);
4045 }
4046}
4047
4048// ----------------------------------------------------------------------------
4049
4050AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4051 : BnAudioTrack(),
4052 mTrack(track)
4053{
4054}
4055
4056AudioFlinger::TrackHandle::~TrackHandle() {
4057 // just stop the track on deletion, associated resources
4058 // will be freed from the main thread once all pending buffers have
4059 // been played. Unless it's not in the active track list, in which
4060 // case we free everything now...
4061 mTrack->destroy();
4062}
4063
4064status_t AudioFlinger::TrackHandle::start() {
4065 return mTrack->start();
4066}
4067
4068void AudioFlinger::TrackHandle::stop() {
4069 mTrack->stop();
4070}
4071
4072void AudioFlinger::TrackHandle::flush() {
4073 mTrack->flush();
4074}
4075
4076void AudioFlinger::TrackHandle::mute(bool e) {
4077 mTrack->mute(e);
4078}
4079
4080void AudioFlinger::TrackHandle::pause() {
4081 mTrack->pause();
4082}
4083
4084void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4085 mTrack->setVolume(left, right);
4086}
4087
4088sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4089 return mTrack->getCblk();
4090}
4091
4092status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4093{
4094 return mTrack->attachAuxEffect(EffectId);
4095}
4096
4097status_t AudioFlinger::TrackHandle::onTransact(
4098 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4099{
4100 return BnAudioTrack::onTransact(code, data, reply, flags);
4101}
4102
4103// ----------------------------------------------------------------------------
4104
4105sp<IAudioRecord> AudioFlinger::openRecord(
4106 pid_t pid,
4107 int input,
4108 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004109 uint32_t format,
4110 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111 int frameCount,
4112 uint32_t flags,
4113 int *sessionId,
4114 status_t *status)
4115{
4116 sp<RecordThread::RecordTrack> recordTrack;
4117 sp<RecordHandle> recordHandle;
4118 sp<Client> client;
4119 wp<Client> wclient;
4120 status_t lStatus;
4121 RecordThread *thread;
4122 size_t inFrameCount;
4123 int lSessionId;
4124
4125 // check calling permissions
4126 if (!recordingAllowed()) {
4127 lStatus = PERMISSION_DENIED;
4128 goto Exit;
4129 }
4130
4131 // add client to list
4132 { // scope for mLock
4133 Mutex::Autolock _l(mLock);
4134 thread = checkRecordThread_l(input);
4135 if (thread == NULL) {
4136 lStatus = BAD_VALUE;
4137 goto Exit;
4138 }
4139
4140 wclient = mClients.valueFor(pid);
4141 if (wclient != NULL) {
4142 client = wclient.promote();
4143 } else {
4144 client = new Client(this, pid);
4145 mClients.add(pid, client);
4146 }
4147
4148 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004149 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004150 lSessionId = *sessionId;
4151 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004152 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004153 if (sessionId != NULL) {
4154 *sessionId = lSessionId;
4155 }
4156 }
4157 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004158 recordTrack = thread->createRecordTrack_l(client,
4159 sampleRate,
4160 format,
4161 channelMask,
4162 frameCount,
4163 flags,
4164 lSessionId,
4165 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004167 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4169 // destructor is called by the TrackBase destructor with mLock held
4170 client.clear();
4171 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172 goto Exit;
4173 }
4174
4175 // return to handle to client
4176 recordHandle = new RecordHandle(recordTrack);
4177 lStatus = NO_ERROR;
4178
4179Exit:
4180 if (status) {
4181 *status = lStatus;
4182 }
4183 return recordHandle;
4184}
4185
4186// ----------------------------------------------------------------------------
4187
4188AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4189 : BnAudioRecord(),
4190 mRecordTrack(recordTrack)
4191{
4192}
4193
4194AudioFlinger::RecordHandle::~RecordHandle() {
4195 stop();
4196}
4197
4198status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004199 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 return mRecordTrack->start();
4201}
4202
4203void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004204 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004205 mRecordTrack->stop();
4206}
4207
4208sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4209 return mRecordTrack->getCblk();
4210}
4211
4212status_t AudioFlinger::RecordHandle::onTransact(
4213 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4214{
4215 return BnAudioRecord::onTransact(code, data, reply, flags);
4216}
4217
4218// ----------------------------------------------------------------------------
4219
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004220AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4221 AudioStreamIn *input,
4222 uint32_t sampleRate,
4223 uint32_t channels,
4224 int id,
4225 uint32_t device) :
4226 ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08004227 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004229 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004230
4231 snprintf(mName, kNameLength, "AudioIn_%d", id);
4232
Dima Zavinfce7a472011-04-19 22:30:36 -07004233 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004234 mReqSampleRate = sampleRate;
4235 readInputParameters();
4236}
4237
4238
4239AudioFlinger::RecordThread::~RecordThread()
4240{
4241 delete[] mRsmpInBuffer;
Glenn Kastene0feee32011-12-13 11:53:26 -08004242 if (mResampler != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243 delete mResampler;
4244 delete[] mRsmpOutBuffer;
4245 }
4246}
4247
4248void AudioFlinger::RecordThread::onFirstRef()
4249{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004250 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251}
4252
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004253status_t AudioFlinger::RecordThread::readyToRun()
4254{
4255 status_t status = initCheck();
4256 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4257 return status;
4258}
4259
Mathias Agopian65ab4712010-07-14 17:59:35 -07004260bool AudioFlinger::RecordThread::threadLoop()
4261{
4262 AudioBufferProvider::Buffer buffer;
4263 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004264 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004265
Eric Laurent44d98482010-09-30 16:12:31 -07004266 nsecs_t lastWarning = 0;
4267
Eric Laurentfeb0db62011-07-22 09:04:31 -07004268 acquireWakeLock();
4269
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270 // start recording
4271 while (!exitPending()) {
4272
4273 processConfigEvents();
4274
4275 { // scope for mLock
4276 Mutex::Autolock _l(mLock);
4277 checkForNewParameters_l();
4278 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4279 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004280 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004281 mStandby = true;
4282 }
4283
4284 if (exitPending()) break;
4285
Eric Laurentfeb0db62011-07-22 09:04:31 -07004286 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004287 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004288 // go to sleep
4289 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004290 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004291 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004292 continue;
4293 }
4294 if (mActiveTrack != 0) {
4295 if (mActiveTrack->mState == TrackBase::PAUSING) {
4296 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004297 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004298 mStandby = true;
4299 }
4300 mActiveTrack.clear();
4301 mStartStopCond.broadcast();
4302 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4303 if (mReqChannelCount != mActiveTrack->channelCount()) {
4304 mActiveTrack.clear();
4305 mStartStopCond.broadcast();
4306 } else if (mBytesRead != 0) {
4307 // record start succeeds only if first read from audio input
4308 // succeeds
4309 if (mBytesRead > 0) {
4310 mActiveTrack->mState = TrackBase::ACTIVE;
4311 } else {
4312 mActiveTrack.clear();
4313 }
4314 mStartStopCond.broadcast();
4315 }
4316 mStandby = false;
4317 }
4318 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004319 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004320 }
4321
4322 if (mActiveTrack != 0) {
4323 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4324 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004325 unlockEffectChains(effectChains);
4326 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004327 continue;
4328 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004329 for (size_t i = 0; i < effectChains.size(); i ++) {
4330 effectChains[i]->process_l();
4331 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004332
Mathias Agopian65ab4712010-07-14 17:59:35 -07004333 buffer.frameCount = mFrameCount;
Glenn Kastenf6b16782011-12-15 09:51:17 -08004334 if (CC_LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004336 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004337 // no resampling
4338 while (framesOut) {
4339 size_t framesIn = mFrameCount - mRsmpInIndex;
4340 if (framesIn) {
4341 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4342 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4343 if (framesIn > framesOut)
4344 framesIn = framesOut;
4345 mRsmpInIndex += framesIn;
4346 framesOut -= framesIn;
4347 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004348 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 memcpy(dst, src, framesIn * mFrameSize);
4350 } else {
4351 int16_t *src16 = (int16_t *)src;
4352 int16_t *dst16 = (int16_t *)dst;
4353 if (mChannelCount == 1) {
4354 while (framesIn--) {
4355 *dst16++ = *src16;
4356 *dst16++ = *src16++;
4357 }
4358 } else {
4359 while (framesIn--) {
4360 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4361 src16 += 2;
4362 }
4363 }
4364 }
4365 }
4366 if (framesOut && mFrameCount == mRsmpInIndex) {
4367 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004368 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004369 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004370 framesOut = 0;
4371 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004372 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004373 mRsmpInIndex = 0;
4374 }
4375 if (mBytesRead < 0) {
4376 LOGE("Error reading audio input");
4377 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4378 // Force input into standby so that it tries to
4379 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004380 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004381 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 }
4383 mRsmpInIndex = mFrameCount;
4384 framesOut = 0;
4385 buffer.frameCount = 0;
4386 }
4387 }
4388 }
4389 } else {
4390 // resampling
4391
4392 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4393 // alter output frame count as if we were expecting stereo samples
4394 if (mChannelCount == 1 && mReqChannelCount == 1) {
4395 framesOut >>= 1;
4396 }
4397 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4398 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4399 // are 32 bit aligned which should be always true.
4400 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004401 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004402 // the resampler always outputs stereo samples: do post stereo to mono conversion
4403 int16_t *src = (int16_t *)mRsmpOutBuffer;
4404 int16_t *dst = buffer.i16;
4405 while (framesOut--) {
4406 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4407 src += 2;
4408 }
4409 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004410 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004411 }
4412
4413 }
4414 mActiveTrack->releaseBuffer(&buffer);
4415 mActiveTrack->overflow();
4416 }
4417 // client isn't retrieving buffers fast enough
4418 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004419 if (!mActiveTrack->setOverflow()) {
4420 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004421 if ((now - lastWarning) > kWarningThrottleNs) {
Eric Laurent44d98482010-09-30 16:12:31 -07004422 LOGW("RecordThread: buffer overflow");
4423 lastWarning = now;
4424 }
4425 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004426 // Release the processor for a while before asking for a new buffer.
4427 // This will give the application more chance to read from the buffer and
4428 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004429 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004430 }
4431 }
Eric Laurentec437d82011-07-26 20:54:46 -07004432 // enable changes in effect chain
4433 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004434 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435 }
4436
4437 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004438 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004439 }
4440 mActiveTrack.clear();
4441
4442 mStartStopCond.broadcast();
4443
Eric Laurentfeb0db62011-07-22 09:04:31 -07004444 releaseWakeLock();
4445
Steve Block3856b092011-10-20 11:56:00 +01004446 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004447 return false;
4448}
4449
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004450
4451sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4452 const sp<AudioFlinger::Client>& client,
4453 uint32_t sampleRate,
4454 int format,
4455 int channelMask,
4456 int frameCount,
4457 uint32_t flags,
4458 int sessionId,
4459 status_t *status)
4460{
4461 sp<RecordTrack> track;
4462 status_t lStatus;
4463
4464 lStatus = initCheck();
4465 if (lStatus != NO_ERROR) {
4466 LOGE("Audio driver not initialized.");
4467 goto Exit;
4468 }
4469
4470 { // scope for mLock
4471 Mutex::Autolock _l(mLock);
4472
4473 track = new RecordTrack(this, client, sampleRate,
4474 format, channelMask, frameCount, flags, sessionId);
4475
4476 if (track->getCblk() == NULL) {
4477 lStatus = NO_MEMORY;
4478 goto Exit;
4479 }
4480
4481 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004482 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4483 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004484 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004485 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4486 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004487 }
4488 lStatus = NO_ERROR;
4489
4490Exit:
4491 if (status) {
4492 *status = lStatus;
4493 }
4494 return track;
4495}
4496
Mathias Agopian65ab4712010-07-14 17:59:35 -07004497status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4498{
Steve Block3856b092011-10-20 11:56:00 +01004499 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004500 sp <ThreadBase> strongMe = this;
4501 status_t status = NO_ERROR;
4502 {
4503 AutoMutex lock(&mLock);
4504 if (mActiveTrack != 0) {
4505 if (recordTrack != mActiveTrack.get()) {
4506 status = -EBUSY;
4507 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4508 mActiveTrack->mState = TrackBase::ACTIVE;
4509 }
4510 return status;
4511 }
4512
4513 recordTrack->mState = TrackBase::IDLE;
4514 mActiveTrack = recordTrack;
4515 mLock.unlock();
4516 status_t status = AudioSystem::startInput(mId);
4517 mLock.lock();
4518 if (status != NO_ERROR) {
4519 mActiveTrack.clear();
4520 return status;
4521 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004522 mRsmpInIndex = mFrameCount;
4523 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004524 if (mResampler != NULL) {
4525 mResampler->reset();
4526 }
4527 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004529 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004530 mWaitWorkCV.signal();
4531 // do not wait for mStartStopCond if exiting
4532 if (mExiting) {
4533 mActiveTrack.clear();
4534 status = INVALID_OPERATION;
4535 goto startError;
4536 }
4537 mStartStopCond.wait(mLock);
4538 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004539 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540 status = BAD_VALUE;
4541 goto startError;
4542 }
Steve Block3856b092011-10-20 11:56:00 +01004543 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004544 return status;
4545 }
4546startError:
4547 AudioSystem::stopInput(mId);
4548 return status;
4549}
4550
4551void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004552 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 sp <ThreadBase> strongMe = this;
4554 {
4555 AutoMutex lock(&mLock);
4556 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4557 mActiveTrack->mState = TrackBase::PAUSING;
4558 // do not wait for mStartStopCond if exiting
4559 if (mExiting) {
4560 return;
4561 }
4562 mStartStopCond.wait(mLock);
4563 // if we have been restarted, recordTrack == mActiveTrack.get() here
4564 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4565 mLock.unlock();
4566 AudioSystem::stopInput(mId);
4567 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004568 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 }
4570 }
4571 }
4572}
4573
4574status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4575{
4576 const size_t SIZE = 256;
4577 char buffer[SIZE];
4578 String8 result;
4579 pid_t pid = 0;
4580
4581 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4582 result.append(buffer);
4583
4584 if (mActiveTrack != 0) {
4585 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004586 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587 mActiveTrack->dump(buffer, SIZE);
4588 result.append(buffer);
4589
4590 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4591 result.append(buffer);
4592 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4593 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004594 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595 result.append(buffer);
4596 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4597 result.append(buffer);
4598 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4599 result.append(buffer);
4600
4601
4602 } else {
4603 result.append("No record client\n");
4604 }
4605 write(fd, result.string(), result.size());
4606
4607 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004608 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004609
4610 return NO_ERROR;
4611}
4612
4613status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4614{
4615 size_t framesReq = buffer->frameCount;
4616 size_t framesReady = mFrameCount - mRsmpInIndex;
4617 int channelCount;
4618
4619 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004620 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004621 if (mBytesRead < 0) {
4622 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4623 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4624 // Force input into standby so that it tries to
4625 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004626 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004627 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004629 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 buffer->frameCount = 0;
4631 return NOT_ENOUGH_DATA;
4632 }
4633 mRsmpInIndex = 0;
4634 framesReady = mFrameCount;
4635 }
4636
4637 if (framesReq > framesReady) {
4638 framesReq = framesReady;
4639 }
4640
4641 if (mChannelCount == 1 && mReqChannelCount == 2) {
4642 channelCount = 1;
4643 } else {
4644 channelCount = 2;
4645 }
4646 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4647 buffer->frameCount = framesReq;
4648 return NO_ERROR;
4649}
4650
4651void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4652{
4653 mRsmpInIndex += buffer->frameCount;
4654 buffer->frameCount = 0;
4655}
4656
4657bool AudioFlinger::RecordThread::checkForNewParameters_l()
4658{
4659 bool reconfig = false;
4660
4661 while (!mNewParameters.isEmpty()) {
4662 status_t status = NO_ERROR;
4663 String8 keyValuePair = mNewParameters[0];
4664 AudioParameter param = AudioParameter(keyValuePair);
4665 int value;
4666 int reqFormat = mFormat;
4667 int reqSamplingRate = mReqSampleRate;
4668 int reqChannelCount = mReqChannelCount;
4669
4670 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4671 reqSamplingRate = value;
4672 reconfig = true;
4673 }
4674 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4675 reqFormat = value;
4676 reconfig = true;
4677 }
4678 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004679 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 reconfig = true;
4681 }
4682 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4683 // do not accept frame count changes if tracks are open as the track buffer
4684 // size depends on frame count and correct behavior would not be garantied
4685 // if frame count is changed after track creation
4686 if (mActiveTrack != 0) {
4687 status = INVALID_OPERATION;
4688 } else {
4689 reconfig = true;
4690 }
4691 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004692 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4693 // forward device change to effects that have requested to be
4694 // aware of attached audio device.
4695 for (size_t i = 0; i < mEffectChains.size(); i++) {
4696 mEffectChains[i]->setDevice_l(value);
4697 }
4698 // store input device and output device but do not forward output device to audio HAL.
4699 // Note that status is ignored by the caller for output device
4700 // (see AudioFlinger::setParameters()
4701 if (value & AUDIO_DEVICE_OUT_ALL) {
4702 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4703 status = BAD_VALUE;
4704 } else {
4705 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004706 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4707 if (mTrack != NULL) {
4708 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004709 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004710 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4711 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4712 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004713 }
4714 mDevice |= (uint32_t)value;
4715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004717 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004718 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004719 mInput->stream->common.standby(&mInput->stream->common);
4720 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004721 }
4722 if (reconfig) {
4723 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004724 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004725 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004726 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4727 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004728 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004729 status = NO_ERROR;
4730 }
4731 if (status == NO_ERROR) {
4732 readInputParameters();
4733 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4734 }
4735 }
4736 }
4737
4738 mNewParameters.removeAt(0);
4739
4740 mParamStatus = status;
4741 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004742 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4743 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004744 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004745 }
4746 return reconfig;
4747}
4748
4749String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4750{
Dima Zavinfce7a472011-04-19 22:30:36 -07004751 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004752 String8 out_s8 = String8();
4753
4754 Mutex::Autolock _l(mLock);
4755 if (initCheck() != NO_ERROR) {
4756 return out_s8;
4757 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004758
Dima Zavin799a70e2011-04-18 16:57:27 -07004759 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004760 out_s8 = String8(s);
4761 free(s);
4762 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004763}
4764
4765void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4766 AudioSystem::OutputDescriptor desc;
4767 void *param2 = 0;
4768
4769 switch (event) {
4770 case AudioSystem::INPUT_OPENED:
4771 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004772 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773 desc.samplingRate = mSampleRate;
4774 desc.format = mFormat;
4775 desc.frameCount = mFrameCount;
4776 desc.latency = 0;
4777 param2 = &desc;
4778 break;
4779
4780 case AudioSystem::INPUT_CLOSED:
4781 default:
4782 break;
4783 }
4784 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4785}
4786
4787void AudioFlinger::RecordThread::readInputParameters()
4788{
4789 if (mRsmpInBuffer) delete mRsmpInBuffer;
4790 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4791 if (mResampler) delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004792 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004793
Dima Zavin799a70e2011-04-18 16:57:27 -07004794 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004795 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4796 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004797 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4798 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4799 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004800 mFrameCount = mInputBytes / mFrameSize;
4801 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4802
4803 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4804 {
4805 int channelCount;
4806 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4807 // stereo to mono post process as the resampler always outputs stereo.
4808 if (mChannelCount == 1 && mReqChannelCount == 2) {
4809 channelCount = 1;
4810 } else {
4811 channelCount = 2;
4812 }
4813 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4814 mResampler->setSampleRate(mSampleRate);
4815 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4816 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4817
4818 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4819 if (mChannelCount == 1 && mReqChannelCount == 1) {
4820 mFrameCount >>= 1;
4821 }
4822
4823 }
4824 mRsmpInIndex = mFrameCount;
4825}
4826
4827unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4828{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004829 Mutex::Autolock _l(mLock);
4830 if (initCheck() != NO_ERROR) {
4831 return 0;
4832 }
4833
Dima Zavin799a70e2011-04-18 16:57:27 -07004834 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004835}
4836
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004837uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4838{
4839 Mutex::Autolock _l(mLock);
4840 uint32_t result = 0;
4841 if (getEffectChain_l(sessionId) != 0) {
4842 result = EFFECT_SESSION;
4843 }
4844
4845 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4846 result |= TRACK_SESSION;
4847 }
4848
4849 return result;
4850}
4851
Eric Laurent59bd0da2011-08-01 09:52:20 -07004852AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4853{
4854 Mutex::Autolock _l(mLock);
4855 return mTrack;
4856}
4857
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004858AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4859{
4860 Mutex::Autolock _l(mLock);
4861 return mInput;
4862}
4863
4864AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4865{
4866 Mutex::Autolock _l(mLock);
4867 AudioStreamIn *input = mInput;
4868 mInput = NULL;
4869 return input;
4870}
4871
4872// this method must always be called either with ThreadBase mLock held or inside the thread loop
4873audio_stream_t* AudioFlinger::RecordThread::stream()
4874{
4875 if (mInput == NULL) {
4876 return NULL;
4877 }
4878 return &mInput->stream->common;
4879}
4880
4881
Mathias Agopian65ab4712010-07-14 17:59:35 -07004882// ----------------------------------------------------------------------------
4883
4884int AudioFlinger::openOutput(uint32_t *pDevices,
4885 uint32_t *pSamplingRate,
4886 uint32_t *pFormat,
4887 uint32_t *pChannels,
4888 uint32_t *pLatencyMs,
4889 uint32_t flags)
4890{
4891 status_t status;
4892 PlaybackThread *thread = NULL;
4893 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4894 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4895 uint32_t format = pFormat ? *pFormat : 0;
4896 uint32_t channels = pChannels ? *pChannels : 0;
4897 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004898 audio_stream_out_t *outStream;
4899 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004900
Steve Block3856b092011-10-20 11:56:00 +01004901 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004902 pDevices ? *pDevices : 0,
4903 samplingRate,
4904 format,
4905 channels,
4906 flags);
4907
4908 if (pDevices == NULL || *pDevices == 0) {
4909 return 0;
4910 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004911
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 Mutex::Autolock _l(mLock);
4913
Dima Zavin799a70e2011-04-18 16:57:27 -07004914 outHwDev = findSuitableHwDev_l(*pDevices);
4915 if (outHwDev == NULL)
4916 return 0;
4917
4918 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4919 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004920 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004921 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 samplingRate,
4923 format,
4924 channels,
4925 status);
4926
4927 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004928 if (outStream != NULL) {
4929 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004930 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004931
Dima Zavinfce7a472011-04-19 22:30:36 -07004932 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4933 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4934 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004936 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004937 } else {
4938 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004939 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004940 }
4941 mPlaybackThreads.add(id, thread);
4942
4943 if (pSamplingRate) *pSamplingRate = samplingRate;
4944 if (pFormat) *pFormat = format;
4945 if (pChannels) *pChannels = channels;
4946 if (pLatencyMs) *pLatencyMs = thread->latency();
4947
4948 // notify client processes of the new output creation
4949 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4950 return id;
4951 }
4952
4953 return 0;
4954}
4955
4956int AudioFlinger::openDuplicateOutput(int output1, int output2)
4957{
4958 Mutex::Autolock _l(mLock);
4959 MixerThread *thread1 = checkMixerThread_l(output1);
4960 MixerThread *thread2 = checkMixerThread_l(output2);
4961
4962 if (thread1 == NULL || thread2 == NULL) {
4963 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4964 return 0;
4965 }
4966
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004967 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004968 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4969 thread->addOutputTrack(thread2);
4970 mPlaybackThreads.add(id, thread);
4971 // notify client processes of the new output creation
4972 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4973 return id;
4974}
4975
4976status_t AudioFlinger::closeOutput(int output)
4977{
4978 // keep strong reference on the playback thread so that
4979 // it is not destroyed while exit() is executed
4980 sp <PlaybackThread> thread;
4981 {
4982 Mutex::Autolock _l(mLock);
4983 thread = checkPlaybackThread_l(output);
4984 if (thread == NULL) {
4985 return BAD_VALUE;
4986 }
4987
Steve Block3856b092011-10-20 11:56:00 +01004988 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004990 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004992 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4994 dupThread->removeOutputTrack((MixerThread *)thread.get());
4995 }
4996 }
4997 }
4998 void *param2 = 0;
4999 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5000 mPlaybackThreads.removeItem(output);
5001 }
5002 thread->exit();
5003
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005004 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005005 AudioStreamOut *out = thread->clearOutput();
5006 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005007 out->hwDev->close_output_stream(out->hwDev, out->stream);
5008 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005009 }
5010 return NO_ERROR;
5011}
5012
5013status_t AudioFlinger::suspendOutput(int output)
5014{
5015 Mutex::Autolock _l(mLock);
5016 PlaybackThread *thread = checkPlaybackThread_l(output);
5017
5018 if (thread == NULL) {
5019 return BAD_VALUE;
5020 }
5021
Steve Block3856b092011-10-20 11:56:00 +01005022 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 thread->suspend();
5024
5025 return NO_ERROR;
5026}
5027
5028status_t AudioFlinger::restoreOutput(int output)
5029{
5030 Mutex::Autolock _l(mLock);
5031 PlaybackThread *thread = checkPlaybackThread_l(output);
5032
5033 if (thread == NULL) {
5034 return BAD_VALUE;
5035 }
5036
Steve Block3856b092011-10-20 11:56:00 +01005037 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005038
5039 thread->restore();
5040
5041 return NO_ERROR;
5042}
5043
5044int AudioFlinger::openInput(uint32_t *pDevices,
5045 uint32_t *pSamplingRate,
5046 uint32_t *pFormat,
5047 uint32_t *pChannels,
5048 uint32_t acoustics)
5049{
5050 status_t status;
5051 RecordThread *thread = NULL;
5052 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5053 uint32_t format = pFormat ? *pFormat : 0;
5054 uint32_t channels = pChannels ? *pChannels : 0;
5055 uint32_t reqSamplingRate = samplingRate;
5056 uint32_t reqFormat = format;
5057 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005058 audio_stream_in_t *inStream;
5059 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005060
5061 if (pDevices == NULL || *pDevices == 0) {
5062 return 0;
5063 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005064
Mathias Agopian65ab4712010-07-14 17:59:35 -07005065 Mutex::Autolock _l(mLock);
5066
Dima Zavin799a70e2011-04-18 16:57:27 -07005067 inHwDev = findSuitableHwDev_l(*pDevices);
5068 if (inHwDev == NULL)
5069 return 0;
5070
5071 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5072 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005073 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005074 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005075 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005076 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005077 samplingRate,
5078 format,
5079 channels,
5080 acoustics,
5081 status);
5082
5083 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5084 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5085 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005086 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005087 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005088 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005089 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005090 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005091 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5092 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005093 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005094 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005095 }
5096
Dima Zavin799a70e2011-04-18 16:57:27 -07005097 if (inStream != NULL) {
5098 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5099
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005100 int id = nextUniqueId();
5101 // Start record thread
5102 // RecorThread require both input and output device indication to forward to audio
5103 // pre processing modules
5104 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5105 thread = new RecordThread(this,
5106 input,
5107 reqSamplingRate,
5108 reqChannels,
5109 id,
5110 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005112 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005113 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5114 if (pFormat) *pFormat = format;
5115 if (pChannels) *pChannels = reqChannels;
5116
Dima Zavin799a70e2011-04-18 16:57:27 -07005117 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005118
5119 // notify client processes of the new input creation
5120 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5121 return id;
5122 }
5123
5124 return 0;
5125}
5126
5127status_t AudioFlinger::closeInput(int input)
5128{
5129 // keep strong reference on the record thread so that
5130 // it is not destroyed while exit() is executed
5131 sp <RecordThread> thread;
5132 {
5133 Mutex::Autolock _l(mLock);
5134 thread = checkRecordThread_l(input);
5135 if (thread == NULL) {
5136 return BAD_VALUE;
5137 }
5138
Steve Block3856b092011-10-20 11:56:00 +01005139 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005140 void *param2 = 0;
5141 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5142 mRecordThreads.removeItem(input);
5143 }
5144 thread->exit();
5145
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005146 AudioStreamIn *in = thread->clearInput();
5147 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005148 in->hwDev->close_input_stream(in->hwDev, in->stream);
5149 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005150
5151 return NO_ERROR;
5152}
5153
5154status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5155{
5156 Mutex::Autolock _l(mLock);
5157 MixerThread *dstThread = checkMixerThread_l(output);
5158 if (dstThread == NULL) {
5159 LOGW("setStreamOutput() bad output id %d", output);
5160 return BAD_VALUE;
5161 }
5162
Steve Block3856b092011-10-20 11:56:00 +01005163 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005164 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5165
Eric Laurent9f6530f2011-08-30 10:18:54 -07005166 dstThread->setStreamValid(stream, true);
5167
Mathias Agopian65ab4712010-07-14 17:59:35 -07005168 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5169 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5170 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005171 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005173 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005174 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 }
Eric Laurentde070132010-07-13 04:45:46 -07005176 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177
5178 return NO_ERROR;
5179}
5180
5181
5182int AudioFlinger::newAudioSessionId()
5183{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005184 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005185}
5186
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005187void AudioFlinger::acquireAudioSessionId(int audioSession)
5188{
5189 Mutex::Autolock _l(mLock);
5190 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005191 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005192 int num = mAudioSessionRefs.size();
5193 for (int i = 0; i< num; i++) {
5194 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5195 if (ref->sessionid == audioSession && ref->pid == caller) {
5196 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005197 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005198 return;
5199 }
5200 }
5201 AudioSessionRef *ref = new AudioSessionRef();
5202 ref->sessionid = audioSession;
5203 ref->pid = caller;
5204 ref->cnt = 1;
5205 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005206 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005207}
5208
5209void AudioFlinger::releaseAudioSessionId(int audioSession)
5210{
5211 Mutex::Autolock _l(mLock);
5212 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005213 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005214 int num = mAudioSessionRefs.size();
5215 for (int i = 0; i< num; i++) {
5216 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5217 if (ref->sessionid == audioSession && ref->pid == caller) {
5218 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005219 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005220 if (ref->cnt == 0) {
5221 mAudioSessionRefs.removeAt(i);
5222 delete ref;
5223 purgeStaleEffects_l();
5224 }
5225 return;
5226 }
5227 }
5228 LOGW("session id %d not found for pid %d", audioSession, caller);
5229}
5230
5231void AudioFlinger::purgeStaleEffects_l() {
5232
Steve Block3856b092011-10-20 11:56:00 +01005233 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005234
5235 Vector< sp<EffectChain> > chains;
5236
5237 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5238 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5239 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5240 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005241 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5242 chains.push(ec);
5243 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005244 }
5245 }
5246 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5247 sp<RecordThread> t = mRecordThreads.valueAt(i);
5248 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5249 sp<EffectChain> ec = t->mEffectChains[j];
5250 chains.push(ec);
5251 }
5252 }
5253
5254 for (size_t i = 0; i < chains.size(); i++) {
5255 sp<EffectChain> ec = chains[i];
5256 int sessionid = ec->sessionId();
5257 sp<ThreadBase> t = ec->mThread.promote();
5258 if (t == 0) {
5259 continue;
5260 }
5261 size_t numsessionrefs = mAudioSessionRefs.size();
5262 bool found = false;
5263 for (size_t k = 0; k < numsessionrefs; k++) {
5264 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5265 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005266 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005267 sessionid, ref->pid, ref->cnt);
5268 found = true;
5269 break;
5270 }
5271 }
5272 if (!found) {
5273 // remove all effects from the chain
5274 while (ec->mEffects.size()) {
5275 sp<EffectModule> effect = ec->mEffects[0];
5276 effect->unPin();
5277 Mutex::Autolock _l (t->mLock);
5278 t->removeEffect_l(effect);
5279 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5280 sp<EffectHandle> handle = effect->mHandles[j].promote();
5281 if (handle != 0) {
5282 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005283 if (handle->mHasControl && handle->mEnabled) {
5284 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5285 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005286 }
5287 }
5288 AudioSystem::unregisterEffect(effect->id());
5289 }
5290 }
5291 }
5292 return;
5293}
5294
Mathias Agopian65ab4712010-07-14 17:59:35 -07005295// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5296AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5297{
5298 PlaybackThread *thread = NULL;
5299 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5300 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5301 }
5302 return thread;
5303}
5304
5305// checkMixerThread_l() must be called with AudioFlinger::mLock held
5306AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5307{
5308 PlaybackThread *thread = checkPlaybackThread_l(output);
5309 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005310 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005311 thread = NULL;
5312 }
5313 }
5314 return (MixerThread *)thread;
5315}
5316
5317// checkRecordThread_l() must be called with AudioFlinger::mLock held
5318AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5319{
5320 RecordThread *thread = NULL;
5321 if (mRecordThreads.indexOfKey(input) >= 0) {
5322 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5323 }
5324 return thread;
5325}
5326
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005327uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005329 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005330}
5331
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005332AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5333{
5334 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5335 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005336 AudioStreamOut *output = thread->getOutput();
5337 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005338 return thread;
5339 }
5340 }
5341 return NULL;
5342}
5343
5344uint32_t AudioFlinger::primaryOutputDevice_l()
5345{
5346 PlaybackThread *thread = primaryPlaybackThread_l();
5347
5348 if (thread == NULL) {
5349 return 0;
5350 }
5351
5352 return thread->device();
5353}
5354
5355
Mathias Agopian65ab4712010-07-14 17:59:35 -07005356// ----------------------------------------------------------------------------
5357// Effect management
5358// ----------------------------------------------------------------------------
5359
5360
Mathias Agopian65ab4712010-07-14 17:59:35 -07005361status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5362{
5363 Mutex::Autolock _l(mLock);
5364 return EffectQueryNumberEffects(numEffects);
5365}
5366
5367status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5368{
5369 Mutex::Autolock _l(mLock);
5370 return EffectQueryEffect(index, descriptor);
5371}
5372
5373status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5374{
5375 Mutex::Autolock _l(mLock);
5376 return EffectGetDescriptor(pUuid, descriptor);
5377}
5378
5379
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5381 effect_descriptor_t *pDesc,
5382 const sp<IEffectClient>& effectClient,
5383 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005384 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385 int sessionId,
5386 status_t *status,
5387 int *id,
5388 int *enabled)
5389{
5390 status_t lStatus = NO_ERROR;
5391 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 effect_descriptor_t desc;
5393 sp<Client> client;
5394 wp<Client> wclient;
5395
Steve Block3856b092011-10-20 11:56:00 +01005396 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005397 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005398
5399 if (pDesc == NULL) {
5400 lStatus = BAD_VALUE;
5401 goto Exit;
5402 }
5403
Eric Laurent84e9a102010-09-23 16:10:16 -07005404 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005405 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005406 lStatus = PERMISSION_DENIED;
5407 goto Exit;
5408 }
5409
Dima Zavinfce7a472011-04-19 22:30:36 -07005410 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005411 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005412 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005413 lStatus = PERMISSION_DENIED;
5414 goto Exit;
5415 }
5416
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005417 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005418 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005419 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005420 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005421 lStatus = BAD_VALUE;
5422 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005423 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005424 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005425 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005426 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005427 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005428 }
5429 }
5430
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 {
5432 Mutex::Autolock _l(mLock);
5433
Mathias Agopian65ab4712010-07-14 17:59:35 -07005434
5435 if (!EffectIsNullUuid(&pDesc->uuid)) {
5436 // if uuid is specified, request effect descriptor
5437 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5438 if (lStatus < 0) {
5439 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5440 goto Exit;
5441 }
5442 } else {
5443 // if uuid is not specified, look for an available implementation
5444 // of the required type in effect factory
5445 if (EffectIsNullUuid(&pDesc->type)) {
5446 LOGW("createEffect() no effect type");
5447 lStatus = BAD_VALUE;
5448 goto Exit;
5449 }
5450 uint32_t numEffects = 0;
5451 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005452 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 bool found = false;
5454
5455 lStatus = EffectQueryNumberEffects(&numEffects);
5456 if (lStatus < 0) {
5457 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5458 goto Exit;
5459 }
5460 for (uint32_t i = 0; i < numEffects; i++) {
5461 lStatus = EffectQueryEffect(i, &desc);
5462 if (lStatus < 0) {
5463 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5464 continue;
5465 }
5466 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5467 // If matching type found save effect descriptor. If the session is
5468 // 0 and the effect is not auxiliary, continue enumeration in case
5469 // an auxiliary version of this effect type is available
5470 found = true;
5471 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005472 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5474 break;
5475 }
5476 }
5477 }
5478 if (!found) {
5479 lStatus = BAD_VALUE;
5480 LOGW("createEffect() effect not found");
5481 goto Exit;
5482 }
5483 // For same effect type, chose auxiliary version over insert version if
5484 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005485 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005486 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5487 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5488 }
5489 }
5490
5491 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005492 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005493 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5494 lStatus = INVALID_OPERATION;
5495 goto Exit;
5496 }
5497
Eric Laurent59255e42011-07-27 19:49:51 -07005498 // check recording permission for visualizer
5499 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5500 !recordingAllowed()) {
5501 lStatus = PERMISSION_DENIED;
5502 goto Exit;
5503 }
5504
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 // return effect descriptor
5506 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5507
5508 // If output is not specified try to find a matching audio session ID in one of the
5509 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005510 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5511 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005512 // Note: io is never 0 when creating an effect on an input
5513 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005514 // look for the thread where the specified audio session is present
5515 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5516 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005517 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005518 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005521 if (io == 0) {
5522 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5523 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5524 io = mRecordThreads.keyAt(i);
5525 break;
5526 }
5527 }
5528 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005529 // If no output thread contains the requested session ID, default to
5530 // first output. The effect chain will be moved to the correct output
5531 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005532 if (io == 0 && mPlaybackThreads.size()) {
5533 io = mPlaybackThreads.keyAt(0);
5534 }
Steve Block3856b092011-10-20 11:56:00 +01005535 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005536 }
5537 ThreadBase *thread = checkRecordThread_l(io);
5538 if (thread == NULL) {
5539 thread = checkPlaybackThread_l(io);
5540 if (thread == NULL) {
5541 LOGE("createEffect() unknown output thread");
5542 lStatus = BAD_VALUE;
5543 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005544 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005546
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 wclient = mClients.valueFor(pid);
5548
5549 if (wclient != NULL) {
5550 client = wclient.promote();
5551 } else {
5552 client = new Client(this, pid);
5553 mClients.add(pid, client);
5554 }
5555
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005556 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005557 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5558 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 if (handle != 0 && id != NULL) {
5560 *id = handle->id();
5561 }
5562 }
5563
5564Exit:
5565 if(status) {
5566 *status = lStatus;
5567 }
5568 return handle;
5569}
5570
Eric Laurent59255e42011-07-27 19:49:51 -07005571status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005572{
Steve Block3856b092011-10-20 11:56:00 +01005573 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005574 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005575 Mutex::Autolock _l(mLock);
5576 if (srcOutput == dstOutput) {
5577 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5578 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005579 }
Eric Laurentde070132010-07-13 04:45:46 -07005580 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5581 if (srcThread == NULL) {
5582 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5583 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584 }
Eric Laurentde070132010-07-13 04:45:46 -07005585 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5586 if (dstThread == NULL) {
5587 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5588 return BAD_VALUE;
5589 }
5590
5591 Mutex::Autolock _dl(dstThread->mLock);
5592 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005593 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005594
Mathias Agopian65ab4712010-07-14 17:59:35 -07005595 return NO_ERROR;
5596}
5597
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005598// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005599status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005600 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005601 AudioFlinger::PlaybackThread *dstThread,
5602 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005603{
Steve Block3856b092011-10-20 11:56:00 +01005604 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005605 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005606
Eric Laurent59255e42011-07-27 19:49:51 -07005607 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005608 if (chain == 0) {
5609 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005610 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005611 return INVALID_OPERATION;
5612 }
5613
Eric Laurent39e94f82010-07-28 01:32:47 -07005614 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005615 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005616 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005617 // removed.
5618 srcThread->removeEffectChain_l(chain);
5619
5620 // transfer all effects one by one so that new effect chain is created on new thread with
5621 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005622 int dstOutput = dstThread->id();
5623 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005624 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005625 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5626 while (effect != 0) {
5627 srcThread->removeEffect_l(effect);
5628 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005629 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5630 if (effect->state() == EffectModule::ACTIVE ||
5631 effect->state() == EffectModule::STOPPING) {
5632 effect->start();
5633 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005634 // if the move request is not received from audio policy manager, the effect must be
5635 // re-registered with the new strategy and output
5636 if (dstChain == 0) {
5637 dstChain = effect->chain().promote();
5638 if (dstChain == 0) {
5639 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5640 srcThread->addEffect_l(effect);
5641 return NO_INIT;
5642 }
5643 strategy = dstChain->strategy();
5644 }
5645 if (reRegister) {
5646 AudioSystem::unregisterEffect(effect->id());
5647 AudioSystem::registerEffect(&effect->desc(),
5648 dstOutput,
5649 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005650 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005651 effect->id());
5652 }
Eric Laurentde070132010-07-13 04:45:46 -07005653 effect = chain->getEffectFromId_l(0);
5654 }
5655
5656 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657}
5658
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005659
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005661sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005662 const sp<AudioFlinger::Client>& client,
5663 const sp<IEffectClient>& effectClient,
5664 int32_t priority,
5665 int sessionId,
5666 effect_descriptor_t *desc,
5667 int *enabled,
5668 status_t *status
5669 )
5670{
5671 sp<EffectModule> effect;
5672 sp<EffectHandle> handle;
5673 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005675 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 bool effectCreated = false;
5677 bool effectRegistered = false;
5678
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005679 lStatus = initCheck();
5680 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005682 goto Exit;
5683 }
5684
5685 // Do not allow effects with session ID 0 on direct output or duplicating threads
5686 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005687 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005688 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5689 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005690 lStatus = BAD_VALUE;
5691 goto Exit;
5692 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005693 // Only Pre processor effects are allowed on input threads and only on input threads
5694 if ((mType == RECORD &&
5695 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5696 (mType != RECORD &&
5697 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5698 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5699 desc->name, desc->flags, mType);
5700 lStatus = BAD_VALUE;
5701 goto Exit;
5702 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703
Steve Block3856b092011-10-20 11:56:00 +01005704 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005705
5706 { // scope for mLock
5707 Mutex::Autolock _l(mLock);
5708
5709 // check for existing effect chain with the requested audio session
5710 chain = getEffectChain_l(sessionId);
5711 if (chain == 0) {
5712 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005713 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005714 chain = new EffectChain(this, sessionId);
5715 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005716 chain->setStrategy(getStrategyForSession_l(sessionId));
5717 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005719 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005720 }
5721
Steve Block3856b092011-10-20 11:56:00 +01005722 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723
5724 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005725 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005727 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005728 if (lStatus != NO_ERROR) {
5729 goto Exit;
5730 }
5731 effectRegistered = true;
5732 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005733 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005734 lStatus = effect->status();
5735 if (lStatus != NO_ERROR) {
5736 goto Exit;
5737 }
Eric Laurentcab11242010-07-15 12:50:15 -07005738 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005739 if (lStatus != NO_ERROR) {
5740 goto Exit;
5741 }
5742 effectCreated = true;
5743
5744 effect->setDevice(mDevice);
5745 effect->setMode(mAudioFlinger->getMode());
5746 }
5747 // create effect handle and connect it to effect module
5748 handle = new EffectHandle(effect, client, effectClient, priority);
5749 lStatus = effect->addHandle(handle);
5750 if (enabled) {
5751 *enabled = (int)effect->isEnabled();
5752 }
5753 }
5754
5755Exit:
5756 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005757 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005759 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005760 }
5761 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005762 AudioSystem::unregisterEffect(effect->id());
5763 }
5764 if (chainCreated) {
5765 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005766 }
5767 handle.clear();
5768 }
5769
5770 if(status) {
5771 *status = lStatus;
5772 }
5773 return handle;
5774}
5775
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005776sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5777{
5778 sp<EffectModule> effect;
5779
5780 sp<EffectChain> chain = getEffectChain_l(sessionId);
5781 if (chain != 0) {
5782 effect = chain->getEffectFromId_l(effectId);
5783 }
5784 return effect;
5785}
5786
Eric Laurentde070132010-07-13 04:45:46 -07005787// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5788// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005789status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005790{
5791 // check for existing effect chain with the requested audio session
5792 int sessionId = effect->sessionId();
5793 sp<EffectChain> chain = getEffectChain_l(sessionId);
5794 bool chainCreated = false;
5795
5796 if (chain == 0) {
5797 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005798 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005799 chain = new EffectChain(this, sessionId);
5800 addEffectChain_l(chain);
5801 chain->setStrategy(getStrategyForSession_l(sessionId));
5802 chainCreated = true;
5803 }
Steve Block3856b092011-10-20 11:56:00 +01005804 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005805
5806 if (chain->getEffectFromId_l(effect->id()) != 0) {
5807 LOGW("addEffect_l() %p effect %s already present in chain %p",
5808 this, effect->desc().name, chain.get());
5809 return BAD_VALUE;
5810 }
5811
5812 status_t status = chain->addEffect_l(effect);
5813 if (status != NO_ERROR) {
5814 if (chainCreated) {
5815 removeEffectChain_l(chain);
5816 }
5817 return status;
5818 }
5819
5820 effect->setDevice(mDevice);
5821 effect->setMode(mAudioFlinger->getMode());
5822 return NO_ERROR;
5823}
5824
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005825void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005826
Steve Block3856b092011-10-20 11:56:00 +01005827 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005829 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5830 detachAuxEffect_l(effect->id());
5831 }
5832
5833 sp<EffectChain> chain = effect->chain().promote();
5834 if (chain != 0) {
5835 // remove effect chain if removing last effect
5836 if (chain->removeEffect_l(effect) == 0) {
5837 removeEffectChain_l(chain);
5838 }
5839 } else {
5840 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5841 }
5842}
5843
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005844void AudioFlinger::ThreadBase::lockEffectChains_l(
5845 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5846{
5847 effectChains = mEffectChains;
5848 for (size_t i = 0; i < mEffectChains.size(); i++) {
5849 mEffectChains[i]->lock();
5850 }
5851}
5852
5853void AudioFlinger::ThreadBase::unlockEffectChains(
5854 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5855{
5856 for (size_t i = 0; i < effectChains.size(); i++) {
5857 effectChains[i]->unlock();
5858 }
5859}
5860
5861sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5862{
5863 Mutex::Autolock _l(mLock);
5864 return getEffectChain_l(sessionId);
5865}
5866
5867sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5868{
5869 sp<EffectChain> chain;
5870
5871 size_t size = mEffectChains.size();
5872 for (size_t i = 0; i < size; i++) {
5873 if (mEffectChains[i]->sessionId() == sessionId) {
5874 chain = mEffectChains[i];
5875 break;
5876 }
5877 }
5878 return chain;
5879}
5880
5881void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5882{
5883 Mutex::Autolock _l(mLock);
5884 size_t size = mEffectChains.size();
5885 for (size_t i = 0; i < size; i++) {
5886 mEffectChains[i]->setMode_l(mode);
5887 }
5888}
5889
5890void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005891 const wp<EffectHandle>& handle,
5892 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005893
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005895 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005896 // delete the effect module if removing last handle on it
5897 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005898 if (!effect->isPinned() || unpiniflast) {
5899 removeEffect_l(effect);
5900 AudioSystem::unregisterEffect(effect->id());
5901 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005902 }
5903}
5904
5905status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5906{
5907 int session = chain->sessionId();
5908 int16_t *buffer = mMixBuffer;
5909 bool ownsBuffer = false;
5910
Steve Block3856b092011-10-20 11:56:00 +01005911 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005912 if (session > 0) {
5913 // Only one effect chain can be present in direct output thread and it uses
5914 // the mix buffer as input
5915 if (mType != DIRECT) {
5916 size_t numSamples = mFrameCount * mChannelCount;
5917 buffer = new int16_t[numSamples];
5918 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005919 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 ownsBuffer = true;
5921 }
5922
5923 // Attach all tracks with same session ID to this chain.
5924 for (size_t i = 0; i < mTracks.size(); ++i) {
5925 sp<Track> track = mTracks[i];
5926 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005927 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005929 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930 }
5931 }
5932
5933 // indicate all active tracks in the chain
5934 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5935 sp<Track> track = mActiveTracks[i].promote();
5936 if (track == 0) continue;
5937 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005938 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005939 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005940 }
5941 }
5942 }
5943
5944 chain->setInBuffer(buffer, ownsBuffer);
5945 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005946 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005947 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005948 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5949 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005950 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005951 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5952 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005953 // Effect chain for other sessions are inserted at beginning of effect
5954 // chains list to be processed before output mix effects. Relative order between other
5955 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 size_t size = mEffectChains.size();
5957 size_t i = 0;
5958 for (i = 0; i < size; i++) {
5959 if (mEffectChains[i]->sessionId() < session) break;
5960 }
5961 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005962 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005963
5964 return NO_ERROR;
5965}
5966
5967size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5968{
5969 int session = chain->sessionId();
5970
Steve Block3856b092011-10-20 11:56:00 +01005971 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972
5973 for (size_t i = 0; i < mEffectChains.size(); i++) {
5974 if (chain == mEffectChains[i]) {
5975 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005976 // detach all active tracks from the chain
5977 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5978 sp<Track> track = mActiveTracks[i].promote();
5979 if (track == 0) continue;
5980 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005981 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005982 chain.get(), session);
5983 chain->decActiveTrackCnt();
5984 }
5985 }
5986
Mathias Agopian65ab4712010-07-14 17:59:35 -07005987 // detach all tracks with same session ID from this chain
5988 for (size_t i = 0; i < mTracks.size(); ++i) {
5989 sp<Track> track = mTracks[i];
5990 if (session == track->sessionId()) {
5991 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005992 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005993 }
5994 }
Eric Laurentde070132010-07-13 04:45:46 -07005995 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 }
5997 }
5998 return mEffectChains.size();
5999}
6000
Eric Laurentde070132010-07-13 04:45:46 -07006001status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6002 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003{
6004 Mutex::Autolock _l(mLock);
6005 return attachAuxEffect_l(track, EffectId);
6006}
6007
Eric Laurentde070132010-07-13 04:45:46 -07006008status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6009 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010{
6011 status_t status = NO_ERROR;
6012
6013 if (EffectId == 0) {
6014 track->setAuxBuffer(0, NULL);
6015 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006016 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6017 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006018 if (effect != 0) {
6019 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6020 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6021 } else {
6022 status = INVALID_OPERATION;
6023 }
6024 } else {
6025 status = BAD_VALUE;
6026 }
6027 }
6028 return status;
6029}
6030
6031void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6032{
6033 for (size_t i = 0; i < mTracks.size(); ++i) {
6034 sp<Track> track = mTracks[i];
6035 if (track->auxEffectId() == effectId) {
6036 attachAuxEffect_l(track, 0);
6037 }
6038 }
6039}
6040
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006041status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6042{
6043 // only one chain per input thread
6044 if (mEffectChains.size() != 0) {
6045 return INVALID_OPERATION;
6046 }
Steve Block3856b092011-10-20 11:56:00 +01006047 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006048
6049 chain->setInBuffer(NULL);
6050 chain->setOutBuffer(NULL);
6051
Eric Laurent59255e42011-07-27 19:49:51 -07006052 checkSuspendOnAddEffectChain_l(chain);
6053
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006054 mEffectChains.add(chain);
6055
6056 return NO_ERROR;
6057}
6058
6059size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6060{
Steve Block3856b092011-10-20 11:56:00 +01006061 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006062 LOGW_IF(mEffectChains.size() != 1,
6063 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6064 chain.get(), mEffectChains.size(), this);
6065 if (mEffectChains.size() == 1) {
6066 mEffectChains.removeAt(0);
6067 }
6068 return 0;
6069}
6070
Mathias Agopian65ab4712010-07-14 17:59:35 -07006071// ----------------------------------------------------------------------------
6072// EffectModule implementation
6073// ----------------------------------------------------------------------------
6074
6075#undef LOG_TAG
6076#define LOG_TAG "AudioFlinger::EffectModule"
6077
6078AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6079 const wp<AudioFlinger::EffectChain>& chain,
6080 effect_descriptor_t *desc,
6081 int id,
6082 int sessionId)
6083 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006084 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085{
Steve Block3856b092011-10-20 11:56:00 +01006086 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087 int lStatus;
6088 sp<ThreadBase> thread = mThread.promote();
6089 if (thread == 0) {
6090 return;
6091 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006092
6093 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6094
6095 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006096 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006097
6098 if (mStatus != NO_ERROR) {
6099 return;
6100 }
6101 lStatus = init();
6102 if (lStatus < 0) {
6103 mStatus = lStatus;
6104 goto Error;
6105 }
6106
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006107 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6108 mPinned = true;
6109 }
Steve Block3856b092011-10-20 11:56:00 +01006110 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 return;
6112Error:
6113 EffectRelease(mEffectInterface);
6114 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006115 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006116}
6117
6118AudioFlinger::EffectModule::~EffectModule()
6119{
Steve Block3856b092011-10-20 11:56:00 +01006120 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006122 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6123 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6124 sp<ThreadBase> thread = mThread.promote();
6125 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006126 audio_stream_t *stream = thread->stream();
6127 if (stream != NULL) {
6128 stream->remove_audio_effect(stream, mEffectInterface);
6129 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006130 }
6131 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006132 // release effect engine
6133 EffectRelease(mEffectInterface);
6134 }
6135}
6136
6137status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6138{
6139 status_t status;
6140
6141 Mutex::Autolock _l(mLock);
6142 // First handle in mHandles has highest priority and controls the effect module
6143 int priority = handle->priority();
6144 size_t size = mHandles.size();
6145 sp<EffectHandle> h;
6146 size_t i;
6147 for (i = 0; i < size; i++) {
6148 h = mHandles[i].promote();
6149 if (h == 0) continue;
6150 if (h->priority() <= priority) break;
6151 }
6152 // if inserted in first place, move effect control from previous owner to this handle
6153 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006154 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006156 enabled = h->enabled();
6157 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 }
Eric Laurent59255e42011-07-27 19:49:51 -07006159 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 status = NO_ERROR;
6161 } else {
6162 status = ALREADY_EXISTS;
6163 }
Steve Block3856b092011-10-20 11:56:00 +01006164 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006165 mHandles.insertAt(handle, i);
6166 return status;
6167}
6168
6169size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6170{
6171 Mutex::Autolock _l(mLock);
6172 size_t size = mHandles.size();
6173 size_t i;
6174 for (i = 0; i < size; i++) {
6175 if (mHandles[i] == handle) break;
6176 }
6177 if (i == size) {
6178 return size;
6179 }
Steve Block3856b092011-10-20 11:56:00 +01006180 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006181
6182 bool enabled = false;
6183 EffectHandle *hdl = handle.unsafe_get();
6184 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006185 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006186 enabled = hdl->enabled();
6187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006188 mHandles.removeAt(i);
6189 size = mHandles.size();
6190 // if removed from first place, move effect control from this handle to next in line
6191 if (i == 0 && size != 0) {
6192 sp<EffectHandle> h = mHandles[0].promote();
6193 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006194 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006195 }
6196 }
6197
Eric Laurentec437d82011-07-26 20:54:46 -07006198 // Prevent calls to process() and other functions on effect interface from now on.
6199 // The effect engine will be released by the destructor when the last strong reference on
6200 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006201 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006202 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006203 }
6204
Mathias Agopian65ab4712010-07-14 17:59:35 -07006205 return size;
6206}
6207
Eric Laurent59255e42011-07-27 19:49:51 -07006208sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6209{
6210 Mutex::Autolock _l(mLock);
6211 sp<EffectHandle> handle;
6212 if (mHandles.size() != 0) {
6213 handle = mHandles[0].promote();
6214 }
6215 return handle;
6216}
6217
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006218void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219{
Steve Block3856b092011-10-20 11:56:00 +01006220 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006221 // keep a strong reference on this EffectModule to avoid calling the
6222 // destructor before we exit
6223 sp<EffectModule> keep(this);
6224 {
6225 sp<ThreadBase> thread = mThread.promote();
6226 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006227 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006228 }
6229 }
6230}
6231
6232void AudioFlinger::EffectModule::updateState() {
6233 Mutex::Autolock _l(mLock);
6234
6235 switch (mState) {
6236 case RESTART:
6237 reset_l();
6238 // FALL THROUGH
6239
6240 case STARTING:
6241 // clear auxiliary effect input buffer for next accumulation
6242 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6243 memset(mConfig.inputCfg.buffer.raw,
6244 0,
6245 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6246 }
6247 start_l();
6248 mState = ACTIVE;
6249 break;
6250 case STOPPING:
6251 stop_l();
6252 mDisableWaitCnt = mMaxDisableWaitCnt;
6253 mState = STOPPED;
6254 break;
6255 case STOPPED:
6256 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6257 // turn off sequence.
6258 if (--mDisableWaitCnt == 0) {
6259 reset_l();
6260 mState = IDLE;
6261 }
6262 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006263 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006264 break;
6265 }
6266}
6267
6268void AudioFlinger::EffectModule::process()
6269{
6270 Mutex::Autolock _l(mLock);
6271
Eric Laurentec437d82011-07-26 20:54:46 -07006272 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006273 mConfig.inputCfg.buffer.raw == NULL ||
6274 mConfig.outputCfg.buffer.raw == NULL) {
6275 return;
6276 }
6277
Eric Laurent8f45bd72010-08-31 13:50:07 -07006278 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6280 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006281 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006283 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006284 }
6285
6286 // do the actual processing in the effect engine
6287 int ret = (*mEffectInterface)->process(mEffectInterface,
6288 &mConfig.inputCfg.buffer,
6289 &mConfig.outputCfg.buffer);
6290
6291 // force transition to IDLE state when engine is ready
6292 if (mState == STOPPED && ret == -ENODATA) {
6293 mDisableWaitCnt = 1;
6294 }
6295
6296 // clear auxiliary effect input buffer for next accumulation
6297 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006298 memset(mConfig.inputCfg.buffer.raw, 0,
6299 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006300 }
6301 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006302 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6303 // If an insert effect is idle and input buffer is different from output buffer,
6304 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006305 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006306 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006307 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6308 int16_t *in = mConfig.inputCfg.buffer.s16;
6309 int16_t *out = mConfig.outputCfg.buffer.s16;
6310 for (size_t i = 0; i < frameCnt; i++) {
6311 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006313 }
6314 }
6315}
6316
6317void AudioFlinger::EffectModule::reset_l()
6318{
6319 if (mEffectInterface == NULL) {
6320 return;
6321 }
6322 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6323}
6324
6325status_t AudioFlinger::EffectModule::configure()
6326{
6327 uint32_t channels;
6328 if (mEffectInterface == NULL) {
6329 return NO_INIT;
6330 }
6331
6332 sp<ThreadBase> thread = mThread.promote();
6333 if (thread == 0) {
6334 return DEAD_OBJECT;
6335 }
6336
6337 // TODO: handle configuration of effects replacing track process
6338 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006339 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006341 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006342 }
6343
6344 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006345 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006346 } else {
6347 mConfig.inputCfg.channels = channels;
6348 }
6349 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006350 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6351 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006352 mConfig.inputCfg.samplingRate = thread->sampleRate();
6353 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6354 mConfig.inputCfg.bufferProvider.cookie = NULL;
6355 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6356 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6357 mConfig.outputCfg.bufferProvider.cookie = NULL;
6358 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6359 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6360 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6361 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006362 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006363 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006364 // - in other sessions:
6365 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6366 // other effect: overwrites output buffer: input buffer == output buffer
6367 // Auxiliary effect:
6368 // accumulates in output buffer: input buffer != output buffer
6369 // Therefore: accumulate <=> input buffer != output buffer
6370 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6371 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6372 } else {
6373 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6374 }
6375 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6376 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6377 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6378 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6379
Steve Block3856b092011-10-20 11:56:00 +01006380 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006381 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6382
Mathias Agopian65ab4712010-07-14 17:59:35 -07006383 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006384 uint32_t size = sizeof(int);
6385 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006386 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006387 sizeof(effect_config_t),
6388 &mConfig,
6389 &size,
6390 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006391 if (status == 0) {
6392 status = cmdStatus;
6393 }
6394
6395 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6396 (1000 * mConfig.outputCfg.buffer.frameCount);
6397
6398 return status;
6399}
6400
6401status_t AudioFlinger::EffectModule::init()
6402{
6403 Mutex::Autolock _l(mLock);
6404 if (mEffectInterface == NULL) {
6405 return NO_INIT;
6406 }
6407 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006408 uint32_t size = sizeof(status_t);
6409 status_t status = (*mEffectInterface)->command(mEffectInterface,
6410 EFFECT_CMD_INIT,
6411 0,
6412 NULL,
6413 &size,
6414 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006415 if (status == 0) {
6416 status = cmdStatus;
6417 }
6418 return status;
6419}
6420
Eric Laurentec35a142011-10-05 17:42:25 -07006421status_t AudioFlinger::EffectModule::start()
6422{
6423 Mutex::Autolock _l(mLock);
6424 return start_l();
6425}
6426
Mathias Agopian65ab4712010-07-14 17:59:35 -07006427status_t AudioFlinger::EffectModule::start_l()
6428{
6429 if (mEffectInterface == NULL) {
6430 return NO_INIT;
6431 }
6432 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006433 uint32_t size = sizeof(status_t);
6434 status_t status = (*mEffectInterface)->command(mEffectInterface,
6435 EFFECT_CMD_ENABLE,
6436 0,
6437 NULL,
6438 &size,
6439 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006440 if (status == 0) {
6441 status = cmdStatus;
6442 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006443 if (status == 0 &&
6444 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6445 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6446 sp<ThreadBase> thread = mThread.promote();
6447 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006448 audio_stream_t *stream = thread->stream();
6449 if (stream != NULL) {
6450 stream->add_audio_effect(stream, mEffectInterface);
6451 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006452 }
6453 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006454 return status;
6455}
6456
Eric Laurentec437d82011-07-26 20:54:46 -07006457status_t AudioFlinger::EffectModule::stop()
6458{
6459 Mutex::Autolock _l(mLock);
6460 return stop_l();
6461}
6462
Mathias Agopian65ab4712010-07-14 17:59:35 -07006463status_t AudioFlinger::EffectModule::stop_l()
6464{
6465 if (mEffectInterface == NULL) {
6466 return NO_INIT;
6467 }
6468 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006469 uint32_t size = sizeof(status_t);
6470 status_t status = (*mEffectInterface)->command(mEffectInterface,
6471 EFFECT_CMD_DISABLE,
6472 0,
6473 NULL,
6474 &size,
6475 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476 if (status == 0) {
6477 status = cmdStatus;
6478 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006479 if (status == 0 &&
6480 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6481 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6482 sp<ThreadBase> thread = mThread.promote();
6483 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006484 audio_stream_t *stream = thread->stream();
6485 if (stream != NULL) {
6486 stream->remove_audio_effect(stream, mEffectInterface);
6487 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006488 }
6489 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006490 return status;
6491}
6492
Eric Laurent25f43952010-07-28 05:40:18 -07006493status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6494 uint32_t cmdSize,
6495 void *pCmdData,
6496 uint32_t *replySize,
6497 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006498{
6499 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006500// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501
Eric Laurentec437d82011-07-26 20:54:46 -07006502 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006503 return NO_INIT;
6504 }
Eric Laurent25f43952010-07-28 05:40:18 -07006505 status_t status = (*mEffectInterface)->command(mEffectInterface,
6506 cmdCode,
6507 cmdSize,
6508 pCmdData,
6509 replySize,
6510 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006512 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006513 for (size_t i = 1; i < mHandles.size(); i++) {
6514 sp<EffectHandle> h = mHandles[i].promote();
6515 if (h != 0) {
6516 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6517 }
6518 }
6519 }
6520 return status;
6521}
6522
6523status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6524{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006525
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006527 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006528
6529 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006530 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6531 if (enabled && status != NO_ERROR) {
6532 return status;
6533 }
6534
Mathias Agopian65ab4712010-07-14 17:59:35 -07006535 switch (mState) {
6536 // going from disabled to enabled
6537 case IDLE:
6538 mState = STARTING;
6539 break;
6540 case STOPPED:
6541 mState = RESTART;
6542 break;
6543 case STOPPING:
6544 mState = ACTIVE;
6545 break;
6546
6547 // going from enabled to disabled
6548 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006549 mState = STOPPED;
6550 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006551 case STARTING:
6552 mState = IDLE;
6553 break;
6554 case ACTIVE:
6555 mState = STOPPING;
6556 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006557 case DESTROYED:
6558 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559 }
6560 for (size_t i = 1; i < mHandles.size(); i++) {
6561 sp<EffectHandle> h = mHandles[i].promote();
6562 if (h != 0) {
6563 h->setEnabled(enabled);
6564 }
6565 }
6566 }
6567 return NO_ERROR;
6568}
6569
6570bool AudioFlinger::EffectModule::isEnabled()
6571{
6572 switch (mState) {
6573 case RESTART:
6574 case STARTING:
6575 case ACTIVE:
6576 return true;
6577 case IDLE:
6578 case STOPPING:
6579 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006580 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581 default:
6582 return false;
6583 }
6584}
6585
Eric Laurent8f45bd72010-08-31 13:50:07 -07006586bool AudioFlinger::EffectModule::isProcessEnabled()
6587{
6588 switch (mState) {
6589 case RESTART:
6590 case ACTIVE:
6591 case STOPPING:
6592 case STOPPED:
6593 return true;
6594 case IDLE:
6595 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006596 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006597 default:
6598 return false;
6599 }
6600}
6601
Mathias Agopian65ab4712010-07-14 17:59:35 -07006602status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6603{
6604 Mutex::Autolock _l(mLock);
6605 status_t status = NO_ERROR;
6606
6607 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6608 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006609 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006610 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6611 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006612 status_t cmdStatus;
6613 uint32_t volume[2];
6614 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006615 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006616 volume[0] = *left;
6617 volume[1] = *right;
6618 if (controller) {
6619 pVolume = volume;
6620 }
Eric Laurent25f43952010-07-28 05:40:18 -07006621 status = (*mEffectInterface)->command(mEffectInterface,
6622 EFFECT_CMD_SET_VOLUME,
6623 size,
6624 volume,
6625 &size,
6626 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006627 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6628 *left = volume[0];
6629 *right = volume[1];
6630 }
6631 }
6632 return status;
6633}
6634
6635status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6636{
6637 Mutex::Autolock _l(mLock);
6638 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006639 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6640 // audio pre processing modules on RecordThread can receive both output and
6641 // input device indication in the same call
6642 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6643 if (dev) {
6644 status_t cmdStatus;
6645 uint32_t size = sizeof(status_t);
6646
6647 status = (*mEffectInterface)->command(mEffectInterface,
6648 EFFECT_CMD_SET_DEVICE,
6649 sizeof(uint32_t),
6650 &dev,
6651 &size,
6652 &cmdStatus);
6653 if (status == NO_ERROR) {
6654 status = cmdStatus;
6655 }
6656 }
6657 dev = device & AUDIO_DEVICE_IN_ALL;
6658 if (dev) {
6659 status_t cmdStatus;
6660 uint32_t size = sizeof(status_t);
6661
6662 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6663 EFFECT_CMD_SET_INPUT_DEVICE,
6664 sizeof(uint32_t),
6665 &dev,
6666 &size,
6667 &cmdStatus);
6668 if (status2 == NO_ERROR) {
6669 status2 = cmdStatus;
6670 }
6671 if (status == NO_ERROR) {
6672 status = status2;
6673 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006674 }
6675 }
6676 return status;
6677}
6678
6679status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6680{
6681 Mutex::Autolock _l(mLock);
6682 status_t status = NO_ERROR;
6683 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006685 uint32_t size = sizeof(status_t);
6686 status = (*mEffectInterface)->command(mEffectInterface,
6687 EFFECT_CMD_SET_AUDIO_MODE,
6688 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006689 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006690 &size,
6691 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006692 if (status == NO_ERROR) {
6693 status = cmdStatus;
6694 }
6695 }
6696 return status;
6697}
6698
Eric Laurent59255e42011-07-27 19:49:51 -07006699void AudioFlinger::EffectModule::setSuspended(bool suspended)
6700{
6701 Mutex::Autolock _l(mLock);
6702 mSuspended = suspended;
6703}
6704bool AudioFlinger::EffectModule::suspended()
6705{
6706 Mutex::Autolock _l(mLock);
6707 return mSuspended;
6708}
6709
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6711{
6712 const size_t SIZE = 256;
6713 char buffer[SIZE];
6714 String8 result;
6715
6716 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6717 result.append(buffer);
6718
6719 bool locked = tryLock(mLock);
6720 // failed to lock - AudioFlinger is probably deadlocked
6721 if (!locked) {
6722 result.append("\t\tCould not lock Fx mutex:\n");
6723 }
6724
6725 result.append("\t\tSession Status State Engine:\n");
6726 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6727 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6728 result.append(buffer);
6729
6730 result.append("\t\tDescriptor:\n");
6731 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6732 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6733 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6734 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6735 result.append(buffer);
6736 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6737 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6738 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6739 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6740 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006741 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006742 mDescriptor.apiVersion,
6743 mDescriptor.flags);
6744 result.append(buffer);
6745 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6746 mDescriptor.name);
6747 result.append(buffer);
6748 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6749 mDescriptor.implementor);
6750 result.append(buffer);
6751
6752 result.append("\t\t- Input configuration:\n");
6753 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6754 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6755 (uint32_t)mConfig.inputCfg.buffer.raw,
6756 mConfig.inputCfg.buffer.frameCount,
6757 mConfig.inputCfg.samplingRate,
6758 mConfig.inputCfg.channels,
6759 mConfig.inputCfg.format);
6760 result.append(buffer);
6761
6762 result.append("\t\t- Output configuration:\n");
6763 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6764 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6765 (uint32_t)mConfig.outputCfg.buffer.raw,
6766 mConfig.outputCfg.buffer.frameCount,
6767 mConfig.outputCfg.samplingRate,
6768 mConfig.outputCfg.channels,
6769 mConfig.outputCfg.format);
6770 result.append(buffer);
6771
6772 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6773 result.append(buffer);
6774 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6775 for (size_t i = 0; i < mHandles.size(); ++i) {
6776 sp<EffectHandle> handle = mHandles[i].promote();
6777 if (handle != 0) {
6778 handle->dump(buffer, SIZE);
6779 result.append(buffer);
6780 }
6781 }
6782
6783 result.append("\n");
6784
6785 write(fd, result.string(), result.length());
6786
6787 if (locked) {
6788 mLock.unlock();
6789 }
6790
6791 return NO_ERROR;
6792}
6793
6794// ----------------------------------------------------------------------------
6795// EffectHandle implementation
6796// ----------------------------------------------------------------------------
6797
6798#undef LOG_TAG
6799#define LOG_TAG "AudioFlinger::EffectHandle"
6800
6801AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6802 const sp<AudioFlinger::Client>& client,
6803 const sp<IEffectClient>& effectClient,
6804 int32_t priority)
6805 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006806 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006807 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808{
Steve Block3856b092011-10-20 11:56:00 +01006809 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006811 if (client == 0) {
6812 return;
6813 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6815 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6816 if (mCblkMemory != 0) {
6817 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6818
6819 if (mCblk) {
6820 new(mCblk) effect_param_cblk_t();
6821 mBuffer = (uint8_t *)mCblk + bufOffset;
6822 }
6823 } else {
6824 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6825 return;
6826 }
6827}
6828
6829AudioFlinger::EffectHandle::~EffectHandle()
6830{
Steve Block3856b092011-10-20 11:56:00 +01006831 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006832 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006833 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006834}
6835
6836status_t AudioFlinger::EffectHandle::enable()
6837{
Steve Block3856b092011-10-20 11:56:00 +01006838 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006839 if (!mHasControl) return INVALID_OPERATION;
6840 if (mEffect == 0) return DEAD_OBJECT;
6841
Eric Laurentdb7c0792011-08-10 10:37:50 -07006842 if (mEnabled) {
6843 return NO_ERROR;
6844 }
6845
Eric Laurent59255e42011-07-27 19:49:51 -07006846 mEnabled = true;
6847
6848 sp<ThreadBase> thread = mEffect->thread().promote();
6849 if (thread != 0) {
6850 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6851 }
6852
6853 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6854 if (mEffect->suspended()) {
6855 return NO_ERROR;
6856 }
6857
Eric Laurentdb7c0792011-08-10 10:37:50 -07006858 status_t status = mEffect->setEnabled(true);
6859 if (status != NO_ERROR) {
6860 if (thread != 0) {
6861 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6862 }
6863 mEnabled = false;
6864 }
6865 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006866}
6867
6868status_t AudioFlinger::EffectHandle::disable()
6869{
Steve Block3856b092011-10-20 11:56:00 +01006870 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006872 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006873
Eric Laurentdb7c0792011-08-10 10:37:50 -07006874 if (!mEnabled) {
6875 return NO_ERROR;
6876 }
Eric Laurent59255e42011-07-27 19:49:51 -07006877 mEnabled = false;
6878
6879 if (mEffect->suspended()) {
6880 return NO_ERROR;
6881 }
6882
6883 status_t status = mEffect->setEnabled(false);
6884
6885 sp<ThreadBase> thread = mEffect->thread().promote();
6886 if (thread != 0) {
6887 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6888 }
6889
6890 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006891}
6892
6893void AudioFlinger::EffectHandle::disconnect()
6894{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006895 disconnect(true);
6896}
6897
6898void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6899{
Steve Block3856b092011-10-20 11:56:00 +01006900 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006901 if (mEffect == 0) {
6902 return;
6903 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006904 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006905
Eric Laurenta85a74a2011-10-19 11:44:54 -07006906 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006907 sp<ThreadBase> thread = mEffect->thread().promote();
6908 if (thread != 0) {
6909 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6910 }
Eric Laurent59255e42011-07-27 19:49:51 -07006911 }
6912
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 // release sp on module => module destructor can be called now
6914 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006915 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006916 if (mCblk) {
6917 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6918 }
6919 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006920 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6921 mClient.clear();
6922 }
6923}
6924
Eric Laurent25f43952010-07-28 05:40:18 -07006925status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6926 uint32_t cmdSize,
6927 void *pCmdData,
6928 uint32_t *replySize,
6929 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930{
Steve Block3856b092011-10-20 11:56:00 +01006931// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006932// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006933
6934 // only get parameter command is permitted for applications not controlling the effect
6935 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6936 return INVALID_OPERATION;
6937 }
6938 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006939 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006940
6941 // handle commands that are not forwarded transparently to effect engine
6942 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6943 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6944 // no risk to block the whole media server process or mixer threads is we are stuck here
6945 Mutex::Autolock _l(mCblk->lock);
6946 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6947 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6948 mCblk->serverIndex = 0;
6949 mCblk->clientIndex = 0;
6950 return BAD_VALUE;
6951 }
6952 status_t status = NO_ERROR;
6953 while (mCblk->serverIndex < mCblk->clientIndex) {
6954 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006955 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006956 int *p = (int *)(mBuffer + mCblk->serverIndex);
6957 int size = *p++;
6958 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6959 LOGW("command(): invalid parameter block size");
6960 break;
6961 }
6962 effect_param_t *param = (effect_param_t *)p;
6963 if (param->psize == 0 || param->vsize == 0) {
6964 LOGW("command(): null parameter or value size");
6965 mCblk->serverIndex += size;
6966 continue;
6967 }
Eric Laurent25f43952010-07-28 05:40:18 -07006968 uint32_t psize = sizeof(effect_param_t) +
6969 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6970 param->vsize;
6971 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6972 psize,
6973 p,
6974 &rsize,
6975 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006976 // stop at first error encountered
6977 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006978 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006979 *(int *)pReplyData = reply;
6980 break;
6981 } else if (reply != NO_ERROR) {
6982 *(int *)pReplyData = reply;
6983 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006984 }
6985 mCblk->serverIndex += size;
6986 }
6987 mCblk->serverIndex = 0;
6988 mCblk->clientIndex = 0;
6989 return status;
6990 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006991 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006992 return enable();
6993 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006994 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006995 return disable();
6996 }
6997
6998 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6999}
7000
7001sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7002 return mCblkMemory;
7003}
7004
Eric Laurent59255e42011-07-27 19:49:51 -07007005void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006{
Steve Block3856b092011-10-20 11:56:00 +01007007 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007008
7009 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007010 mEnabled = enabled;
7011
Mathias Agopian65ab4712010-07-14 17:59:35 -07007012 if (signal && mEffectClient != 0) {
7013 mEffectClient->controlStatusChanged(hasControl);
7014 }
7015}
7016
Eric Laurent25f43952010-07-28 05:40:18 -07007017void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7018 uint32_t cmdSize,
7019 void *pCmdData,
7020 uint32_t replySize,
7021 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022{
7023 if (mEffectClient != 0) {
7024 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7025 }
7026}
7027
7028
7029
7030void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7031{
7032 if (mEffectClient != 0) {
7033 mEffectClient->enableStatusChanged(enabled);
7034 }
7035}
7036
7037status_t AudioFlinger::EffectHandle::onTransact(
7038 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7039{
7040 return BnEffect::onTransact(code, data, reply, flags);
7041}
7042
7043
7044void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7045{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007046 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047
7048 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7049 (mClient == NULL) ? getpid() : mClient->pid(),
7050 mPriority,
7051 mHasControl,
7052 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007053 mCblk ? mCblk->clientIndex : 0,
7054 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055 );
7056
7057 if (locked) {
7058 mCblk->lock.unlock();
7059 }
7060}
7061
7062#undef LOG_TAG
7063#define LOG_TAG "AudioFlinger::EffectChain"
7064
7065AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7066 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007067 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007068 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7069 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070{
Dima Zavinfce7a472011-04-19 22:30:36 -07007071 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007072 sp<ThreadBase> thread = mThread.promote();
7073 if (thread == 0) {
7074 return;
7075 }
7076 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7077 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007078}
7079
7080AudioFlinger::EffectChain::~EffectChain()
7081{
7082 if (mOwnInBuffer) {
7083 delete mInBuffer;
7084 }
7085
7086}
7087
Eric Laurent59255e42011-07-27 19:49:51 -07007088// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007089sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007090{
7091 sp<EffectModule> effect;
7092 size_t size = mEffects.size();
7093
7094 for (size_t i = 0; i < size; i++) {
7095 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7096 effect = mEffects[i];
7097 break;
7098 }
7099 }
7100 return effect;
7101}
7102
Eric Laurent59255e42011-07-27 19:49:51 -07007103// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007104sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007105{
7106 sp<EffectModule> effect;
7107 size_t size = mEffects.size();
7108
7109 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007110 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7111 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112 effect = mEffects[i];
7113 break;
7114 }
7115 }
7116 return effect;
7117}
7118
Eric Laurent59255e42011-07-27 19:49:51 -07007119// getEffectFromType_l() must be called with ThreadBase::mLock held
7120sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7121 const effect_uuid_t *type)
7122{
7123 sp<EffectModule> effect;
7124 size_t size = mEffects.size();
7125
7126 for (size_t i = 0; i < size; i++) {
7127 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7128 effect = mEffects[i];
7129 break;
7130 }
7131 }
7132 return effect;
7133}
7134
Mathias Agopian65ab4712010-07-14 17:59:35 -07007135// Must be called with EffectChain::mLock locked
7136void AudioFlinger::EffectChain::process_l()
7137{
Eric Laurentdac69112010-09-28 14:09:57 -07007138 sp<ThreadBase> thread = mThread.promote();
7139 if (thread == 0) {
7140 LOGW("process_l(): cannot promote mixer thread");
7141 return;
7142 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007143 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7144 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007145 // always process effects unless no more tracks are on the session and the effect tail
7146 // has been rendered
7147 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007148 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007149 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007150
Eric Laurent544fe9b2011-11-11 15:42:52 -08007151 if (!tracksOnSession && mTailBufferCount == 0) {
7152 doProcess = false;
7153 }
7154
7155 if (activeTrackCnt() == 0) {
7156 // if no track is active and the effect tail has not been rendered,
7157 // the input buffer must be cleared here as the mixer process will not do it
7158 if (tracksOnSession || mTailBufferCount > 0) {
7159 size_t numSamples = thread->frameCount() * thread->channelCount();
7160 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7161 if (mTailBufferCount > 0) {
7162 mTailBufferCount--;
7163 }
7164 }
7165 }
Eric Laurentdac69112010-09-28 14:09:57 -07007166 }
7167
Mathias Agopian65ab4712010-07-14 17:59:35 -07007168 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007169 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007170 for (size_t i = 0; i < size; i++) {
7171 mEffects[i]->process();
7172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007173 }
7174 for (size_t i = 0; i < size; i++) {
7175 mEffects[i]->updateState();
7176 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007177}
7178
Eric Laurentcab11242010-07-15 12:50:15 -07007179// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007180status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007181{
7182 effect_descriptor_t desc = effect->desc();
7183 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7184
7185 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007186 effect->setChain(this);
7187 sp<ThreadBase> thread = mThread.promote();
7188 if (thread == 0) {
7189 return NO_INIT;
7190 }
7191 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007192
7193 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7194 // Auxiliary effects are inserted at the beginning of mEffects vector as
7195 // they are processed first and accumulated in chain input buffer
7196 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007197
Mathias Agopian65ab4712010-07-14 17:59:35 -07007198 // the input buffer for auxiliary effect contains mono samples in
7199 // 32 bit format. This is to avoid saturation in AudoMixer
7200 // accumulation stage. Saturation is done in EffectModule::process() before
7201 // calling the process in effect engine
7202 size_t numSamples = thread->frameCount();
7203 int32_t *buffer = new int32_t[numSamples];
7204 memset(buffer, 0, numSamples * sizeof(int32_t));
7205 effect->setInBuffer((int16_t *)buffer);
7206 // auxiliary effects output samples to chain input buffer for further processing
7207 // by insert effects
7208 effect->setOutBuffer(mInBuffer);
7209 } else {
7210 // Insert effects are inserted at the end of mEffects vector as they are processed
7211 // after track and auxiliary effects.
7212 // Insert effect order as a function of indicated preference:
7213 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7214 // another effect is present
7215 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7216 // last effect claiming first position
7217 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7218 // first effect claiming last position
7219 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7220 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7221 // already present
7222
7223 int size = (int)mEffects.size();
7224 int idx_insert = size;
7225 int idx_insert_first = -1;
7226 int idx_insert_last = -1;
7227
7228 for (int i = 0; i < size; i++) {
7229 effect_descriptor_t d = mEffects[i]->desc();
7230 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7231 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7232 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7233 // check invalid effect chaining combinations
7234 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7235 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007236 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007237 return INVALID_OPERATION;
7238 }
7239 // remember position of first insert effect and by default
7240 // select this as insert position for new effect
7241 if (idx_insert == size) {
7242 idx_insert = i;
7243 }
7244 // remember position of last insert effect claiming
7245 // first position
7246 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7247 idx_insert_first = i;
7248 }
7249 // remember position of first insert effect claiming
7250 // last position
7251 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7252 idx_insert_last == -1) {
7253 idx_insert_last = i;
7254 }
7255 }
7256 }
7257
7258 // modify idx_insert from first position if needed
7259 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7260 if (idx_insert_last != -1) {
7261 idx_insert = idx_insert_last;
7262 } else {
7263 idx_insert = size;
7264 }
7265 } else {
7266 if (idx_insert_first != -1) {
7267 idx_insert = idx_insert_first + 1;
7268 }
7269 }
7270
7271 // always read samples from chain input buffer
7272 effect->setInBuffer(mInBuffer);
7273
7274 // if last effect in the chain, output samples to chain
7275 // output buffer, otherwise to chain input buffer
7276 if (idx_insert == size) {
7277 if (idx_insert != 0) {
7278 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7279 mEffects[idx_insert-1]->configure();
7280 }
7281 effect->setOutBuffer(mOutBuffer);
7282 } else {
7283 effect->setOutBuffer(mInBuffer);
7284 }
7285 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286
Steve Block3856b092011-10-20 11:56:00 +01007287 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007288 }
7289 effect->configure();
7290 return NO_ERROR;
7291}
7292
Eric Laurentcab11242010-07-15 12:50:15 -07007293// removeEffect_l() must be called with PlaybackThread::mLock held
7294size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295{
7296 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007297 int size = (int)mEffects.size();
7298 int i;
7299 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7300
7301 for (i = 0; i < size; i++) {
7302 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007303 // calling stop here will remove pre-processing effect from the audio HAL.
7304 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7305 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007306 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7307 mEffects[i]->state() == EffectModule::STOPPING) {
7308 mEffects[i]->stop();
7309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7311 delete[] effect->inBuffer();
7312 } else {
7313 if (i == size - 1 && i != 0) {
7314 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7315 mEffects[i - 1]->configure();
7316 }
7317 }
7318 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007319 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007320 break;
7321 }
7322 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007323
7324 return mEffects.size();
7325}
7326
Eric Laurentcab11242010-07-15 12:50:15 -07007327// setDevice_l() must be called with PlaybackThread::mLock held
7328void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007329{
7330 size_t size = mEffects.size();
7331 for (size_t i = 0; i < size; i++) {
7332 mEffects[i]->setDevice(device);
7333 }
7334}
7335
Eric Laurentcab11242010-07-15 12:50:15 -07007336// setMode_l() must be called with PlaybackThread::mLock held
7337void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007338{
7339 size_t size = mEffects.size();
7340 for (size_t i = 0; i < size; i++) {
7341 mEffects[i]->setMode(mode);
7342 }
7343}
7344
Eric Laurentcab11242010-07-15 12:50:15 -07007345// setVolume_l() must be called with PlaybackThread::mLock held
7346bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007347{
7348 uint32_t newLeft = *left;
7349 uint32_t newRight = *right;
7350 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007351 int ctrlIdx = -1;
7352 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353
Eric Laurentcab11242010-07-15 12:50:15 -07007354 // first update volume controller
7355 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007356 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007357 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7358 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007359 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007360 break;
7361 }
7362 }
7363
7364 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007365 if (hasControl) {
7366 *left = mNewLeftVolume;
7367 *right = mNewRightVolume;
7368 }
7369 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007370 }
7371
7372 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007373 mLeftVolume = newLeft;
7374 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007375
7376 // second get volume update from volume controller
7377 if (ctrlIdx >= 0) {
7378 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007379 mNewLeftVolume = newLeft;
7380 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381 }
7382 // then indicate volume to all other effects in chain.
7383 // Pass altered volume to effects before volume controller
7384 // and requested volume to effects after controller
7385 uint32_t lVol = newLeft;
7386 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007387
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007389 if ((int)i == ctrlIdx) continue;
7390 // this also works for ctrlIdx == -1 when there is no volume controller
7391 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007392 lVol = *left;
7393 rVol = *right;
7394 }
7395 mEffects[i]->setVolume(&lVol, &rVol, false);
7396 }
7397 *left = newLeft;
7398 *right = newRight;
7399
7400 return hasControl;
7401}
7402
Mathias Agopian65ab4712010-07-14 17:59:35 -07007403status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7404{
7405 const size_t SIZE = 256;
7406 char buffer[SIZE];
7407 String8 result;
7408
7409 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7410 result.append(buffer);
7411
7412 bool locked = tryLock(mLock);
7413 // failed to lock - AudioFlinger is probably deadlocked
7414 if (!locked) {
7415 result.append("\tCould not lock mutex:\n");
7416 }
7417
Eric Laurentcab11242010-07-15 12:50:15 -07007418 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7419 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007420 mEffects.size(),
7421 (uint32_t)mInBuffer,
7422 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007423 mActiveTrackCnt);
7424 result.append(buffer);
7425 write(fd, result.string(), result.size());
7426
7427 for (size_t i = 0; i < mEffects.size(); ++i) {
7428 sp<EffectModule> effect = mEffects[i];
7429 if (effect != 0) {
7430 effect->dump(fd, args);
7431 }
7432 }
7433
7434 if (locked) {
7435 mLock.unlock();
7436 }
7437
7438 return NO_ERROR;
7439}
7440
Eric Laurent59255e42011-07-27 19:49:51 -07007441// must be called with ThreadBase::mLock held
7442void AudioFlinger::EffectChain::setEffectSuspended_l(
7443 const effect_uuid_t *type, bool suspend)
7444{
7445 sp<SuspendedEffectDesc> desc;
7446 // use effect type UUID timelow as key as there is no real risk of identical
7447 // timeLow fields among effect type UUIDs.
7448 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7449 if (suspend) {
7450 if (index >= 0) {
7451 desc = mSuspendedEffects.valueAt(index);
7452 } else {
7453 desc = new SuspendedEffectDesc();
7454 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7455 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007456 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007457 }
7458 if (desc->mRefCount++ == 0) {
7459 sp<EffectModule> effect = getEffectIfEnabled(type);
7460 if (effect != 0) {
7461 desc->mEffect = effect;
7462 effect->setSuspended(true);
7463 effect->setEnabled(false);
7464 }
7465 }
7466 } else {
7467 if (index < 0) {
7468 return;
7469 }
7470 desc = mSuspendedEffects.valueAt(index);
7471 if (desc->mRefCount <= 0) {
7472 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7473 desc->mRefCount = 1;
7474 }
7475 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007476 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007477 if (desc->mEffect != 0) {
7478 sp<EffectModule> effect = desc->mEffect.promote();
7479 if (effect != 0) {
7480 effect->setSuspended(false);
7481 sp<EffectHandle> handle = effect->controlHandle();
7482 if (handle != 0) {
7483 effect->setEnabled(handle->enabled());
7484 }
7485 }
7486 desc->mEffect.clear();
7487 }
7488 mSuspendedEffects.removeItemsAt(index);
7489 }
7490 }
7491}
7492
7493// must be called with ThreadBase::mLock held
7494void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7495{
7496 sp<SuspendedEffectDesc> desc;
7497
7498 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7499 if (suspend) {
7500 if (index >= 0) {
7501 desc = mSuspendedEffects.valueAt(index);
7502 } else {
7503 desc = new SuspendedEffectDesc();
7504 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007505 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007506 }
7507 if (desc->mRefCount++ == 0) {
7508 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7509 for (size_t i = 0; i < effects.size(); i++) {
7510 setEffectSuspended_l(&effects[i]->desc().type, true);
7511 }
7512 }
7513 } else {
7514 if (index < 0) {
7515 return;
7516 }
7517 desc = mSuspendedEffects.valueAt(index);
7518 if (desc->mRefCount <= 0) {
7519 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7520 desc->mRefCount = 1;
7521 }
7522 if (--desc->mRefCount == 0) {
7523 Vector<const effect_uuid_t *> types;
7524 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7525 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7526 continue;
7527 }
7528 types.add(&mSuspendedEffects.valueAt(i)->mType);
7529 }
7530 for (size_t i = 0; i < types.size(); i++) {
7531 setEffectSuspended_l(types[i], false);
7532 }
Steve Block3856b092011-10-20 11:56:00 +01007533 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007534 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7535 }
7536 }
7537}
7538
Eric Laurent6bffdb82011-09-23 08:40:41 -07007539
7540// The volume effect is used for automated tests only
7541#ifndef OPENSL_ES_H_
7542static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7543 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7544const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7545#endif //OPENSL_ES_H_
7546
Eric Laurentdb7c0792011-08-10 10:37:50 -07007547bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7548{
7549 // auxiliary effects and visualizer are never suspended on output mix
7550 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7551 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007552 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7553 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007554 return false;
7555 }
7556 return true;
7557}
7558
Eric Laurent59255e42011-07-27 19:49:51 -07007559Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7560{
7561 Vector< sp<EffectModule> > effects;
7562 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007563 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007564 continue;
7565 }
7566 effects.add(mEffects[i]);
7567 }
7568 return effects;
7569}
7570
7571sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7572 const effect_uuid_t *type)
7573{
7574 sp<EffectModule> effect;
7575 effect = getEffectFromType_l(type);
7576 if (effect != 0 && !effect->isEnabled()) {
7577 effect.clear();
7578 }
7579 return effect;
7580}
7581
7582void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7583 bool enabled)
7584{
7585 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7586 if (enabled) {
7587 if (index < 0) {
7588 // if the effect is not suspend check if all effects are suspended
7589 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7590 if (index < 0) {
7591 return;
7592 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007593 if (!isEffectEligibleForSuspend(effect->desc())) {
7594 return;
7595 }
Eric Laurent59255e42011-07-27 19:49:51 -07007596 setEffectSuspended_l(&effect->desc().type, enabled);
7597 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007598 if (index < 0) {
7599 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7600 return;
7601 }
Eric Laurent59255e42011-07-27 19:49:51 -07007602 }
Steve Block3856b092011-10-20 11:56:00 +01007603 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007604 effect->desc().type.timeLow);
7605 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7606 // if effect is requested to suspended but was not yet enabled, supend it now.
7607 if (desc->mEffect == 0) {
7608 desc->mEffect = effect;
7609 effect->setEnabled(false);
7610 effect->setSuspended(true);
7611 }
7612 } else {
7613 if (index < 0) {
7614 return;
7615 }
Steve Block3856b092011-10-20 11:56:00 +01007616 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007617 effect->desc().type.timeLow);
7618 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7619 desc->mEffect.clear();
7620 effect->setSuspended(false);
7621 }
7622}
7623
Mathias Agopian65ab4712010-07-14 17:59:35 -07007624#undef LOG_TAG
7625#define LOG_TAG "AudioFlinger"
7626
7627// ----------------------------------------------------------------------------
7628
7629status_t AudioFlinger::onTransact(
7630 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7631{
7632 return BnAudioFlinger::onTransact(code, data, reply, flags);
7633}
7634
Mathias Agopian65ab4712010-07-14 17:59:35 -07007635}; // namespace android