blob: 778e40915fe93b061e0e528981b3220509a47fc9 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Gloria Wang9ee159b2011-02-24 14:51:45 -080027#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028#include <binder/IServiceManager.h>
29#include <utils/Log.h>
30#include <binder/Parcel.h>
31#include <binder/IPCThreadState.h>
32#include <utils/String16.h>
33#include <utils/threads.h>
Eric Laurent38ccae22011-03-28 18:37:07 -070034#include <utils/Atomic.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070035
Dima Zavinfce7a472011-04-19 22:30:36 -070036#include <cutils/bitops.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070037#include <cutils/properties.h>
38
39#include <media/AudioTrack.h>
40#include <media/AudioRecord.h>
Gloria Wang9ee159b2011-02-24 14:51:45 -080041#include <media/IMediaPlayerService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070042
43#include <private/media/AudioTrackShared.h>
44#include <private/media/AudioEffectShared.h>
Dima Zavinfce7a472011-04-19 22:30:36 -070045
Dima Zavin64760242011-05-11 14:15:23 -070046#include <system/audio.h>
Dima Zavin7394a4f2011-06-13 18:16:26 -070047#include <hardware/audio.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49#include "AudioMixer.h"
50#include "AudioFlinger.h"
51
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <media/EffectsFactoryApi.h>
Eric Laurent6d8b6942011-06-24 07:01:31 -070053#include <audio_effects/effect_visualizer.h>
Eric Laurent59bd0da2011-08-01 09:52:20 -070054#include <audio_effects/effect_ns.h>
55#include <audio_effects/effect_aec.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070057#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070058#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
60
Mike J. Chen500e5102011-08-15 13:28:26 -070061#include <aah_timesrv/cc_helper.h>
62#include <aah_timesrv/local_clock.h>
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
69static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
70static const char* kHardwareLockedString = "Hardware lock is taken\n";
71
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;
86static const int kDumpLockSleep = 20000;
87
88static const nsecs_t kWarningThrottle = seconds(5);
89
Eric Laurent7c7f10b2011-06-17 21:29:58 -070090// RecordThread loop sleep time upon application overrun or audio HAL read error
91static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070092
Eric Laurent60cd0a02011-09-13 11:40:21 -070093static const nsecs_t kSetParametersTimeout = seconds(2);
94
Mathias Agopian65ab4712010-07-14 17:59:35 -070095// ----------------------------------------------------------------------------
96
97static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070098 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
99 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
100 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
101 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102}
103
104static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
107 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
Gloria Wang9ee159b2011-02-24 14:51:45 -0800111// To collect the amplifier usage
112static void addBatteryData(uint32_t params) {
113 sp<IBinder> binder =
114 defaultServiceManager()->getService(String16("media.player"));
115 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
116 if (service.get() == NULL) {
117 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
118 return;
119 }
120
121 service->addBatteryData(params);
122}
123
Dima Zavin799a70e2011-04-18 16:57:27 -0700124static int load_audio_interface(const char *if_name, const hw_module_t **mod,
125 audio_hw_device_t **dev)
126{
127 int rc;
128
129 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
130 if (rc)
131 goto out;
132
133 rc = audio_hw_device_open(*mod, dev);
134 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
135 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
136 if (rc)
137 goto out;
138
139 return 0;
140
141out:
142 *mod = NULL;
143 *dev = NULL;
144 return rc;
145}
146
147static const char *audio_interfaces[] = {
148 "primary",
149 "a2dp",
150 "usb",
151};
152#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
153
Mathias Agopian65ab4712010-07-14 17:59:35 -0700154// ----------------------------------------------------------------------------
155
156AudioFlinger::AudioFlinger()
157 : BnAudioFlinger(),
Mike J. Chen500e5102011-08-15 13:28:26 -0700158 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterVolumeSW(1.0f),
159 mMasterVolumeSupportLvl(MVS_NONE), mMasterMute(false), mNextUniqueId(1),
160 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700162}
163
164void AudioFlinger::onFirstRef()
165{
Dima Zavin799a70e2011-04-18 16:57:27 -0700166 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700167
Eric Laurent93575202011-01-18 18:39:02 -0800168 Mutex::Autolock _l(mLock);
169
Dima Zavin799a70e2011-04-18 16:57:27 -0700170 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700171 mHardwareStatus = AUDIO_HW_IDLE;
172
Dima Zavin799a70e2011-04-18 16:57:27 -0700173 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
174 const hw_module_t *mod;
175 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700176
Dima Zavin799a70e2011-04-18 16:57:27 -0700177 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
178 if (rc)
179 continue;
180
181 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
182 mod->name, mod->id);
183 mAudioHwDevs.push(dev);
184
185 if (!mPrimaryHardwareDev) {
186 mPrimaryHardwareDev = dev;
187 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700188 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700189 }
190 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700191
192 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700193
Dima Zavin799a70e2011-04-18 16:57:27 -0700194 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
195 LOGE("Primary audio interface not found");
196 return;
197 }
198
Mike J. Chen500e5102011-08-15 13:28:26 -0700199 // Determine the level of master volume support the primary audio HAL has,
200 // and set the initial master volume at the same time.
201 float initialVolume = 1.0;
202 mMasterVolumeSupportLvl = MVS_NONE;
203 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
204 AutoMutex lock(mHardwareLock);
205 audio_hw_device_t *dev = mPrimaryHardwareDev;
206
207 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
208 if ((NULL != dev->get_master_volume) &&
209 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
210 mMasterVolumeSupportLvl = MVS_FULL;
211 } else {
212 mMasterVolumeSupportLvl = MVS_SETONLY;
213 initialVolume = 1.0;
214 }
215
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 if ((NULL == dev->set_master_volume) ||
218 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
219 mMasterVolumeSupportLvl = MVS_NONE;
220 }
221 mHardwareStatus = AUDIO_HW_INIT;
222 }
223
224 // Set the mode for each audio HAL, and try to set the initial volume (if
225 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700226 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
227 audio_hw_device_t *dev = mAudioHwDevs[i];
228
229 mHardwareStatus = AUDIO_HW_INIT;
230 rc = dev->init_check(dev);
231 if (rc == 0) {
232 AutoMutex lock(mHardwareLock);
233
234 mMode = AUDIO_MODE_NORMAL;
235 mHardwareStatus = AUDIO_HW_SET_MODE;
236 dev->set_mode(dev, mMode);
Mike J. Chen500e5102011-08-15 13:28:26 -0700237
238 if ((dev != mPrimaryHardwareDev) &&
239 (NULL != dev->set_master_volume)) {
240 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
241 dev->set_master_volume(dev, initialVolume);
242 }
243
244 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin799a70e2011-04-18 16:57:27 -0700245 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246 }
Mike J. Chen500e5102011-08-15 13:28:26 -0700247
248 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
249 ? initialVolume
250 : 1.0;
251 mMasterVolume = initialVolume;
252 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700253}
254
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700255status_t AudioFlinger::initCheck() const
256{
257 Mutex::Autolock _l(mLock);
258 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
259 return NO_INIT;
260 return NO_ERROR;
261}
262
Mathias Agopian65ab4712010-07-14 17:59:35 -0700263AudioFlinger::~AudioFlinger()
264{
Dima Zavin799a70e2011-04-18 16:57:27 -0700265 int num_devs = mAudioHwDevs.size();
266
Mathias Agopian65ab4712010-07-14 17:59:35 -0700267 while (!mRecordThreads.isEmpty()) {
268 // closeInput() will remove first entry from mRecordThreads
269 closeInput(mRecordThreads.keyAt(0));
270 }
271 while (!mPlaybackThreads.isEmpty()) {
272 // closeOutput() will remove first entry from mPlaybackThreads
273 closeOutput(mPlaybackThreads.keyAt(0));
274 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700275
276 for (int i = 0; i < num_devs; i++) {
277 audio_hw_device_t *dev = mAudioHwDevs[i];
278 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700279 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700280 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700281}
282
Dima Zavin799a70e2011-04-18 16:57:27 -0700283audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
284{
285 /* first matching HW device is returned */
286 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
287 audio_hw_device_t *dev = mAudioHwDevs[i];
288 if ((dev->get_supported_devices(dev) & devices) == devices)
289 return dev;
290 }
291 return NULL;
292}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700293
294status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
295{
296 const size_t SIZE = 256;
297 char buffer[SIZE];
298 String8 result;
299
300 result.append("Clients:\n");
301 for (size_t i = 0; i < mClients.size(); ++i) {
302 wp<Client> wClient = mClients.valueAt(i);
303 if (wClient != 0) {
304 sp<Client> client = wClient.promote();
305 if (client != 0) {
306 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
307 result.append(buffer);
308 }
309 }
310 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700311
312 result.append("Global session refs:\n");
313 result.append(" session pid cnt\n");
314 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
315 AudioSessionRef *r = mAudioSessionRefs[i];
316 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
317 result.append(buffer);
318 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700319 write(fd, result.string(), result.size());
320 return NO_ERROR;
321}
322
323
324status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
325{
326 const size_t SIZE = 256;
327 char buffer[SIZE];
328 String8 result;
329 int hardwareStatus = mHardwareStatus;
330
331 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
332 result.append(buffer);
333 write(fd, result.string(), result.size());
334 return NO_ERROR;
335}
336
337status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
338{
339 const size_t SIZE = 256;
340 char buffer[SIZE];
341 String8 result;
342 snprintf(buffer, SIZE, "Permission Denial: "
343 "can't dump AudioFlinger from pid=%d, uid=%d\n",
344 IPCThreadState::self()->getCallingPid(),
345 IPCThreadState::self()->getCallingUid());
346 result.append(buffer);
347 write(fd, result.string(), result.size());
348 return NO_ERROR;
349}
350
351static bool tryLock(Mutex& mutex)
352{
353 bool locked = false;
354 for (int i = 0; i < kDumpLockRetries; ++i) {
355 if (mutex.tryLock() == NO_ERROR) {
356 locked = true;
357 break;
358 }
359 usleep(kDumpLockSleep);
360 }
361 return locked;
362}
363
364status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
365{
366 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
367 dumpPermissionDenial(fd, args);
368 } else {
369 // get state of hardware lock
370 bool hardwareLocked = tryLock(mHardwareLock);
371 if (!hardwareLocked) {
372 String8 result(kHardwareLockedString);
373 write(fd, result.string(), result.size());
374 } else {
375 mHardwareLock.unlock();
376 }
377
378 bool locked = tryLock(mLock);
379
380 // failed to lock - AudioFlinger is probably deadlocked
381 if (!locked) {
382 String8 result(kDeadlockedString);
383 write(fd, result.string(), result.size());
384 }
385
386 dumpClients(fd, args);
387 dumpInternals(fd, args);
388
389 // dump playback threads
390 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
391 mPlaybackThreads.valueAt(i)->dump(fd, args);
392 }
393
394 // dump record threads
395 for (size_t i = 0; i < mRecordThreads.size(); i++) {
396 mRecordThreads.valueAt(i)->dump(fd, args);
397 }
398
Dima Zavin799a70e2011-04-18 16:57:27 -0700399 // dump all hardware devs
400 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
401 audio_hw_device_t *dev = mAudioHwDevs[i];
402 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 }
404 if (locked) mLock.unlock();
405 }
406 return NO_ERROR;
407}
408
409
410// IAudioFlinger interface
411
412
413sp<IAudioTrack> AudioFlinger::createTrack(
414 pid_t pid,
415 int streamType,
416 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700417 uint32_t format,
418 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700419 int frameCount,
420 uint32_t flags,
421 const sp<IMemory>& sharedBuffer,
422 int output,
Mike J. Chen500e5102011-08-15 13:28:26 -0700423 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424 int *sessionId,
425 status_t *status)
426{
427 sp<PlaybackThread::Track> track;
428 sp<TrackHandle> trackHandle;
429 sp<Client> client;
430 wp<Client> wclient;
431 status_t lStatus;
432 int lSessionId;
433
Dima Zavinfce7a472011-04-19 22:30:36 -0700434 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700435 LOGE("invalid stream type");
436 lStatus = BAD_VALUE;
437 goto Exit;
438 }
439
440 {
441 Mutex::Autolock _l(mLock);
442 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700443 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 if (thread == NULL) {
445 LOGE("unknown output thread");
446 lStatus = BAD_VALUE;
447 goto Exit;
448 }
449
450 wclient = mClients.valueFor(pid);
451
452 if (wclient != NULL) {
453 client = wclient.promote();
454 } else {
455 client = new Client(this, pid);
456 mClients.add(pid, client);
457 }
458
Mathias Agopian65ab4712010-07-14 17:59:35 -0700459 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700460 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700461 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700462 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
463 if (mPlaybackThreads.keyAt(i) != output) {
464 // prevent same audio session on different output threads
465 uint32_t sessions = t->hasAudioSession(*sessionId);
466 if (sessions & PlaybackThread::TRACK_SESSION) {
467 lStatus = BAD_VALUE;
468 goto Exit;
469 }
470 // check if an effect with same session ID is waiting for a track to be created
471 if (sessions & PlaybackThread::EFFECT_SESSION) {
472 effectThread = t.get();
473 }
Eric Laurentde070132010-07-13 04:45:46 -0700474 }
475 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700476 lSessionId = *sessionId;
477 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700478 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700479 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480 if (sessionId != NULL) {
481 *sessionId = lSessionId;
482 }
483 }
484 LOGV("createTrack() lSessionId: %d", lSessionId);
485
486 track = thread->createTrack_l(client, streamType, sampleRate, format,
Mike J. Chen500e5102011-08-15 13:28:26 -0700487 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700488
489 // move effect chain to this output thread if an effect on same session was waiting
490 // for a track to be created
491 if (lStatus == NO_ERROR && effectThread != NULL) {
492 Mutex::Autolock _dl(thread->mLock);
493 Mutex::Autolock _sl(effectThread->mLock);
494 moveEffectChain_l(lSessionId, effectThread, thread, true);
495 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700496 }
497 if (lStatus == NO_ERROR) {
498 trackHandle = new TrackHandle(track);
499 } else {
500 // remove local strong reference to Client before deleting the Track so that the Client
501 // destructor is called by the TrackBase destructor with mLock held
502 client.clear();
503 track.clear();
504 }
505
506Exit:
507 if(status) {
508 *status = lStatus;
509 }
510 return trackHandle;
511}
512
513uint32_t AudioFlinger::sampleRate(int output) const
514{
515 Mutex::Autolock _l(mLock);
516 PlaybackThread *thread = checkPlaybackThread_l(output);
517 if (thread == NULL) {
518 LOGW("sampleRate() unknown thread %d", output);
519 return 0;
520 }
521 return thread->sampleRate();
522}
523
524int AudioFlinger::channelCount(int output) const
525{
526 Mutex::Autolock _l(mLock);
527 PlaybackThread *thread = checkPlaybackThread_l(output);
528 if (thread == NULL) {
529 LOGW("channelCount() unknown thread %d", output);
530 return 0;
531 }
532 return thread->channelCount();
533}
534
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700535uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700536{
537 Mutex::Autolock _l(mLock);
538 PlaybackThread *thread = checkPlaybackThread_l(output);
539 if (thread == NULL) {
540 LOGW("format() unknown thread %d", output);
541 return 0;
542 }
543 return thread->format();
544}
545
546size_t AudioFlinger::frameCount(int output) const
547{
548 Mutex::Autolock _l(mLock);
549 PlaybackThread *thread = checkPlaybackThread_l(output);
550 if (thread == NULL) {
551 LOGW("frameCount() unknown thread %d", output);
552 return 0;
553 }
554 return thread->frameCount();
555}
556
557uint32_t AudioFlinger::latency(int output) const
558{
559 Mutex::Autolock _l(mLock);
560 PlaybackThread *thread = checkPlaybackThread_l(output);
561 if (thread == NULL) {
562 LOGW("latency() unknown thread %d", output);
563 return 0;
564 }
565 return thread->latency();
566}
567
568status_t AudioFlinger::setMasterVolume(float value)
569{
Eric Laurenta1884f92011-08-23 08:25:03 -0700570 status_t ret = initCheck();
571 if (ret != NO_ERROR) {
572 return ret;
573 }
574
Mathias Agopian65ab4712010-07-14 17:59:35 -0700575 // check calling permissions
576 if (!settingsAllowed()) {
577 return PERMISSION_DENIED;
578 }
579
Mike J. Chen500e5102011-08-15 13:28:26 -0700580 float swmv = value;
581
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582 // when hw supports master volume, don't scale in sw mixer
Mike J. Chen500e5102011-08-15 13:28:26 -0700583 if (MVS_NONE != mMasterVolumeSupportLvl) {
584 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
585 AutoMutex lock(mHardwareLock);
586 audio_hw_device_t *dev = mAudioHwDevs[i];
587
588 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
589 if (NULL != dev->set_master_volume) {
590 dev->set_master_volume(dev, value);
591 }
592 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800593 }
Mike J. Chen500e5102011-08-15 13:28:26 -0700594
595 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700597
Eric Laurent93575202011-01-18 18:39:02 -0800598 Mutex::Autolock _l(mLock);
Mike J. Chen500e5102011-08-15 13:28:26 -0700599 mMasterVolume = value;
600 mMasterVolumeSW = swmv;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Mike J. Chen500e5102011-08-15 13:28:26 -0700602 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603
604 return NO_ERROR;
605}
606
607status_t AudioFlinger::setMode(int mode)
608{
Eric Laurenta1884f92011-08-23 08:25:03 -0700609 status_t ret = initCheck();
610 if (ret != NO_ERROR) {
611 return ret;
612 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700613
614 // check calling permissions
615 if (!settingsAllowed()) {
616 return PERMISSION_DENIED;
617 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700618 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700619 LOGW("Illegal value: setMode(%d)", mode);
620 return BAD_VALUE;
621 }
622
623 { // scope for the lock
624 AutoMutex lock(mHardwareLock);
625 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700626 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700627 mHardwareStatus = AUDIO_HW_IDLE;
628 }
629
630 if (NO_ERROR == ret) {
631 Mutex::Autolock _l(mLock);
632 mMode = mode;
633 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
634 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700635 }
636
637 return ret;
638}
639
640status_t AudioFlinger::setMicMute(bool state)
641{
Eric Laurenta1884f92011-08-23 08:25:03 -0700642 status_t ret = initCheck();
643 if (ret != NO_ERROR) {
644 return ret;
645 }
646
Mathias Agopian65ab4712010-07-14 17:59:35 -0700647 // check calling permissions
648 if (!settingsAllowed()) {
649 return PERMISSION_DENIED;
650 }
651
652 AutoMutex lock(mHardwareLock);
653 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700654 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700655 mHardwareStatus = AUDIO_HW_IDLE;
656 return ret;
657}
658
659bool AudioFlinger::getMicMute() const
660{
Eric Laurenta1884f92011-08-23 08:25:03 -0700661 status_t ret = initCheck();
662 if (ret != NO_ERROR) {
663 return false;
664 }
665
Dima Zavinfce7a472011-04-19 22:30:36 -0700666 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700668 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700669 mHardwareStatus = AUDIO_HW_IDLE;
670 return state;
671}
672
673status_t AudioFlinger::setMasterMute(bool muted)
674{
675 // check calling permissions
676 if (!settingsAllowed()) {
677 return PERMISSION_DENIED;
678 }
679
Eric Laurent93575202011-01-18 18:39:02 -0800680 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700681 mMasterMute = muted;
682 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
683 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
684
685 return NO_ERROR;
686}
687
688float AudioFlinger::masterVolume() const
689{
Mike J. Chen500e5102011-08-15 13:28:26 -0700690 if (MVS_FULL == mMasterVolumeSupportLvl) {
691 float ret_val;
692 AutoMutex lock(mHardwareLock);
693
694 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
695 assert(NULL != mPrimaryHardwareDev);
696 assert(NULL != mPrimaryHardwareDev->get_master_volume);
697
698 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
699 mHardwareStatus = AUDIO_HW_IDLE;
700 return ret_val;
701 }
702
Mathias Agopian65ab4712010-07-14 17:59:35 -0700703 return mMasterVolume;
704}
705
Mike J. Chen500e5102011-08-15 13:28:26 -0700706float AudioFlinger::masterVolumeSW() const
707{
708 return mMasterVolumeSW;
709}
710
Mathias Agopian65ab4712010-07-14 17:59:35 -0700711bool AudioFlinger::masterMute() const
712{
713 return mMasterMute;
714}
715
716status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
717{
718 // check calling permissions
719 if (!settingsAllowed()) {
720 return PERMISSION_DENIED;
721 }
722
Dima Zavinfce7a472011-04-19 22:30:36 -0700723 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700724 return BAD_VALUE;
725 }
726
727 AutoMutex lock(mLock);
728 PlaybackThread *thread = NULL;
729 if (output) {
730 thread = checkPlaybackThread_l(output);
731 if (thread == NULL) {
732 return BAD_VALUE;
733 }
734 }
735
736 mStreamTypes[stream].volume = value;
737
738 if (thread == NULL) {
739 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
740 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
741 }
742 } else {
743 thread->setStreamVolume(stream, value);
744 }
745
746 return NO_ERROR;
747}
748
749status_t AudioFlinger::setStreamMute(int stream, bool muted)
750{
751 // check calling permissions
752 if (!settingsAllowed()) {
753 return PERMISSION_DENIED;
754 }
755
Dima Zavinfce7a472011-04-19 22:30:36 -0700756 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
757 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700758 return BAD_VALUE;
759 }
760
Eric Laurent93575202011-01-18 18:39:02 -0800761 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700762 mStreamTypes[stream].mute = muted;
763 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
764 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
765
766 return NO_ERROR;
767}
768
769float AudioFlinger::streamVolume(int stream, int output) const
770{
Dima Zavinfce7a472011-04-19 22:30:36 -0700771 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700772 return 0.0f;
773 }
774
775 AutoMutex lock(mLock);
776 float volume;
777 if (output) {
778 PlaybackThread *thread = checkPlaybackThread_l(output);
779 if (thread == NULL) {
780 return 0.0f;
781 }
782 volume = thread->streamVolume(stream);
783 } else {
784 volume = mStreamTypes[stream].volume;
785 }
786
787 return volume;
788}
789
790bool AudioFlinger::streamMute(int stream) const
791{
Dima Zavinfce7a472011-04-19 22:30:36 -0700792 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700793 return true;
794 }
795
796 return mStreamTypes[stream].mute;
797}
798
Mathias Agopian65ab4712010-07-14 17:59:35 -0700799status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
800{
801 status_t result;
802
803 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
804 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
805 // check calling permissions
806 if (!settingsAllowed()) {
807 return PERMISSION_DENIED;
808 }
809
Mathias Agopian65ab4712010-07-14 17:59:35 -0700810 // ioHandle == 0 means the parameters are global to the audio hardware interface
811 if (ioHandle == 0) {
812 AutoMutex lock(mHardwareLock);
813 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700814 status_t final_result = NO_ERROR;
815 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
816 audio_hw_device_t *dev = mAudioHwDevs[i];
817 result = dev->set_parameters(dev, keyValuePairs.string());
818 final_result = result ?: final_result;
819 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700820 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700821 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
822 AudioParameter param = AudioParameter(keyValuePairs);
823 String8 value;
824 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
825 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700826 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
827 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700828 for (size_t i = 0; i < mRecordThreads.size(); i++) {
829 sp<RecordThread> thread = mRecordThreads.valueAt(i);
830 RecordThread::RecordTrack *track = thread->track();
831 if (track != NULL) {
832 audio_devices_t device = (audio_devices_t)(
833 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700834 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700835 thread->setEffectSuspended(FX_IID_AEC,
836 suspend,
837 track->sessionId());
838 thread->setEffectSuspended(FX_IID_NS,
839 suspend,
840 track->sessionId());
841 }
842 }
Eric Laurentbee53372011-08-29 12:42:48 -0700843 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700844 }
845 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700846 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700847 }
848
849 // hold a strong ref on thread in case closeOutput() or closeInput() is called
850 // and the thread is exited once the lock is released
851 sp<ThreadBase> thread;
852 {
853 Mutex::Autolock _l(mLock);
854 thread = checkPlaybackThread_l(ioHandle);
855 if (thread == NULL) {
856 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700857 } else if (thread.get() == primaryPlaybackThread_l()) {
858 // indicate output device change to all input threads for pre processing
859 AudioParameter param = AudioParameter(keyValuePairs);
860 int value;
861 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
862 for (size_t i = 0; i < mRecordThreads.size(); i++) {
863 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
864 }
865 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700866 }
867 }
868 if (thread != NULL) {
869 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700870 return result;
871 }
872 return BAD_VALUE;
873}
874
875String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
876{
877// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
878// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
879
880 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700881 String8 out_s8;
882
Dima Zavin799a70e2011-04-18 16:57:27 -0700883 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
884 audio_hw_device_t *dev = mAudioHwDevs[i];
885 char *s = dev->get_parameters(dev, keys.string());
886 out_s8 += String8(s);
887 free(s);
888 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700889 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700890 }
891
892 Mutex::Autolock _l(mLock);
893
894 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
895 if (playbackThread != NULL) {
896 return playbackThread->getParameters(keys);
897 }
898 RecordThread *recordThread = checkRecordThread_l(ioHandle);
899 if (recordThread != NULL) {
900 return recordThread->getParameters(keys);
901 }
902 return String8("");
903}
904
905size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
906{
Eric Laurenta1884f92011-08-23 08:25:03 -0700907 status_t ret = initCheck();
908 if (ret != NO_ERROR) {
909 return 0;
910 }
911
Dima Zavin799a70e2011-04-18 16:57:27 -0700912 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700913}
914
915unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
916{
917 if (ioHandle == 0) {
918 return 0;
919 }
920
921 Mutex::Autolock _l(mLock);
922
923 RecordThread *recordThread = checkRecordThread_l(ioHandle);
924 if (recordThread != NULL) {
925 return recordThread->getInputFramesLost();
926 }
927 return 0;
928}
929
930status_t AudioFlinger::setVoiceVolume(float value)
931{
Eric Laurenta1884f92011-08-23 08:25:03 -0700932 status_t ret = initCheck();
933 if (ret != NO_ERROR) {
934 return ret;
935 }
936
Mathias Agopian65ab4712010-07-14 17:59:35 -0700937 // check calling permissions
938 if (!settingsAllowed()) {
939 return PERMISSION_DENIED;
940 }
941
942 AutoMutex lock(mHardwareLock);
943 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700944 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700945 mHardwareStatus = AUDIO_HW_IDLE;
946
947 return ret;
948}
949
950status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
951{
952 status_t status;
953
954 Mutex::Autolock _l(mLock);
955
956 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
957 if (playbackThread != NULL) {
958 return playbackThread->getRenderPosition(halFrames, dspFrames);
959 }
960
961 return BAD_VALUE;
962}
963
964void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
965{
966
967 Mutex::Autolock _l(mLock);
968
969 int pid = IPCThreadState::self()->getCallingPid();
970 if (mNotificationClients.indexOfKey(pid) < 0) {
971 sp<NotificationClient> notificationClient = new NotificationClient(this,
972 client,
973 pid);
974 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
975
976 mNotificationClients.add(pid, notificationClient);
977
978 sp<IBinder> binder = client->asBinder();
979 binder->linkToDeath(notificationClient);
980
981 // the config change is always sent from playback or record threads to avoid deadlock
982 // with AudioSystem::gLock
983 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
984 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
985 }
986
987 for (size_t i = 0; i < mRecordThreads.size(); i++) {
988 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
989 }
990 }
991}
992
993void AudioFlinger::removeNotificationClient(pid_t pid)
994{
995 Mutex::Autolock _l(mLock);
996
997 int index = mNotificationClients.indexOfKey(pid);
998 if (index >= 0) {
999 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
1000 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001001 mNotificationClients.removeItem(pid);
1002 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001003
1004 LOGV("%d died, releasing its sessions", pid);
1005 int num = mAudioSessionRefs.size();
1006 bool removed = false;
1007 for (int i = 0; i< num; i++) {
1008 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1009 LOGV(" pid %d @ %d", ref->pid, i);
1010 if (ref->pid == pid) {
1011 LOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
1012 mAudioSessionRefs.removeAt(i);
1013 delete ref;
1014 removed = true;
1015 i--;
1016 num--;
1017 }
1018 }
1019 if (removed) {
1020 purgeStaleEffects_l();
1021 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001022}
1023
1024// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1025void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
1026{
1027 size_t size = mNotificationClients.size();
1028 for (size_t i = 0; i < size; i++) {
1029 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
1030 }
1031}
1032
1033// removeClient_l() must be called with AudioFlinger::mLock held
1034void AudioFlinger::removeClient_l(pid_t pid)
1035{
1036 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
1037 mClients.removeItem(pid);
1038}
1039
1040
1041// ----------------------------------------------------------------------------
1042
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001043AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001044 : Thread(false),
1045 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -07001046 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
1047 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001049 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001050}
1051
1052AudioFlinger::ThreadBase::~ThreadBase()
1053{
1054 mParamCond.broadcast();
1055 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001056 // do not lock the mutex in destructor
1057 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001058 if (mPowerManager != 0) {
1059 sp<IBinder> binder = mPowerManager->asBinder();
1060 binder->unlinkToDeath(mDeathRecipient);
1061 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001062}
1063
1064void AudioFlinger::ThreadBase::exit()
1065{
1066 // keep a strong ref on ourself so that we wont get
1067 // destroyed in the middle of requestExitAndWait()
1068 sp <ThreadBase> strongMe = this;
1069
1070 LOGV("ThreadBase::exit");
1071 {
1072 AutoMutex lock(&mLock);
1073 mExiting = true;
1074 requestExit();
1075 mWaitWorkCV.signal();
1076 }
1077 requestExitAndWait();
1078}
1079
1080uint32_t AudioFlinger::ThreadBase::sampleRate() const
1081{
1082 return mSampleRate;
1083}
1084
1085int AudioFlinger::ThreadBase::channelCount() const
1086{
1087 return (int)mChannelCount;
1088}
1089
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001090uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091{
1092 return mFormat;
1093}
1094
1095size_t AudioFlinger::ThreadBase::frameCount() const
1096{
1097 return mFrameCount;
1098}
1099
1100status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1101{
1102 status_t status;
1103
1104 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1105 Mutex::Autolock _l(mLock);
1106
1107 mNewParameters.add(keyValuePairs);
1108 mWaitWorkCV.signal();
1109 // wait condition with timeout in case the thread loop has exited
1110 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001111 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001112 status = mParamStatus;
1113 mWaitWorkCV.signal();
1114 } else {
1115 status = TIMED_OUT;
1116 }
1117 return status;
1118}
1119
1120void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1121{
1122 Mutex::Autolock _l(mLock);
1123 sendConfigEvent_l(event, param);
1124}
1125
1126// sendConfigEvent_l() must be called with ThreadBase::mLock held
1127void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1128{
1129 ConfigEvent *configEvent = new ConfigEvent();
1130 configEvent->mEvent = event;
1131 configEvent->mParam = param;
1132 mConfigEvents.add(configEvent);
1133 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1134 mWaitWorkCV.signal();
1135}
1136
1137void AudioFlinger::ThreadBase::processConfigEvents()
1138{
1139 mLock.lock();
1140 while(!mConfigEvents.isEmpty()) {
1141 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1142 ConfigEvent *configEvent = mConfigEvents[0];
1143 mConfigEvents.removeAt(0);
1144 // release mLock before locking AudioFlinger mLock: lock order is always
1145 // AudioFlinger then ThreadBase to avoid cross deadlock
1146 mLock.unlock();
1147 mAudioFlinger->mLock.lock();
1148 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1149 mAudioFlinger->mLock.unlock();
1150 delete configEvent;
1151 mLock.lock();
1152 }
1153 mLock.unlock();
1154}
1155
1156status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1157{
1158 const size_t SIZE = 256;
1159 char buffer[SIZE];
1160 String8 result;
1161
1162 bool locked = tryLock(mLock);
1163 if (!locked) {
1164 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1165 write(fd, buffer, strlen(buffer));
1166 }
1167
1168 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1169 result.append(buffer);
1170 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1171 result.append(buffer);
1172 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1173 result.append(buffer);
1174 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1175 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001176 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1177 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001178 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1179 result.append(buffer);
1180 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1181 result.append(buffer);
1182
1183 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1184 result.append(buffer);
1185 result.append(" Index Command");
1186 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1187 snprintf(buffer, SIZE, "\n %02d ", i);
1188 result.append(buffer);
1189 result.append(mNewParameters[i]);
1190 }
1191
1192 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1193 result.append(buffer);
1194 snprintf(buffer, SIZE, " Index event param\n");
1195 result.append(buffer);
1196 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1197 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1198 result.append(buffer);
1199 }
1200 result.append("\n");
1201
1202 write(fd, result.string(), result.size());
1203
1204 if (locked) {
1205 mLock.unlock();
1206 }
1207 return NO_ERROR;
1208}
1209
Eric Laurent1d2bff02011-07-24 17:49:51 -07001210status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1211{
1212 const size_t SIZE = 256;
1213 char buffer[SIZE];
1214 String8 result;
1215
1216 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1217 write(fd, buffer, strlen(buffer));
1218
1219 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1220 sp<EffectChain> chain = mEffectChains[i];
1221 if (chain != 0) {
1222 chain->dump(fd, args);
1223 }
1224 }
1225 return NO_ERROR;
1226}
1227
Eric Laurentfeb0db62011-07-22 09:04:31 -07001228void AudioFlinger::ThreadBase::acquireWakeLock()
1229{
1230 Mutex::Autolock _l(mLock);
1231 acquireWakeLock_l();
1232}
1233
1234void AudioFlinger::ThreadBase::acquireWakeLock_l()
1235{
1236 if (mPowerManager == 0) {
1237 // use checkService() to avoid blocking if power service is not up yet
1238 sp<IBinder> binder =
1239 defaultServiceManager()->checkService(String16("power"));
1240 if (binder == 0) {
1241 LOGW("Thread %s cannot connect to the power manager service", mName);
1242 } else {
1243 mPowerManager = interface_cast<IPowerManager>(binder);
1244 binder->linkToDeath(mDeathRecipient);
1245 }
1246 }
1247 if (mPowerManager != 0) {
1248 sp<IBinder> binder = new BBinder();
1249 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1250 binder,
1251 String16(mName));
1252 if (status == NO_ERROR) {
1253 mWakeLockToken = binder;
1254 }
1255 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1256 }
1257}
1258
1259void AudioFlinger::ThreadBase::releaseWakeLock()
1260{
1261 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001262 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001263}
1264
1265void AudioFlinger::ThreadBase::releaseWakeLock_l()
1266{
1267 if (mWakeLockToken != 0) {
1268 LOGV("releaseWakeLock_l() %s", mName);
1269 if (mPowerManager != 0) {
1270 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1271 }
1272 mWakeLockToken.clear();
1273 }
1274}
1275
1276void AudioFlinger::ThreadBase::clearPowerManager()
1277{
1278 Mutex::Autolock _l(mLock);
1279 releaseWakeLock_l();
1280 mPowerManager.clear();
1281}
1282
1283void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1284{
1285 sp<ThreadBase> thread = mThread.promote();
1286 if (thread != 0) {
1287 thread->clearPowerManager();
1288 }
1289 LOGW("power manager service died !!!");
1290}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001291
Eric Laurent59255e42011-07-27 19:49:51 -07001292void AudioFlinger::ThreadBase::setEffectSuspended(
1293 const effect_uuid_t *type, bool suspend, int sessionId)
1294{
1295 Mutex::Autolock _l(mLock);
1296 setEffectSuspended_l(type, suspend, sessionId);
1297}
1298
1299void AudioFlinger::ThreadBase::setEffectSuspended_l(
1300 const effect_uuid_t *type, bool suspend, int sessionId)
1301{
1302 sp<EffectChain> chain;
1303 chain = getEffectChain_l(sessionId);
1304 if (chain != 0) {
1305 if (type != NULL) {
1306 chain->setEffectSuspended_l(type, suspend);
1307 } else {
1308 chain->setEffectSuspendedAll_l(suspend);
1309 }
1310 }
1311
1312 updateSuspendedSessions_l(type, suspend, sessionId);
1313}
1314
1315void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1316{
1317 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1318 if (index < 0) {
1319 return;
1320 }
1321
1322 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1323 mSuspendedSessions.editValueAt(index);
1324
1325 for (size_t i = 0; i < sessionEffects.size(); i++) {
1326 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1327 for (int j = 0; j < desc->mRefCount; j++) {
1328 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1329 chain->setEffectSuspendedAll_l(true);
1330 } else {
1331 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1332 desc->mType.timeLow);
1333 chain->setEffectSuspended_l(&desc->mType, true);
1334 }
1335 }
1336 }
1337}
1338
Eric Laurent59255e42011-07-27 19:49:51 -07001339void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1340 bool suspend,
1341 int sessionId)
1342{
1343 int index = mSuspendedSessions.indexOfKey(sessionId);
1344
1345 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1346
1347 if (suspend) {
1348 if (index >= 0) {
1349 sessionEffects = mSuspendedSessions.editValueAt(index);
1350 } else {
1351 mSuspendedSessions.add(sessionId, sessionEffects);
1352 }
1353 } else {
1354 if (index < 0) {
1355 return;
1356 }
1357 sessionEffects = mSuspendedSessions.editValueAt(index);
1358 }
1359
1360
1361 int key = EffectChain::kKeyForSuspendAll;
1362 if (type != NULL) {
1363 key = type->timeLow;
1364 }
1365 index = sessionEffects.indexOfKey(key);
1366
1367 sp <SuspendedSessionDesc> desc;
1368 if (suspend) {
1369 if (index >= 0) {
1370 desc = sessionEffects.valueAt(index);
1371 } else {
1372 desc = new SuspendedSessionDesc();
1373 if (type != NULL) {
1374 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1375 }
1376 sessionEffects.add(key, desc);
1377 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1378 }
1379 desc->mRefCount++;
1380 } else {
1381 if (index < 0) {
1382 return;
1383 }
1384 desc = sessionEffects.valueAt(index);
1385 if (--desc->mRefCount == 0) {
1386 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1387 sessionEffects.removeItemsAt(index);
1388 if (sessionEffects.isEmpty()) {
1389 LOGV("updateSuspendedSessions_l() restore removing session %d",
1390 sessionId);
1391 mSuspendedSessions.removeItem(sessionId);
1392 }
1393 }
1394 }
1395 if (!sessionEffects.isEmpty()) {
1396 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1397 }
1398}
1399
1400void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1401 bool enabled,
1402 int sessionId)
1403{
1404 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001405 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1406}
Eric Laurent59255e42011-07-27 19:49:51 -07001407
Eric Laurenta85a74a2011-10-19 11:44:54 -07001408void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1409 bool enabled,
1410 int sessionId)
1411{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001412 if (mType != RECORD) {
1413 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1414 // another session. This gives the priority to well behaved effect control panels
1415 // and applications not using global effects.
1416 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1417 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1418 }
1419 }
Eric Laurent59255e42011-07-27 19:49:51 -07001420
1421 sp<EffectChain> chain = getEffectChain_l(sessionId);
1422 if (chain != 0) {
1423 chain->checkSuspendOnEffectEnabled(effect, enabled);
1424 }
1425}
1426
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427// ----------------------------------------------------------------------------
1428
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001429AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1430 AudioStreamOut* output,
1431 int id,
1432 uint32_t device)
1433 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001435 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001437 snprintf(mName, kNameLength, "AudioOut_%d", id);
1438
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 readOutputParameters();
1440
Mike J. Chen500e5102011-08-15 13:28:26 -07001441 mMasterVolume = mAudioFlinger->masterVolumeSW();
1442
Mathias Agopian65ab4712010-07-14 17:59:35 -07001443 mMasterMute = mAudioFlinger->masterMute();
1444
Dima Zavinfce7a472011-04-19 22:30:36 -07001445 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001446 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1447 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001448 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001449 }
1450}
1451
1452AudioFlinger::PlaybackThread::~PlaybackThread()
1453{
1454 delete [] mMixBuffer;
1455}
1456
1457status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1458{
1459 dumpInternals(fd, args);
1460 dumpTracks(fd, args);
1461 dumpEffectChains(fd, args);
1462 return NO_ERROR;
1463}
1464
1465status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1466{
1467 const size_t SIZE = 256;
1468 char buffer[SIZE];
1469 String8 result;
1470
1471 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1472 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001473 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 -07001474 for (size_t i = 0; i < mTracks.size(); ++i) {
1475 sp<Track> track = mTracks[i];
1476 if (track != 0) {
1477 track->dump(buffer, SIZE);
1478 result.append(buffer);
1479 }
1480 }
1481
1482 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1483 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001484 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 -07001485 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1486 wp<Track> wTrack = mActiveTracks[i];
1487 if (wTrack != 0) {
1488 sp<Track> track = wTrack.promote();
1489 if (track != 0) {
1490 track->dump(buffer, SIZE);
1491 result.append(buffer);
1492 }
1493 }
1494 }
1495 write(fd, result.string(), result.size());
1496 return NO_ERROR;
1497}
1498
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1500{
1501 const size_t SIZE = 256;
1502 char buffer[SIZE];
1503 String8 result;
1504
1505 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1506 result.append(buffer);
1507 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1508 result.append(buffer);
1509 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1510 result.append(buffer);
1511 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1512 result.append(buffer);
1513 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1514 result.append(buffer);
1515 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1516 result.append(buffer);
1517 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1518 result.append(buffer);
1519 write(fd, result.string(), result.size());
1520
1521 dumpBase(fd, args);
1522
1523 return NO_ERROR;
1524}
1525
1526// Thread virtuals
1527status_t AudioFlinger::PlaybackThread::readyToRun()
1528{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001529 status_t status = initCheck();
1530 if (status == NO_ERROR) {
1531 LOGI("AudioFlinger's thread %p ready to run", this);
1532 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001533 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001534 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001535 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001536}
1537
1538void AudioFlinger::PlaybackThread::onFirstRef()
1539{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001540 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541}
1542
1543// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1544sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1545 const sp<AudioFlinger::Client>& client,
1546 int streamType,
1547 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001548 uint32_t format,
1549 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001550 int frameCount,
1551 const sp<IMemory>& sharedBuffer,
1552 int sessionId,
Mike J. Chen500e5102011-08-15 13:28:26 -07001553 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001554 status_t *status)
1555{
1556 sp<Track> track;
1557 status_t lStatus;
1558
1559 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001560 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1561 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1562 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1563 "for output %p with format %d",
1564 sampleRate, format, channelMask, mOutput, mFormat);
1565 lStatus = BAD_VALUE;
1566 goto Exit;
1567 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 }
1569 } else {
1570 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1571 if (sampleRate > mSampleRate*2) {
1572 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1573 lStatus = BAD_VALUE;
1574 goto Exit;
1575 }
1576 }
1577
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001578 lStatus = initCheck();
1579 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001580 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001581 goto Exit;
1582 }
1583
1584 { // scope for mLock
1585 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001586
1587 // all tracks in same audio session must share the same routing strategy otherwise
1588 // conflicts will happen when tracks are moved from one output to another by audio policy
1589 // manager
1590 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001591 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001592 for (size_t i = 0; i < mTracks.size(); ++i) {
1593 sp<Track> t = mTracks[i];
1594 if (t != 0) {
1595 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001596 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001597 lStatus = BAD_VALUE;
1598 goto Exit;
1599 }
1600 }
1601 }
1602
Mike J. Chen500e5102011-08-15 13:28:26 -07001603 if (!isTimed) {
1604 track = new Track(this, client, streamType, sampleRate, format,
1605 channelMask, frameCount, sharedBuffer, sessionId);
1606 } else {
1607 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1608 channelMask, frameCount, sharedBuffer, sessionId);
1609 }
1610 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611 lStatus = NO_MEMORY;
1612 goto Exit;
1613 }
1614 mTracks.add(track);
1615
1616 sp<EffectChain> chain = getEffectChain_l(sessionId);
1617 if (chain != 0) {
1618 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1619 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001620 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001621 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001622 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001623
1624 // invalidate track immediately if the stream type was moved to another thread since
1625 // createTrack() was called by the client process.
1626 if (!mStreamTypes[streamType].valid) {
1627 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1628 this, streamType);
1629 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631 }
1632 lStatus = NO_ERROR;
1633
1634Exit:
1635 if(status) {
1636 *status = lStatus;
1637 }
1638 return track;
1639}
1640
1641uint32_t AudioFlinger::PlaybackThread::latency() const
1642{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001643 Mutex::Autolock _l(mLock);
1644 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001645 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001646 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647 return 0;
1648 }
1649}
1650
1651status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1652{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001653 mMasterVolume = value;
1654 return NO_ERROR;
1655}
1656
1657status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1658{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 mMasterMute = muted;
1660 return NO_ERROR;
1661}
1662
1663float AudioFlinger::PlaybackThread::masterVolume() const
1664{
1665 return mMasterVolume;
1666}
1667
1668bool AudioFlinger::PlaybackThread::masterMute() const
1669{
1670 return mMasterMute;
1671}
1672
1673status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1674{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001675 mStreamTypes[stream].volume = value;
1676 return NO_ERROR;
1677}
1678
1679status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1680{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681 mStreamTypes[stream].mute = muted;
1682 return NO_ERROR;
1683}
1684
1685float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1686{
1687 return mStreamTypes[stream].volume;
1688}
1689
1690bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1691{
1692 return mStreamTypes[stream].mute;
1693}
1694
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695// addTrack_l() must be called with ThreadBase::mLock held
1696status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1697{
1698 status_t status = ALREADY_EXISTS;
1699
1700 // set retry count for buffer fill
1701 track->mRetryCount = kMaxTrackStartupRetries;
1702 if (mActiveTracks.indexOf(track) < 0) {
1703 // the track is newly added, make sure it fills up all its
1704 // buffers before playing. This is to ensure the client will
1705 // effectively get the latency it requested.
1706 track->mFillingUpStatus = Track::FS_FILLING;
1707 track->mResetDone = false;
1708 mActiveTracks.add(track);
1709 if (track->mainBuffer() != mMixBuffer) {
1710 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1711 if (chain != 0) {
1712 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001713 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001714 }
1715 }
1716
1717 status = NO_ERROR;
1718 }
1719
1720 LOGV("mWaitWorkCV.broadcast");
1721 mWaitWorkCV.broadcast();
1722
1723 return status;
1724}
1725
1726// destroyTrack_l() must be called with ThreadBase::mLock held
1727void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1728{
1729 track->mState = TrackBase::TERMINATED;
1730 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001731 removeTrack_l(track);
1732 }
1733}
1734
1735void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1736{
1737 mTracks.remove(track);
1738 deleteTrackName_l(track->name());
1739 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1740 if (chain != 0) {
1741 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 }
1743}
1744
1745String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1746{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001747 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001748 char *s;
1749
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001750 Mutex::Autolock _l(mLock);
1751 if (initCheck() != NO_ERROR) {
1752 return out_s8;
1753 }
1754
Dima Zavin799a70e2011-04-18 16:57:27 -07001755 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001756 out_s8 = String8(s);
1757 free(s);
1758 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759}
1760
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001761// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1763 AudioSystem::OutputDescriptor desc;
1764 void *param2 = 0;
1765
1766 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1767
1768 switch (event) {
1769 case AudioSystem::OUTPUT_OPENED:
1770 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001771 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001772 desc.samplingRate = mSampleRate;
1773 desc.format = mFormat;
1774 desc.frameCount = mFrameCount;
1775 desc.latency = latency();
1776 param2 = &desc;
1777 break;
1778
1779 case AudioSystem::STREAM_CONFIG_CHANGED:
1780 param2 = &param;
1781 case AudioSystem::OUTPUT_CLOSED:
1782 default:
1783 break;
1784 }
1785 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1786}
1787
1788void AudioFlinger::PlaybackThread::readOutputParameters()
1789{
Dima Zavin799a70e2011-04-18 16:57:27 -07001790 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001791 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1792 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001793 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1794 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1795 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001796
1797 // FIXME - Current mixer implementation only supports stereo output: Always
1798 // Allocate a stereo buffer even if HW output is mono.
1799 if (mMixBuffer != NULL) delete[] mMixBuffer;
1800 mMixBuffer = new int16_t[mFrameCount * 2];
1801 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1802
Eric Laurentde070132010-07-13 04:45:46 -07001803 // force reconfiguration of effect chains and engines to take new buffer size and audio
1804 // parameters into account
1805 // Note that mLock is not held when readOutputParameters() is called from the constructor
1806 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1807 // matter.
1808 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1809 Vector< sp<EffectChain> > effectChains = mEffectChains;
1810 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001811 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001812 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813}
1814
1815status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1816{
1817 if (halFrames == 0 || dspFrames == 0) {
1818 return BAD_VALUE;
1819 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001820 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001821 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 return INVALID_OPERATION;
1823 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001824 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825
Dima Zavin799a70e2011-04-18 16:57:27 -07001826 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001827}
1828
Eric Laurent39e94f82010-07-28 01:32:47 -07001829uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001830{
1831 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001832 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001834 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001835 }
1836
1837 for (size_t i = 0; i < mTracks.size(); ++i) {
1838 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001839 if (sessionId == track->sessionId() &&
1840 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001841 result |= TRACK_SESSION;
1842 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843 }
1844 }
1845
Eric Laurent39e94f82010-07-28 01:32:47 -07001846 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001847}
1848
Eric Laurentde070132010-07-13 04:45:46 -07001849uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1850{
Dima Zavinfce7a472011-04-19 22:30:36 -07001851 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001852 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001853 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1854 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001855 }
1856 for (size_t i = 0; i < mTracks.size(); i++) {
1857 sp<Track> track = mTracks[i];
1858 if (sessionId == track->sessionId() &&
1859 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001860 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001861 }
1862 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001863 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001864}
1865
Mathias Agopian65ab4712010-07-14 17:59:35 -07001866
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001867AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1868{
1869 Mutex::Autolock _l(mLock);
1870 return mOutput;
1871}
1872
1873AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1874{
1875 Mutex::Autolock _l(mLock);
1876 AudioStreamOut *output = mOutput;
1877 mOutput = NULL;
1878 return output;
1879}
1880
1881// this method must always be called either with ThreadBase mLock held or inside the thread loop
1882audio_stream_t* AudioFlinger::PlaybackThread::stream()
1883{
1884 if (mOutput == NULL) {
1885 return NULL;
1886 }
1887 return &mOutput->stream->common;
1888}
1889
Mathias Agopian65ab4712010-07-14 17:59:35 -07001890// ----------------------------------------------------------------------------
1891
Dima Zavin799a70e2011-04-18 16:57:27 -07001892AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 : PlaybackThread(audioFlinger, output, id, device),
1894 mAudioMixer(0)
1895{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001896 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1898
1899 // FIXME - Current mixer implementation only supports stereo output
1900 if (mChannelCount == 1) {
1901 LOGE("Invalid audio hardware channel count");
1902 }
1903}
1904
1905AudioFlinger::MixerThread::~MixerThread()
1906{
1907 delete mAudioMixer;
1908}
1909
1910bool AudioFlinger::MixerThread::threadLoop()
1911{
1912 Vector< sp<Track> > tracksToRemove;
1913 uint32_t mixerStatus = MIXER_IDLE;
1914 nsecs_t standbyTime = systemTime();
1915 size_t mixBufferSize = mFrameCount * mFrameSize;
1916 // FIXME: Relaxed timing because of a certain device that can't meet latency
1917 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001918 // increase threshold again due to low power audio mode. The way this warning threshold is
1919 // calculated and its usefulness should be reconsidered anyway.
1920 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921 nsecs_t lastWarning = 0;
1922 bool longStandbyExit = false;
1923 uint32_t activeSleepTime = activeSleepTimeUs();
1924 uint32_t idleSleepTime = idleSleepTimeUs();
1925 uint32_t sleepTime = idleSleepTime;
1926 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001927#ifdef DEBUG_CPU_USAGE
1928 ThreadCpuUsage cpu;
1929 const CentralTendencyStatistics& stats = cpu.statistics();
1930#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001931
Eric Laurentfeb0db62011-07-22 09:04:31 -07001932 acquireWakeLock();
1933
Mike J. Chen500e5102011-08-15 13:28:26 -07001934 LocalClock lc;
1935 uint64_t localTimeFreq;
1936 localTimeFreq = lc.getLocalFreq();
1937
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 while (!exitPending())
1939 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001940#ifdef DEBUG_CPU_USAGE
1941 cpu.sampleAndEnable();
1942 unsigned n = stats.n();
1943 // cpu.elapsed() is expensive, so don't call it every loop
1944 if ((n & 127) == 1) {
1945 long long elapsed = cpu.elapsed();
1946 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1947 double perLoop = elapsed / (double) n;
1948 double perLoop100 = perLoop * 0.01;
1949 double mean = stats.mean();
1950 double stddev = stats.stddev();
1951 double minimum = stats.minimum();
1952 double maximum = stats.maximum();
1953 cpu.resetStatistics();
1954 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",
1955 elapsed * .000000001, n, perLoop * .000001,
1956 mean * .001,
1957 stddev * .001,
1958 minimum * .001,
1959 maximum * .001,
1960 mean / perLoop100,
1961 stddev / perLoop100,
1962 minimum / perLoop100,
1963 maximum / perLoop100);
1964 }
1965 }
1966#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 processConfigEvents();
1968
1969 mixerStatus = MIXER_IDLE;
1970 { // scope for mLock
1971
1972 Mutex::Autolock _l(mLock);
1973
1974 if (checkForNewParameters_l()) {
1975 mixBufferSize = mFrameCount * mFrameSize;
1976 // FIXME: Relaxed timing because of a certain device that can't meet latency
1977 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001978 // increase threshold again due to low power audio mode. The way this warning
1979 // threshold is calculated and its usefulness should be reconsidered anyway.
1980 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001981 activeSleepTime = activeSleepTimeUs();
1982 idleSleepTime = idleSleepTimeUs();
1983 }
1984
1985 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1986
1987 // put audio hardware into standby after short delay
1988 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1989 mSuspended) {
1990 if (!mStandby) {
1991 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001992 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001993 mStandby = true;
1994 mBytesWritten = 0;
1995 }
1996
1997 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1998 // we're about to wait, flush the binder command buffer
1999 IPCThreadState::self()->flushCommands();
2000
2001 if (exitPending()) break;
2002
Eric Laurentfeb0db62011-07-22 09:04:31 -07002003 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004 // wait until we have something to do...
2005 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
2006 mWaitWorkCV.wait(mLock);
2007 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002008 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002009
2010 if (mMasterMute == false) {
2011 char value[PROPERTY_VALUE_MAX];
2012 property_get("ro.audio.silent", value, "0");
2013 if (atoi(value)) {
2014 LOGD("Silence is golden");
2015 setMasterMute(true);
2016 }
2017 }
2018
2019 standbyTime = systemTime() + kStandbyTimeInNsecs;
2020 sleepTime = idleSleepTime;
2021 continue;
2022 }
2023 }
2024
2025 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2026
2027 // prevent any changes in effect chain list and in each effect chain
2028 // during mixing and effect process as the audio buffers could be deleted
2029 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002030 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002031 }
2032
2033 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mike J. Chen500e5102011-08-15 13:28:26 -07002034 // obtain the presentation timestamp of the next output buffer
2035 int64_t pts;
John Grossman94dacaf2011-08-29 10:26:47 -07002036 status_t status = INVALID_OPERATION;
2037
2038 if (NULL != mOutput->stream->get_next_write_timestamp) {
2039 status = mOutput->stream->get_next_write_timestamp(
2040 mOutput->stream, &pts);
2041 }
2042
Mike J. Chen500e5102011-08-15 13:28:26 -07002043 if (status != NO_ERROR) {
2044 pts = AudioBufferProvider::kInvalidPTS;
2045 }
2046
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 // mix buffers...
Mike J. Chen500e5102011-08-15 13:28:26 -07002048 mAudioMixer->process(pts);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002049 sleepTime = 0;
2050 standbyTime = systemTime() + kStandbyTimeInNsecs;
2051 //TODO: delay standby when effects have a tail
2052 } else {
2053 // If no tracks are ready, sleep once for the duration of an output
2054 // buffer size, then write 0s to the output
2055 if (sleepTime == 0) {
2056 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2057 sleepTime = activeSleepTime;
2058 } else {
2059 sleepTime = idleSleepTime;
2060 }
2061 } else if (mBytesWritten != 0 ||
2062 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2063 memset (mMixBuffer, 0, mixBufferSize);
2064 sleepTime = 0;
2065 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2066 }
2067 // TODO add standby time extension fct of effect tail
2068 }
2069
2070 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002071 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 }
2073 // sleepTime == 0 means we must write to audio hardware
2074 if (sleepTime == 0) {
2075 for (size_t i = 0; i < effectChains.size(); i ++) {
2076 effectChains[i]->process_l();
2077 }
2078 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002079 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 mLastWriteTime = systemTime();
2081 mInWrite = true;
2082 mBytesWritten += mixBufferSize;
2083
Dima Zavin799a70e2011-04-18 16:57:27 -07002084 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002085 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2086 mNumWrites++;
2087 mInWrite = false;
2088 nsecs_t now = systemTime();
2089 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002090 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 mNumDelayedWrites++;
2092 if ((now - lastWarning) > kWarningThrottle) {
2093 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2094 ns2ms(delta), mNumDelayedWrites, this);
2095 lastWarning = now;
2096 }
2097 if (mStandby) {
2098 longStandbyExit = true;
2099 }
2100 }
2101 mStandby = false;
2102 } else {
2103 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002104 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 usleep(sleepTime);
2106 }
2107
2108 // finally let go of all our tracks, without the lock held
2109 // since we can't guarantee the destructors won't acquire that
2110 // same lock.
2111 tracksToRemove.clear();
2112
2113 // Effect chains will be actually deleted here if they were removed from
2114 // mEffectChains list during mixing or effects processing
2115 effectChains.clear();
2116 }
2117
2118 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002119 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120 }
2121
Eric Laurentfeb0db62011-07-22 09:04:31 -07002122 releaseWakeLock();
2123
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 LOGV("MixerThread %p exiting", this);
2125 return false;
2126}
2127
2128// prepareTracks_l() must be called with ThreadBase::mLock held
2129uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2130{
2131
2132 uint32_t mixerStatus = MIXER_IDLE;
2133 // find out which tracks need to be processed
2134 size_t count = activeTracks.size();
2135 size_t mixedTracks = 0;
2136 size_t tracksWithEffect = 0;
2137
2138 float masterVolume = mMasterVolume;
2139 bool masterMute = mMasterMute;
2140
Eric Laurent571d49c2010-08-11 05:20:11 -07002141 if (masterMute) {
2142 masterVolume = 0;
2143 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002145 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002146 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002147 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002148 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002149 masterVolume = (float)((v + (1 << 23)) >> 24);
2150 chain.clear();
2151 }
2152
2153 for (size_t i=0 ; i<count ; i++) {
2154 sp<Track> t = activeTracks[i].promote();
2155 if (t == 0) continue;
2156
2157 Track* const track = t.get();
2158 audio_track_cblk_t* cblk = track->cblk();
2159
2160 // The first time a track is added we wait
2161 // for all its buffers to be filled before processing it
2162 mAudioMixer->setActiveTrack(track->name());
Mike J. Chen500e5102011-08-15 13:28:26 -07002163 if (track->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002164 !track->isPaused() && !track->isTerminated())
2165 {
2166 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
2167
2168 mixedTracks++;
2169
2170 // track->mainBuffer() != mMixBuffer means there is an effect chain
2171 // connected to the track
2172 chain.clear();
2173 if (track->mainBuffer() != mMixBuffer) {
2174 chain = getEffectChain_l(track->sessionId());
2175 // Delegate volume control to effect in track effect chain if needed
2176 if (chain != 0) {
2177 tracksWithEffect++;
2178 } else {
2179 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2180 track->name(), track->sessionId());
2181 }
2182 }
2183
2184
2185 int param = AudioMixer::VOLUME;
2186 if (track->mFillingUpStatus == Track::FS_FILLED) {
2187 // no ramp for the first volume setting
2188 track->mFillingUpStatus = Track::FS_ACTIVE;
2189 if (track->mState == TrackBase::RESUMING) {
2190 track->mState = TrackBase::ACTIVE;
2191 param = AudioMixer::RAMP_VOLUME;
2192 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002193 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002194 } else if (cblk->server != 0) {
2195 // If the track is stopped before the first frame was mixed,
2196 // do not apply ramp
2197 param = AudioMixer::RAMP_VOLUME;
2198 }
2199
2200 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002201 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002202 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002204 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 if (track->isPausing()) {
2206 track->setPaused();
2207 }
2208 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002209
Mathias Agopian65ab4712010-07-14 17:59:35 -07002210 // read original volumes with volume control
2211 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002212 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002213 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2214 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215
Eric Laurente0aed6d2010-09-10 17:44:44 -07002216 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002217 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002218 // Delegate volume control to effect in track effect chain if needed
2219 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2220 // Do not ramp volume if volume is controlled by effect
2221 param = AudioMixer::VOLUME;
2222 track->mHasVolumeController = true;
2223 } else {
2224 // force no volume ramp when volume controller was just disabled or removed
2225 // from effect chain to avoid volume spike
2226 if (track->mHasVolumeController) {
2227 param = AudioMixer::VOLUME;
2228 }
2229 track->mHasVolumeController = false;
2230 }
2231
2232 // Convert volumes from 8.24 to 4.12 format
2233 int16_t left, right, aux;
2234 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2235 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2236 left = int16_t(v_clamped);
2237 v_clamped = (vr + (1 << 11)) >> 12;
2238 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2239 right = int16_t(v_clamped);
2240
2241 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2242 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243
Mathias Agopian65ab4712010-07-14 17:59:35 -07002244 // XXX: these things DON'T need to be done each time
2245 mAudioMixer->setBufferProvider(track);
2246 mAudioMixer->enable(AudioMixer::MIXING);
2247
2248 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2249 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2250 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2251 mAudioMixer->setParameter(
2252 AudioMixer::TRACK,
2253 AudioMixer::FORMAT, (void *)track->format());
2254 mAudioMixer->setParameter(
2255 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002256 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002257 mAudioMixer->setParameter(
2258 AudioMixer::RESAMPLE,
2259 AudioMixer::SAMPLE_RATE,
2260 (void *)(cblk->sampleRate));
2261 mAudioMixer->setParameter(
2262 AudioMixer::TRACK,
2263 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2264 mAudioMixer->setParameter(
2265 AudioMixer::TRACK,
2266 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2267
2268 // reset retry count
2269 track->mRetryCount = kMaxTrackRetries;
2270 mixerStatus = MIXER_TRACKS_READY;
2271 } else {
2272 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2273 if (track->isStopped()) {
2274 track->reset();
2275 }
2276 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2277 // We have consumed all the buffers of this track.
2278 // Remove it from the list of active tracks.
2279 tracksToRemove->add(track);
2280 } else {
2281 // No buffers for this track. Give it a few chances to
2282 // fill a buffer, then remove it from active list.
2283 if (--(track->mRetryCount) <= 0) {
2284 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2285 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002286 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002287 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002288 } else if (mixerStatus != MIXER_TRACKS_READY) {
2289 mixerStatus = MIXER_TRACKS_ENABLED;
2290 }
2291 }
2292 mAudioMixer->disable(AudioMixer::MIXING);
2293 }
2294 }
2295
2296 // remove all the tracks that need to be...
2297 count = tracksToRemove->size();
2298 if (UNLIKELY(count)) {
2299 for (size_t i=0 ; i<count ; i++) {
2300 const sp<Track>& track = tracksToRemove->itemAt(i);
2301 mActiveTracks.remove(track);
2302 if (track->mainBuffer() != mMixBuffer) {
2303 chain = getEffectChain_l(track->sessionId());
2304 if (chain != 0) {
2305 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002306 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002307 }
2308 }
2309 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002310 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311 }
2312 }
2313 }
2314
2315 // mix buffer must be cleared if all tracks are connected to an
2316 // effect chain as in this case the mixer will not write to
2317 // mix buffer and track effects will accumulate into it
2318 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2319 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2320 }
2321
2322 return mixerStatus;
2323}
2324
2325void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2326{
Eric Laurentde070132010-07-13 04:45:46 -07002327 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2328 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002329 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002330
Mathias Agopian65ab4712010-07-14 17:59:35 -07002331 size_t size = mTracks.size();
2332 for (size_t i = 0; i < size; i++) {
2333 sp<Track> t = mTracks[i];
2334 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002335 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002336 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002337 }
2338 }
2339}
2340
Eric Laurent9f6530f2011-08-30 10:18:54 -07002341void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2342{
2343 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2344 this, streamType, valid);
2345 Mutex::Autolock _l(mLock);
2346
2347 mStreamTypes[streamType].valid = valid;
2348}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002349
2350// getTrackName_l() must be called with ThreadBase::mLock held
2351int AudioFlinger::MixerThread::getTrackName_l()
2352{
2353 return mAudioMixer->getTrackName();
2354}
2355
2356// deleteTrackName_l() must be called with ThreadBase::mLock held
2357void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2358{
2359 LOGV("remove track (%d) and delete from mixer", name);
2360 mAudioMixer->deleteTrackName(name);
2361}
2362
2363// checkForNewParameters_l() must be called with ThreadBase::mLock held
2364bool AudioFlinger::MixerThread::checkForNewParameters_l()
2365{
2366 bool reconfig = false;
2367
2368 while (!mNewParameters.isEmpty()) {
2369 status_t status = NO_ERROR;
2370 String8 keyValuePair = mNewParameters[0];
2371 AudioParameter param = AudioParameter(keyValuePair);
2372 int value;
2373
2374 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2375 reconfig = true;
2376 }
2377 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002378 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002379 status = BAD_VALUE;
2380 } else {
2381 reconfig = true;
2382 }
2383 }
2384 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002385 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 status = BAD_VALUE;
2387 } else {
2388 reconfig = true;
2389 }
2390 }
2391 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2392 // do not accept frame count changes if tracks are open as the track buffer
2393 // size depends on frame count and correct behavior would not be garantied
2394 // if frame count is changed after track creation
2395 if (!mTracks.isEmpty()) {
2396 status = INVALID_OPERATION;
2397 } else {
2398 reconfig = true;
2399 }
2400 }
2401 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002402 // when changing the audio output device, call addBatteryData to notify
2403 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002404 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002405 uint32_t params = 0;
2406 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002407 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002408 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2409 }
2410
2411 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002412 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002413 // check if any other device (except speaker) is on
2414 if (value & deviceWithoutSpeaker ) {
2415 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2416 }
2417
2418 if (params != 0) {
2419 addBatteryData(params);
2420 }
2421 }
2422
Mathias Agopian65ab4712010-07-14 17:59:35 -07002423 // forward device change to effects that have requested to be
2424 // aware of attached audio device.
2425 mDevice = (uint32_t)value;
2426 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002427 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002428 }
2429 }
2430
2431 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002432 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002433 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002434 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002435 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002436 mStandby = true;
2437 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002438 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002439 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002440 }
2441 if (status == NO_ERROR && reconfig) {
2442 delete mAudioMixer;
2443 readOutputParameters();
2444 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2445 for (size_t i = 0; i < mTracks.size() ; i++) {
2446 int name = getTrackName_l();
2447 if (name < 0) break;
2448 mTracks[i]->mName = name;
2449 // limit track sample rate to 2 x new output sample rate
2450 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2451 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2452 }
2453 }
2454 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2455 }
2456 }
2457
2458 mNewParameters.removeAt(0);
2459
2460 mParamStatus = status;
2461 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002462 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2463 // already timed out waiting for the status and will never signal the condition.
2464 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 }
2466 return reconfig;
2467}
2468
2469status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2470{
2471 const size_t SIZE = 256;
2472 char buffer[SIZE];
2473 String8 result;
2474
2475 PlaybackThread::dumpInternals(fd, args);
2476
2477 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2478 result.append(buffer);
2479 write(fd, result.string(), result.size());
2480 return NO_ERROR;
2481}
2482
2483uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2484{
Dima Zavin799a70e2011-04-18 16:57:27 -07002485 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486}
2487
2488uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2489{
Eric Laurent60e18242010-07-29 06:50:24 -07002490 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002491}
2492
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002493uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2494{
2495 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2496}
2497
Mathias Agopian65ab4712010-07-14 17:59:35 -07002498// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002499AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002500 : PlaybackThread(audioFlinger, output, id, device)
2501{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002502 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002503}
2504
2505AudioFlinger::DirectOutputThread::~DirectOutputThread()
2506{
2507}
2508
2509
2510static inline int16_t clamp16(int32_t sample)
2511{
2512 if ((sample>>15) ^ (sample>>31))
2513 sample = 0x7FFF ^ (sample>>31);
2514 return sample;
2515}
2516
2517static inline
2518int32_t mul(int16_t in, int16_t v)
2519{
2520#if defined(__arm__) && !defined(__thumb__)
2521 int32_t out;
2522 asm( "smulbb %[out], %[in], %[v] \n"
2523 : [out]"=r"(out)
2524 : [in]"%r"(in), [v]"r"(v)
2525 : );
2526 return out;
2527#else
2528 return in * int32_t(v);
2529#endif
2530}
2531
2532void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2533{
2534 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002535 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002536 return;
2537 }
2538
2539 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002540 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002541 size_t count = mFrameCount * mChannelCount;
2542 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2543 int16_t *dst = mMixBuffer + count-1;
2544 while(count--) {
2545 *dst-- = (int16_t)(*src--^0x80) << 8;
2546 }
2547 }
2548
2549 size_t frameCount = mFrameCount;
2550 int16_t *out = mMixBuffer;
2551 if (ramp) {
2552 if (mChannelCount == 1) {
2553 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2554 int32_t vlInc = d / (int32_t)frameCount;
2555 int32_t vl = ((int32_t)mLeftVolShort << 16);
2556 do {
2557 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2558 out++;
2559 vl += vlInc;
2560 } while (--frameCount);
2561
2562 } else {
2563 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2564 int32_t vlInc = d / (int32_t)frameCount;
2565 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2566 int32_t vrInc = d / (int32_t)frameCount;
2567 int32_t vl = ((int32_t)mLeftVolShort << 16);
2568 int32_t vr = ((int32_t)mRightVolShort << 16);
2569 do {
2570 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2571 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2572 out += 2;
2573 vl += vlInc;
2574 vr += vrInc;
2575 } while (--frameCount);
2576 }
2577 } else {
2578 if (mChannelCount == 1) {
2579 do {
2580 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2581 out++;
2582 } while (--frameCount);
2583 } else {
2584 do {
2585 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2586 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2587 out += 2;
2588 } while (--frameCount);
2589 }
2590 }
2591
2592 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002593 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002594 size_t count = mFrameCount * mChannelCount;
2595 int16_t *src = mMixBuffer;
2596 uint8_t *dst = (uint8_t *)mMixBuffer;
2597 while(count--) {
2598 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2599 }
2600 }
2601
2602 mLeftVolShort = leftVol;
2603 mRightVolShort = rightVol;
2604}
2605
2606bool AudioFlinger::DirectOutputThread::threadLoop()
2607{
2608 uint32_t mixerStatus = MIXER_IDLE;
2609 sp<Track> trackToRemove;
2610 sp<Track> activeTrack;
2611 nsecs_t standbyTime = systemTime();
2612 int8_t *curBuf;
2613 size_t mixBufferSize = mFrameCount*mFrameSize;
2614 uint32_t activeSleepTime = activeSleepTimeUs();
2615 uint32_t idleSleepTime = idleSleepTimeUs();
2616 uint32_t sleepTime = idleSleepTime;
2617 // use shorter standby delay as on normal output to release
2618 // hardware resources as soon as possible
2619 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2620
Eric Laurentfeb0db62011-07-22 09:04:31 -07002621 acquireWakeLock();
2622
Mathias Agopian65ab4712010-07-14 17:59:35 -07002623 while (!exitPending())
2624 {
2625 bool rampVolume;
2626 uint16_t leftVol;
2627 uint16_t rightVol;
2628 Vector< sp<EffectChain> > effectChains;
2629
2630 processConfigEvents();
2631
2632 mixerStatus = MIXER_IDLE;
2633
2634 { // scope for the mLock
2635
2636 Mutex::Autolock _l(mLock);
2637
2638 if (checkForNewParameters_l()) {
2639 mixBufferSize = mFrameCount*mFrameSize;
2640 activeSleepTime = activeSleepTimeUs();
2641 idleSleepTime = idleSleepTimeUs();
2642 standbyDelay = microseconds(activeSleepTime*2);
2643 }
2644
2645 // put audio hardware into standby after short delay
2646 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2647 mSuspended) {
2648 // wait until we have something to do...
2649 if (!mStandby) {
2650 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002651 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002652 mStandby = true;
2653 mBytesWritten = 0;
2654 }
2655
2656 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2657 // we're about to wait, flush the binder command buffer
2658 IPCThreadState::self()->flushCommands();
2659
2660 if (exitPending()) break;
2661
Eric Laurentfeb0db62011-07-22 09:04:31 -07002662 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002663 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2664 mWaitWorkCV.wait(mLock);
2665 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002666 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667
2668 if (mMasterMute == false) {
2669 char value[PROPERTY_VALUE_MAX];
2670 property_get("ro.audio.silent", value, "0");
2671 if (atoi(value)) {
2672 LOGD("Silence is golden");
2673 setMasterMute(true);
2674 }
2675 }
2676
2677 standbyTime = systemTime() + standbyDelay;
2678 sleepTime = idleSleepTime;
2679 continue;
2680 }
2681 }
2682
2683 effectChains = mEffectChains;
2684
2685 // find out which tracks need to be processed
2686 if (mActiveTracks.size() != 0) {
2687 sp<Track> t = mActiveTracks[0].promote();
2688 if (t == 0) continue;
2689
2690 Track* const track = t.get();
2691 audio_track_cblk_t* cblk = track->cblk();
2692
2693 // The first time a track is added we wait
2694 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002695 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002696 !track->isPaused() && !track->isTerminated())
2697 {
2698 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2699
2700 if (track->mFillingUpStatus == Track::FS_FILLED) {
2701 track->mFillingUpStatus = Track::FS_ACTIVE;
2702 mLeftVolFloat = mRightVolFloat = 0;
2703 mLeftVolShort = mRightVolShort = 0;
2704 if (track->mState == TrackBase::RESUMING) {
2705 track->mState = TrackBase::ACTIVE;
2706 rampVolume = true;
2707 }
2708 } else if (cblk->server != 0) {
2709 // If the track is stopped before the first frame was mixed,
2710 // do not apply ramp
2711 rampVolume = true;
2712 }
2713 // compute volume for this track
2714 float left, right;
2715 if (track->isMuted() || mMasterMute || track->isPausing() ||
2716 mStreamTypes[track->type()].mute) {
2717 left = right = 0;
2718 if (track->isPausing()) {
2719 track->setPaused();
2720 }
2721 } else {
2722 float typeVolume = mStreamTypes[track->type()].volume;
2723 float v = mMasterVolume * typeVolume;
2724 float v_clamped = v * cblk->volume[0];
2725 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2726 left = v_clamped/MAX_GAIN;
2727 v_clamped = v * cblk->volume[1];
2728 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2729 right = v_clamped/MAX_GAIN;
2730 }
2731
2732 if (left != mLeftVolFloat || right != mRightVolFloat) {
2733 mLeftVolFloat = left;
2734 mRightVolFloat = right;
2735
2736 // If audio HAL implements volume control,
2737 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002738 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 left = 1.0f;
2740 right = 1.0f;
2741 }
2742
2743 // Convert volumes from float to 8.24
2744 uint32_t vl = (uint32_t)(left * (1 << 24));
2745 uint32_t vr = (uint32_t)(right * (1 << 24));
2746
2747 // Delegate volume control to effect in track effect chain if needed
2748 // only one effect chain can be present on DirectOutputThread, so if
2749 // there is one, the track is connected to it
2750 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002751 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002752 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002753 rampVolume = false;
2754 }
2755 }
2756
2757 // Convert volumes from 8.24 to 4.12 format
2758 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2759 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2760 leftVol = (uint16_t)v_clamped;
2761 v_clamped = (vr + (1 << 11)) >> 12;
2762 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2763 rightVol = (uint16_t)v_clamped;
2764 } else {
2765 leftVol = mLeftVolShort;
2766 rightVol = mRightVolShort;
2767 rampVolume = false;
2768 }
2769
2770 // reset retry count
2771 track->mRetryCount = kMaxTrackRetriesDirect;
2772 activeTrack = t;
2773 mixerStatus = MIXER_TRACKS_READY;
2774 } else {
2775 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2776 if (track->isStopped()) {
2777 track->reset();
2778 }
2779 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2780 // We have consumed all the buffers of this track.
2781 // Remove it from the list of active tracks.
2782 trackToRemove = track;
2783 } else {
2784 // No buffers for this track. Give it a few chances to
2785 // fill a buffer, then remove it from active list.
2786 if (--(track->mRetryCount) <= 0) {
2787 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2788 trackToRemove = track;
2789 } else {
2790 mixerStatus = MIXER_TRACKS_ENABLED;
2791 }
2792 }
2793 }
2794 }
2795
2796 // remove all the tracks that need to be...
2797 if (UNLIKELY(trackToRemove != 0)) {
2798 mActiveTracks.remove(trackToRemove);
2799 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002800 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2801 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002802 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002803 }
2804 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002805 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002806 }
2807 }
2808
Eric Laurentde070132010-07-13 04:45:46 -07002809 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810 }
2811
2812 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2813 AudioBufferProvider::Buffer buffer;
2814 size_t frameCount = mFrameCount;
2815 curBuf = (int8_t *)mMixBuffer;
2816 // output audio to hardware
2817 while (frameCount) {
2818 buffer.frameCount = frameCount;
Mike J. Chen500e5102011-08-15 13:28:26 -07002819 activeTrack->getNextBuffer(&buffer,
2820 AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 if (UNLIKELY(buffer.raw == 0)) {
2822 memset(curBuf, 0, frameCount * mFrameSize);
2823 break;
2824 }
2825 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2826 frameCount -= buffer.frameCount;
2827 curBuf += buffer.frameCount * mFrameSize;
2828 activeTrack->releaseBuffer(&buffer);
2829 }
2830 sleepTime = 0;
2831 standbyTime = systemTime() + standbyDelay;
2832 } else {
2833 if (sleepTime == 0) {
2834 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2835 sleepTime = activeSleepTime;
2836 } else {
2837 sleepTime = idleSleepTime;
2838 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002839 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002840 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2841 sleepTime = 0;
2842 }
2843 }
2844
2845 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002846 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002847 }
2848 // sleepTime == 0 means we must write to audio hardware
2849 if (sleepTime == 0) {
2850 if (mixerStatus == MIXER_TRACKS_READY) {
2851 applyVolume(leftVol, rightVol, rampVolume);
2852 }
2853 for (size_t i = 0; i < effectChains.size(); i ++) {
2854 effectChains[i]->process_l();
2855 }
Eric Laurentde070132010-07-13 04:45:46 -07002856 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002857
2858 mLastWriteTime = systemTime();
2859 mInWrite = true;
2860 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002861 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002862 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2863 mNumWrites++;
2864 mInWrite = false;
2865 mStandby = false;
2866 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002867 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002868 usleep(sleepTime);
2869 }
2870
2871 // finally let go of removed track, without the lock held
2872 // since we can't guarantee the destructors won't acquire that
2873 // same lock.
2874 trackToRemove.clear();
2875 activeTrack.clear();
2876
2877 // Effect chains will be actually deleted here if they were removed from
2878 // mEffectChains list during mixing or effects processing
2879 effectChains.clear();
2880 }
2881
2882 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002883 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002884 }
2885
Eric Laurentfeb0db62011-07-22 09:04:31 -07002886 releaseWakeLock();
2887
Mathias Agopian65ab4712010-07-14 17:59:35 -07002888 LOGV("DirectOutputThread %p exiting", this);
2889 return false;
2890}
2891
2892// getTrackName_l() must be called with ThreadBase::mLock held
2893int AudioFlinger::DirectOutputThread::getTrackName_l()
2894{
2895 return 0;
2896}
2897
2898// deleteTrackName_l() must be called with ThreadBase::mLock held
2899void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2900{
2901}
2902
2903// checkForNewParameters_l() must be called with ThreadBase::mLock held
2904bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2905{
2906 bool reconfig = false;
2907
2908 while (!mNewParameters.isEmpty()) {
2909 status_t status = NO_ERROR;
2910 String8 keyValuePair = mNewParameters[0];
2911 AudioParameter param = AudioParameter(keyValuePair);
2912 int value;
2913
2914 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2915 // do not accept frame count changes if tracks are open as the track buffer
2916 // size depends on frame count and correct behavior would not be garantied
2917 // if frame count is changed after track creation
2918 if (!mTracks.isEmpty()) {
2919 status = INVALID_OPERATION;
2920 } else {
2921 reconfig = true;
2922 }
2923 }
2924 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002925 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002926 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002927 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002928 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929 mStandby = true;
2930 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002931 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002932 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933 }
2934 if (status == NO_ERROR && reconfig) {
2935 readOutputParameters();
2936 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2937 }
2938 }
2939
2940 mNewParameters.removeAt(0);
2941
2942 mParamStatus = status;
2943 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002944 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2945 // already timed out waiting for the status and will never signal the condition.
2946 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 }
2948 return reconfig;
2949}
2950
2951uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2952{
2953 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002954 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002955 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002956 } else {
2957 time = 10000;
2958 }
2959 return time;
2960}
2961
2962uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2963{
2964 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002965 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002966 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002967 } else {
2968 time = 10000;
2969 }
2970 return time;
2971}
2972
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002973uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2974{
2975 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002976 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002977 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2978 } else {
2979 time = 10000;
2980 }
2981 return time;
2982}
2983
2984
Mathias Agopian65ab4712010-07-14 17:59:35 -07002985// ----------------------------------------------------------------------------
2986
2987AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2988 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2989{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002990 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991 addOutputTrack(mainThread);
2992}
2993
2994AudioFlinger::DuplicatingThread::~DuplicatingThread()
2995{
2996 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2997 mOutputTracks[i]->destroy();
2998 }
2999 mOutputTracks.clear();
3000}
3001
3002bool AudioFlinger::DuplicatingThread::threadLoop()
3003{
3004 Vector< sp<Track> > tracksToRemove;
3005 uint32_t mixerStatus = MIXER_IDLE;
3006 nsecs_t standbyTime = systemTime();
3007 size_t mixBufferSize = mFrameCount*mFrameSize;
3008 SortedVector< sp<OutputTrack> > outputTracks;
3009 uint32_t writeFrames = 0;
3010 uint32_t activeSleepTime = activeSleepTimeUs();
3011 uint32_t idleSleepTime = idleSleepTimeUs();
3012 uint32_t sleepTime = idleSleepTime;
3013 Vector< sp<EffectChain> > effectChains;
3014
Eric Laurentfeb0db62011-07-22 09:04:31 -07003015 acquireWakeLock();
3016
Mathias Agopian65ab4712010-07-14 17:59:35 -07003017 while (!exitPending())
3018 {
3019 processConfigEvents();
3020
3021 mixerStatus = MIXER_IDLE;
3022 { // scope for the mLock
3023
3024 Mutex::Autolock _l(mLock);
3025
3026 if (checkForNewParameters_l()) {
3027 mixBufferSize = mFrameCount*mFrameSize;
3028 updateWaitTime();
3029 activeSleepTime = activeSleepTimeUs();
3030 idleSleepTime = idleSleepTimeUs();
3031 }
3032
3033 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3034
3035 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3036 outputTracks.add(mOutputTracks[i]);
3037 }
3038
3039 // put audio hardware into standby after short delay
3040 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3041 mSuspended) {
3042 if (!mStandby) {
3043 for (size_t i = 0; i < outputTracks.size(); i++) {
3044 outputTracks[i]->stop();
3045 }
3046 mStandby = true;
3047 mBytesWritten = 0;
3048 }
3049
3050 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3051 // we're about to wait, flush the binder command buffer
3052 IPCThreadState::self()->flushCommands();
3053 outputTracks.clear();
3054
3055 if (exitPending()) break;
3056
Eric Laurentfeb0db62011-07-22 09:04:31 -07003057 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003058 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
3059 mWaitWorkCV.wait(mLock);
3060 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003061 acquireWakeLock_l();
3062
Mathias Agopian65ab4712010-07-14 17:59:35 -07003063 if (mMasterMute == false) {
3064 char value[PROPERTY_VALUE_MAX];
3065 property_get("ro.audio.silent", value, "0");
3066 if (atoi(value)) {
3067 LOGD("Silence is golden");
3068 setMasterMute(true);
3069 }
3070 }
3071
3072 standbyTime = systemTime() + kStandbyTimeInNsecs;
3073 sleepTime = idleSleepTime;
3074 continue;
3075 }
3076 }
3077
3078 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3079
3080 // prevent any changes in effect chain list and in each effect chain
3081 // during mixing and effect process as the audio buffers could be deleted
3082 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003083 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003084 }
3085
3086 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3087 // mix buffers...
3088 if (outputsReady(outputTracks)) {
Mike J. Chen500e5102011-08-15 13:28:26 -07003089 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003090 } else {
3091 memset(mMixBuffer, 0, mixBufferSize);
3092 }
3093 sleepTime = 0;
3094 writeFrames = mFrameCount;
3095 } else {
3096 if (sleepTime == 0) {
3097 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3098 sleepTime = activeSleepTime;
3099 } else {
3100 sleepTime = idleSleepTime;
3101 }
3102 } else if (mBytesWritten != 0) {
3103 // flush remaining overflow buffers in output tracks
3104 for (size_t i = 0; i < outputTracks.size(); i++) {
3105 if (outputTracks[i]->isActive()) {
3106 sleepTime = 0;
3107 writeFrames = 0;
3108 memset(mMixBuffer, 0, mixBufferSize);
3109 break;
3110 }
3111 }
3112 }
3113 }
3114
3115 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003116 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003117 }
3118 // sleepTime == 0 means we must write to audio hardware
3119 if (sleepTime == 0) {
3120 for (size_t i = 0; i < effectChains.size(); i ++) {
3121 effectChains[i]->process_l();
3122 }
3123 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003124 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125
3126 standbyTime = systemTime() + kStandbyTimeInNsecs;
3127 for (size_t i = 0; i < outputTracks.size(); i++) {
3128 outputTracks[i]->write(mMixBuffer, writeFrames);
3129 }
3130 mStandby = false;
3131 mBytesWritten += mixBufferSize;
3132 } else {
3133 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003134 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 usleep(sleepTime);
3136 }
3137
3138 // finally let go of all our tracks, without the lock held
3139 // since we can't guarantee the destructors won't acquire that
3140 // same lock.
3141 tracksToRemove.clear();
3142 outputTracks.clear();
3143
3144 // Effect chains will be actually deleted here if they were removed from
3145 // mEffectChains list during mixing or effects processing
3146 effectChains.clear();
3147 }
3148
Eric Laurentfeb0db62011-07-22 09:04:31 -07003149 releaseWakeLock();
3150
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 return false;
3152}
3153
3154void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3155{
3156 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3157 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3158 this,
3159 mSampleRate,
3160 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003161 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003162 frameCount);
3163 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003164 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003165 mOutputTracks.add(outputTrack);
3166 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3167 updateWaitTime();
3168 }
3169}
3170
3171void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3172{
3173 Mutex::Autolock _l(mLock);
3174 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3175 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3176 mOutputTracks[i]->destroy();
3177 mOutputTracks.removeAt(i);
3178 updateWaitTime();
3179 return;
3180 }
3181 }
3182 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3183}
3184
3185void AudioFlinger::DuplicatingThread::updateWaitTime()
3186{
3187 mWaitTimeMs = UINT_MAX;
3188 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3189 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3190 if (strong != NULL) {
3191 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3192 if (waitTimeMs < mWaitTimeMs) {
3193 mWaitTimeMs = waitTimeMs;
3194 }
3195 }
3196 }
3197}
3198
3199
3200bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3201{
3202 for (size_t i = 0; i < outputTracks.size(); i++) {
3203 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3204 if (thread == 0) {
3205 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3206 return false;
3207 }
3208 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3209 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3210 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3211 return false;
3212 }
3213 }
3214 return true;
3215}
3216
3217uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3218{
3219 return (mWaitTimeMs * 1000) / 2;
3220}
3221
3222// ----------------------------------------------------------------------------
3223
3224// TrackBase constructor must be called with AudioFlinger::mLock held
3225AudioFlinger::ThreadBase::TrackBase::TrackBase(
3226 const wp<ThreadBase>& thread,
3227 const sp<Client>& client,
3228 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003229 uint32_t format,
3230 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003231 int frameCount,
3232 uint32_t flags,
3233 const sp<IMemory>& sharedBuffer,
3234 int sessionId)
3235 : RefBase(),
3236 mThread(thread),
3237 mClient(client),
3238 mCblk(0),
3239 mFrameCount(0),
3240 mState(IDLE),
3241 mClientTid(-1),
3242 mFormat(format),
3243 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3244 mSessionId(sessionId)
3245{
3246 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3247
3248 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3249 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003250 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003251 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3252 if (sharedBuffer == 0) {
3253 size += bufferSize;
3254 }
3255
3256 if (client != NULL) {
3257 mCblkMemory = client->heap()->allocate(size);
3258 if (mCblkMemory != 0) {
3259 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3260 if (mCblk) { // construct the shared structure in-place.
3261 new(mCblk) audio_track_cblk_t();
3262 // clear all buffers
3263 mCblk->frameCount = frameCount;
3264 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003265 mChannelCount = channelCount;
3266 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003267 if (sharedBuffer == 0) {
3268 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3269 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3270 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003271 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003272 mCblk->flags = CBLK_UNDERRUN_ON;
3273 } else {
3274 mBuffer = sharedBuffer->pointer();
3275 }
3276 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3277 }
3278 } else {
3279 LOGE("not enough memory for AudioTrack size=%u", size);
3280 client->heap()->dump("AudioTrack");
3281 return;
3282 }
3283 } else {
3284 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3285 if (mCblk) { // construct the shared structure in-place.
3286 new(mCblk) audio_track_cblk_t();
3287 // clear all buffers
3288 mCblk->frameCount = frameCount;
3289 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003290 mChannelCount = channelCount;
3291 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3293 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3294 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003295 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003296 mCblk->flags = CBLK_UNDERRUN_ON;
3297 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3298 }
3299 }
3300}
3301
3302AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3303{
3304 if (mCblk) {
3305 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3306 if (mClient == NULL) {
3307 delete mCblk;
3308 }
3309 }
3310 mCblkMemory.clear(); // and free the shared memory
3311 if (mClient != NULL) {
3312 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3313 mClient.clear();
3314 }
3315}
3316
3317void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3318{
3319 buffer->raw = 0;
3320 mFrameCount = buffer->frameCount;
3321 step();
3322 buffer->frameCount = 0;
3323}
3324
3325bool AudioFlinger::ThreadBase::TrackBase::step() {
3326 bool result;
3327 audio_track_cblk_t* cblk = this->cblk();
3328
3329 result = cblk->stepServer(mFrameCount);
3330 if (!result) {
3331 LOGV("stepServer failed acquiring cblk mutex");
3332 mFlags |= STEPSERVER_FAILED;
3333 }
3334 return result;
3335}
3336
3337void AudioFlinger::ThreadBase::TrackBase::reset() {
3338 audio_track_cblk_t* cblk = this->cblk();
3339
3340 cblk->user = 0;
3341 cblk->server = 0;
3342 cblk->userBase = 0;
3343 cblk->serverBase = 0;
3344 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3345 LOGV("TrackBase::reset");
3346}
3347
3348sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3349{
3350 return mCblkMemory;
3351}
3352
3353int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3354 return (int)mCblk->sampleRate;
3355}
3356
3357int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003358 return (const int)mChannelCount;
3359}
3360
3361uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3362 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363}
3364
3365void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3366 audio_track_cblk_t* cblk = this->cblk();
3367 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3368 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3369
3370 // Check validity of returned pointer in case the track control block would have been corrupted.
3371 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3372 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3373 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 -07003374 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003375 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003376 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003377 return 0;
3378 }
3379
3380 return bufferStart;
3381}
3382
3383// ----------------------------------------------------------------------------
3384
3385// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3386AudioFlinger::PlaybackThread::Track::Track(
3387 const wp<ThreadBase>& thread,
3388 const sp<Client>& client,
3389 int streamType,
3390 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003391 uint32_t format,
3392 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003393 int frameCount,
3394 const sp<IMemory>& sharedBuffer,
3395 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003396 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003397 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3398 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003399{
3400 if (mCblk != NULL) {
3401 sp<ThreadBase> baseThread = thread.promote();
3402 if (baseThread != 0) {
3403 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3404 mName = playbackThread->getTrackName_l();
3405 mMainBuffer = playbackThread->mixBuffer();
3406 }
3407 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3408 if (mName < 0) {
3409 LOGE("no more track names available");
3410 }
3411 mVolume[0] = 1.0f;
3412 mVolume[1] = 1.0f;
3413 mStreamType = streamType;
3414 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3415 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003416 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003417 }
3418}
3419
3420AudioFlinger::PlaybackThread::Track::~Track()
3421{
3422 LOGV("PlaybackThread::Track destructor");
3423 sp<ThreadBase> thread = mThread.promote();
3424 if (thread != 0) {
3425 Mutex::Autolock _l(thread->mLock);
3426 mState = TERMINATED;
3427 }
3428}
3429
3430void AudioFlinger::PlaybackThread::Track::destroy()
3431{
3432 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3433 // by removing it from mTracks vector, so there is a risk that this Tracks's
3434 // desctructor is called. As the destructor needs to lock mLock,
3435 // we must acquire a strong reference on this Track before locking mLock
3436 // here so that the destructor is called only when exiting this function.
3437 // On the other hand, as long as Track::destroy() is only called by
3438 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3439 // this Track with its member mTrack.
3440 sp<Track> keep(this);
3441 { // scope for mLock
3442 sp<ThreadBase> thread = mThread.promote();
3443 if (thread != 0) {
3444 if (!isOutputTrack()) {
3445 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003446 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003447 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003448 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003449
3450 // to track the speaker usage
3451 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003452 }
3453 AudioSystem::releaseOutput(thread->id());
3454 }
3455 Mutex::Autolock _l(thread->mLock);
3456 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3457 playbackThread->destroyTrack_l(this);
3458 }
3459 }
3460}
3461
3462void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3463{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003464 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 -07003465 mName - AudioMixer::TRACK0,
3466 (mClient == NULL) ? getpid() : mClient->pid(),
3467 mStreamType,
3468 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003469 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003470 mSessionId,
3471 mFrameCount,
3472 mState,
3473 mMute,
3474 mFillingUpStatus,
3475 mCblk->sampleRate,
3476 mCblk->volume[0],
3477 mCblk->volume[1],
3478 mCblk->server,
3479 mCblk->user,
3480 (int)mMainBuffer,
3481 (int)mAuxBuffer);
3482}
3483
Mike J. Chen500e5102011-08-15 13:28:26 -07003484status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3485 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003486{
3487 audio_track_cblk_t* cblk = this->cblk();
3488 uint32_t framesReady;
3489 uint32_t framesReq = buffer->frameCount;
3490
3491 // Check if last stepServer failed, try to step now
3492 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3493 if (!step()) goto getNextBuffer_exit;
3494 LOGV("stepServer recovered");
3495 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3496 }
3497
3498 framesReady = cblk->framesReady();
3499
3500 if (LIKELY(framesReady)) {
3501 uint32_t s = cblk->server;
3502 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3503
3504 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3505 if (framesReq > framesReady) {
3506 framesReq = framesReady;
3507 }
3508 if (s + framesReq > bufferEnd) {
3509 framesReq = bufferEnd - s;
3510 }
3511
3512 buffer->raw = getBuffer(s, framesReq);
3513 if (buffer->raw == 0) goto getNextBuffer_exit;
3514
3515 buffer->frameCount = framesReq;
3516 return NO_ERROR;
3517 }
3518
3519getNextBuffer_exit:
3520 buffer->raw = 0;
3521 buffer->frameCount = 0;
3522 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3523 return NOT_ENOUGH_DATA;
3524}
3525
Mike J. Chen500e5102011-08-15 13:28:26 -07003526uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3527 return mCblk->framesReady();
3528}
3529
Mathias Agopian65ab4712010-07-14 17:59:35 -07003530bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003531 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003532
Mike J. Chen500e5102011-08-15 13:28:26 -07003533 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003534 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3535 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003536 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003537 return true;
3538 }
3539 return false;
3540}
3541
3542status_t AudioFlinger::PlaybackThread::Track::start()
3543{
3544 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003545 LOGV("start(%d), calling thread %d session %d",
3546 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003547 sp<ThreadBase> thread = mThread.promote();
3548 if (thread != 0) {
3549 Mutex::Autolock _l(thread->mLock);
3550 int state = mState;
3551 // here the track could be either new, or restarted
3552 // in both cases "unstop" the track
3553 if (mState == PAUSED) {
3554 mState = TrackBase::RESUMING;
3555 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3556 } else {
3557 mState = TrackBase::ACTIVE;
3558 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3559 }
3560
3561 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3562 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003563 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003564 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003565 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003566 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003567
3568 // to track the speaker usage
3569 if (status == NO_ERROR) {
3570 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003572 }
3573 if (status == NO_ERROR) {
3574 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3575 playbackThread->addTrack_l(this);
3576 } else {
3577 mState = state;
3578 }
3579 } else {
3580 status = BAD_VALUE;
3581 }
3582 return status;
3583}
3584
3585void AudioFlinger::PlaybackThread::Track::stop()
3586{
3587 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3588 sp<ThreadBase> thread = mThread.promote();
3589 if (thread != 0) {
3590 Mutex::Autolock _l(thread->mLock);
3591 int state = mState;
3592 if (mState > STOPPED) {
3593 mState = STOPPED;
3594 // If the track is not active (PAUSED and buffers full), flush buffers
3595 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3596 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3597 reset();
3598 }
3599 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3600 }
3601 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3602 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003603 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003604 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003605 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003606 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003607
3608 // to track the speaker usage
3609 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610 }
3611 }
3612}
3613
3614void AudioFlinger::PlaybackThread::Track::pause()
3615{
3616 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3617 sp<ThreadBase> thread = mThread.promote();
3618 if (thread != 0) {
3619 Mutex::Autolock _l(thread->mLock);
3620 if (mState == ACTIVE || mState == RESUMING) {
3621 mState = PAUSING;
3622 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3623 if (!isOutputTrack()) {
3624 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003625 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003626 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003627 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003628 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003629
3630 // to track the speaker usage
3631 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 }
3633 }
3634 }
3635}
3636
3637void AudioFlinger::PlaybackThread::Track::flush()
3638{
3639 LOGV("flush(%d)", mName);
3640 sp<ThreadBase> thread = mThread.promote();
3641 if (thread != 0) {
3642 Mutex::Autolock _l(thread->mLock);
3643 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3644 return;
3645 }
3646 // No point remaining in PAUSED state after a flush => go to
3647 // STOPPED state
3648 mState = STOPPED;
3649
Eric Laurent38ccae22011-03-28 18:37:07 -07003650 // do not reset the track if it is still in the process of being stopped or paused.
3651 // this will be done by prepareTracks_l() when the track is stopped.
3652 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3653 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3654 reset();
3655 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656 }
3657}
3658
3659void AudioFlinger::PlaybackThread::Track::reset()
3660{
3661 // Do not reset twice to avoid discarding data written just after a flush and before
3662 // the audioflinger thread detects the track is stopped.
3663 if (!mResetDone) {
3664 TrackBase::reset();
3665 // Force underrun condition to avoid false underrun callback until first data is
3666 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003667 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3668 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003669 mFillingUpStatus = FS_FILLING;
3670 mResetDone = true;
3671 }
3672}
3673
3674void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3675{
3676 mMute = muted;
3677}
3678
3679void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3680{
3681 mVolume[0] = left;
3682 mVolume[1] = right;
3683}
3684
3685status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3686{
3687 status_t status = DEAD_OBJECT;
3688 sp<ThreadBase> thread = mThread.promote();
3689 if (thread != 0) {
3690 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3691 status = playbackThread->attachAuxEffect(this, EffectId);
3692 }
3693 return status;
3694}
3695
3696void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3697{
3698 mAuxEffectId = EffectId;
3699 mAuxBuffer = buffer;
3700}
3701
Mike J. Chen500e5102011-08-15 13:28:26 -07003702// timed audio tracks
3703
3704sp<AudioFlinger::PlaybackThread::TimedTrack>
3705AudioFlinger::PlaybackThread::TimedTrack::create(
3706 const wp<ThreadBase>& thread,
3707 const sp<Client>& client,
3708 int streamType,
3709 uint32_t sampleRate,
3710 uint32_t format,
3711 uint32_t channelMask,
3712 int frameCount,
3713 const sp<IMemory>& sharedBuffer,
3714 int sessionId) {
3715 if (!client->reserveTimedTrack())
3716 return NULL;
3717
3718 sp<TimedTrack> track = new TimedTrack(
3719 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3720 sharedBuffer, sessionId);
3721
3722 if (track == NULL) {
3723 client->releaseTimedTrack();
3724 return NULL;
3725 }
3726
3727 return track;
3728}
3729
3730AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
3731 const wp<ThreadBase>& thread,
3732 const sp<Client>& client,
3733 int streamType,
3734 uint32_t sampleRate,
3735 uint32_t format,
3736 uint32_t channelMask,
3737 int frameCount,
3738 const sp<IMemory>& sharedBuffer,
3739 int sessionId)
3740 : Track(thread, client, streamType, sampleRate, format, channelMask,
3741 frameCount, sharedBuffer, sessionId),
3742 mTimedSilenceBuffer(NULL),
3743 mTimedSilenceBufferSize(0),
3744 mTimedAudioOutputOnTime(false),
3745 mMediaTimeTransformValid(false)
3746{
3747 LocalClock lc;
3748 mLocalTimeFreq = lc.getLocalFreq();
3749
3750 mLocalTimeToSampleTransform.a_zero = 0;
3751 mLocalTimeToSampleTransform.b_zero = 0;
3752 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3753 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3754 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3755 &mLocalTimeToSampleTransform.a_to_b_denom);
3756}
3757
3758AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3759 mClient->releaseTimedTrack();
3760 delete [] mTimedSilenceBuffer;
3761}
3762
3763status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3764 size_t size, sp<IMemory>* buffer) {
3765
3766 Mutex::Autolock _l(mTimedBufferQueueLock);
3767
3768 trimTimedBufferQueue_l();
3769
3770 // lazily initialize the shared memory heap for timed buffers
3771 if (mTimedMemoryDealer == NULL) {
3772 const int kTimedBufferHeapSize = 512 << 10;
3773
3774 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3775 "AudioFlingerTimed");
3776 if (mTimedMemoryDealer == NULL)
3777 return NO_MEMORY;
3778 }
3779
3780 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3781 if (newBuffer == NULL) {
3782 newBuffer = mTimedMemoryDealer->allocate(size);
3783 if (newBuffer == NULL)
3784 return NO_MEMORY;
3785 }
3786
3787 *buffer = newBuffer;
3788 return NO_ERROR;
3789}
3790
3791// caller must hold mTimedBufferQueueLock
3792void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3793 int64_t mediaTimeNow;
3794 {
3795 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3796 if (!mMediaTimeTransformValid)
3797 return;
3798
3799 int64_t targetTimeNow;
3800 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3801 ? CCHelper::getCommonTime(&targetTimeNow)
3802 : CCHelper::getLocalTime(&targetTimeNow);
3803
3804 if (OK != res)
3805 return;
3806
3807 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3808 &mediaTimeNow)) {
3809 return;
3810 }
3811 }
3812
3813 size_t trimIndex;
3814 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3815 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3816 break;
3817 }
3818
3819 if (trimIndex) {
3820 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3821 }
3822}
3823
3824status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3825 const sp<IMemory>& buffer, int64_t pts) {
3826
3827 {
3828 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3829 if (!mMediaTimeTransformValid)
3830 return INVALID_OPERATION;
3831 }
3832
3833 Mutex::Autolock _l(mTimedBufferQueueLock);
3834
3835 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3836
3837 return NO_ERROR;
3838}
3839
3840status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3841 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3842
3843 LOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3844 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3845 target);
3846
3847 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3848 target == TimedAudioTrack::COMMON_TIME)) {
3849 return BAD_VALUE;
3850 }
3851
3852 Mutex::Autolock lock(mMediaTimeTransformLock);
3853 mMediaTimeTransform = xform;
3854 mMediaTimeTransformTarget = target;
3855 mMediaTimeTransformValid = true;
3856
3857 return NO_ERROR;
3858}
3859
3860#define min(a, b) ((a) < (b) ? (a) : (b))
3861
3862// implementation of getNextBuffer for tracks whose buffers have timestamps
3863status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3864 AudioBufferProvider::Buffer* buffer, int64_t pts)
3865{
3866 if (pts == AudioBufferProvider::kInvalidPTS) {
3867 buffer->raw = 0;
3868 buffer->frameCount = 0;
3869 return INVALID_OPERATION;
3870 }
3871
3872 // get ahold of the output stream that these samples will be written to
3873 sp<ThreadBase> thread = mThread.promote();
3874 if (thread == NULL) {
3875 buffer->raw = 0;
3876 buffer->frameCount = 0;
3877 return INVALID_OPERATION;
3878 }
3879 PlaybackThread* playbackThread = static_cast<PlaybackThread*>(thread.get());
3880
3881 Mutex::Autolock _l(mTimedBufferQueueLock);
3882
3883 while (true) {
3884
3885 // if we have no timed buffers, then fail
3886 if (mTimedBufferQueue.isEmpty()) {
3887 buffer->raw = 0;
3888 buffer->frameCount = 0;
3889 return NOT_ENOUGH_DATA;
3890 }
3891
3892 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3893
3894 // calculate the PTS of the head of the timed buffer queue expressed in
3895 // local time
3896 int64_t headLocalPTS;
3897 {
3898 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3899
3900 assert(mMediaTimeTransformValid);
3901
3902 if (mMediaTimeTransform.a_to_b_denom == 0) {
3903 // the transform represents a pause, so yield silence
3904 timedYieldSilence(buffer->frameCount, buffer);
3905 return NO_ERROR;
3906 }
3907
3908 int64_t transformedPTS;
3909 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3910 &transformedPTS)) {
3911 // the transform failed. this shouldn't happen, but if it does
3912 // then just drop this buffer
3913 LOGW("timedGetNextBuffer transform failed");
3914 buffer->raw = 0;
3915 buffer->frameCount = 0;
3916 mTimedBufferQueue.removeAt(0);
3917 return NO_ERROR;
3918 }
3919
3920 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3921 if (OK != CCHelper::commonTimeToLocalTime(transformedPTS,
3922 &headLocalPTS)) {
3923 buffer->raw = 0;
3924 buffer->frameCount = 0;
3925 return INVALID_OPERATION;
3926 }
3927 } else {
3928 headLocalPTS = transformedPTS;
3929 }
3930 }
3931
3932 // adjust the head buffer's PTS to reflect the portion of the head buffer
3933 // that has already been consumed
3934 int64_t effectivePTS = headLocalPTS +
3935 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3936
3937 // Calculate the delta in samples between the head of the input buffer
3938 // queue and the start of the next output buffer that will be written.
3939 // If the transformation fails because of over or underflow, it means
3940 // that the sample's position in the output stream is so far out of
3941 // whack that it should just be dropped.
3942 int64_t sampleDelta;
3943 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3944 LOGV("*** head buffer is too far from PTS: dropped buffer");
3945 mTimedBufferQueue.removeAt(0);
3946 continue;
3947 }
3948 if (!mLocalTimeToSampleTransform.doForwardTransform(
3949 (effectivePTS - pts) << 32, &sampleDelta)) {
3950 LOGV("*** too late during sample rate transform: dropped buffer");
3951 mTimedBufferQueue.removeAt(0);
3952 continue;
3953 }
3954
3955 LOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3956 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3957 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3958 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3959
3960 // if the delta between the ideal placement for the next input sample and
3961 // the current output position is within this threshold, then we will
3962 // concatenate the next input samples to the previous output
3963 const int64_t kSampleContinuityThreshold =
3964 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3965
3966 // if this is the first buffer of audio that we're emitting from this track
3967 // then it should be almost exactly on time.
3968 const int64_t kSampleStartupThreshold = 1LL << 32;
3969
3970 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3971 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3972 // the next input is close enough to being on time, so concatenate it
3973 // with the last output
3974 timedYieldSamples(buffer);
3975
3976 LOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3977 return NO_ERROR;
3978 } else if (sampleDelta > 0) {
3979 // the gap between the current output position and the proper start of
3980 // the next input sample is too big, so fill it with silence
3981 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3982
3983 timedYieldSilence(framesUntilNextInput, buffer);
3984 LOGV("*** silence: frameCount=%u", buffer->frameCount);
3985 return NO_ERROR;
3986 } else {
3987 // the next input sample is late
3988 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3989 size_t onTimeSamplePosition =
3990 head.position() + lateFrames * mCblk->frameSize;
3991
3992 if (onTimeSamplePosition > head.buffer()->size()) {
3993 // all the remaining samples in the head are too late, so
3994 // drop it and move on
3995 LOGV("*** too late: dropped buffer");
3996 mTimedBufferQueue.removeAt(0);
3997 continue;
3998 } else {
3999 // skip over the late samples
4000 head.setPosition(onTimeSamplePosition);
4001
4002 // yield the available samples
4003 timedYieldSamples(buffer);
4004
4005 LOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
4006 return NO_ERROR;
4007 }
4008 }
4009 }
4010}
4011
4012// Yield samples from the timed buffer queue head up to the given output
4013// buffer's capacity.
4014//
4015// Caller must hold mTimedBufferQueueLock
4016void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4017 AudioBufferProvider::Buffer* buffer) {
4018
4019 const TimedBuffer& head = mTimedBufferQueue[0];
4020
4021 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4022 head.position());
4023
4024 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4025 mCblk->frameSize);
4026 size_t framesRequested = buffer->frameCount;
4027 buffer->frameCount = min(framesLeftInHead, framesRequested);
4028
4029 mTimedAudioOutputOnTime = true;
4030}
4031
4032// Yield samples of silence up to the given output buffer's capacity
4033//
4034// Caller must hold mTimedBufferQueueLock
4035void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4036 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4037
4038 // lazily allocate a buffer filled with silence
4039 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4040 delete [] mTimedSilenceBuffer;
4041 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4042 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4043 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4044 }
4045
4046 buffer->raw = mTimedSilenceBuffer;
4047 size_t framesRequested = buffer->frameCount;
4048 buffer->frameCount = min(numFrames, framesRequested);
4049
4050 mTimedAudioOutputOnTime = false;
4051}
4052
4053void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4054 AudioBufferProvider::Buffer* buffer) {
4055
4056 Mutex::Autolock _l(mTimedBufferQueueLock);
4057
4058 if (buffer->raw != mTimedSilenceBuffer) {
4059 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4060 head.setPosition(head.position() + buffer->frameCount * mCblk->frameSize);
4061 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4062 mTimedBufferQueue.removeAt(0);
4063 }
4064 }
4065
4066 buffer->raw = 0;
4067 buffer->frameCount = 0;
4068}
4069
4070uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4071 Mutex::Autolock _l(mTimedBufferQueueLock);
4072
4073 uint32_t frames = 0;
4074 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4075 const TimedBuffer& tb = mTimedBufferQueue[i];
4076 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4077 }
4078
4079 return frames;
4080}
4081
4082AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4083 : mPTS(0), mPosition(0) {}
4084
4085AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4086 const sp<IMemory>& buffer, int64_t pts)
4087 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4088
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089// ----------------------------------------------------------------------------
4090
4091// RecordTrack constructor must be called with AudioFlinger::mLock held
4092AudioFlinger::RecordThread::RecordTrack::RecordTrack(
4093 const wp<ThreadBase>& thread,
4094 const sp<Client>& client,
4095 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004096 uint32_t format,
4097 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 int frameCount,
4099 uint32_t flags,
4100 int sessionId)
4101 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004102 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004103 mOverflow(false)
4104{
4105 if (mCblk != NULL) {
4106 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004107 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004108 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004109 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004110 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004111 } else {
4112 mCblk->frameSize = sizeof(int8_t);
4113 }
4114 }
4115}
4116
4117AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4118{
4119 sp<ThreadBase> thread = mThread.promote();
4120 if (thread != 0) {
4121 AudioSystem::releaseInput(thread->id());
4122 }
4123}
4124
Mike J. Chen500e5102011-08-15 13:28:26 -07004125status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004126{
4127 audio_track_cblk_t* cblk = this->cblk();
4128 uint32_t framesAvail;
4129 uint32_t framesReq = buffer->frameCount;
4130
4131 // Check if last stepServer failed, try to step now
4132 if (mFlags & TrackBase::STEPSERVER_FAILED) {
4133 if (!step()) goto getNextBuffer_exit;
4134 LOGV("stepServer recovered");
4135 mFlags &= ~TrackBase::STEPSERVER_FAILED;
4136 }
4137
4138 framesAvail = cblk->framesAvailable_l();
4139
4140 if (LIKELY(framesAvail)) {
4141 uint32_t s = cblk->server;
4142 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4143
4144 if (framesReq > framesAvail) {
4145 framesReq = framesAvail;
4146 }
4147 if (s + framesReq > bufferEnd) {
4148 framesReq = bufferEnd - s;
4149 }
4150
4151 buffer->raw = getBuffer(s, framesReq);
4152 if (buffer->raw == 0) goto getNextBuffer_exit;
4153
4154 buffer->frameCount = framesReq;
4155 return NO_ERROR;
4156 }
4157
4158getNextBuffer_exit:
4159 buffer->raw = 0;
4160 buffer->frameCount = 0;
4161 return NOT_ENOUGH_DATA;
4162}
4163
4164status_t AudioFlinger::RecordThread::RecordTrack::start()
4165{
4166 sp<ThreadBase> thread = mThread.promote();
4167 if (thread != 0) {
4168 RecordThread *recordThread = (RecordThread *)thread.get();
4169 return recordThread->start(this);
4170 } else {
4171 return BAD_VALUE;
4172 }
4173}
4174
4175void AudioFlinger::RecordThread::RecordTrack::stop()
4176{
4177 sp<ThreadBase> thread = mThread.promote();
4178 if (thread != 0) {
4179 RecordThread *recordThread = (RecordThread *)thread.get();
4180 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004181 TrackBase::reset();
4182 // Force overerrun condition to avoid false overrun callback until first data is
4183 // read from buffer
4184 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004185 }
4186}
4187
4188void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4189{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004190 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191 (mClient == NULL) ? getpid() : mClient->pid(),
4192 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004193 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004194 mSessionId,
4195 mFrameCount,
4196 mState,
4197 mCblk->sampleRate,
4198 mCblk->server,
4199 mCblk->user);
4200}
4201
4202
4203// ----------------------------------------------------------------------------
4204
4205AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
4206 const wp<ThreadBase>& thread,
4207 DuplicatingThread *sourceThread,
4208 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004209 uint32_t format,
4210 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004211 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004212 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 mActive(false), mSourceThread(sourceThread)
4214{
4215
4216 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
4217 if (mCblk != NULL) {
4218 mCblk->flags |= CBLK_DIRECTION_OUT;
4219 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
4220 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
4221 mOutBuffer.frameCount = 0;
4222 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004223 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
4224 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4225 mCblk, mBuffer, mCblk->buffers,
4226 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227 } else {
4228 LOGW("Error creating output track on thread %p", playbackThread);
4229 }
4230}
4231
4232AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4233{
4234 clearBufferQueue();
4235}
4236
4237status_t AudioFlinger::PlaybackThread::OutputTrack::start()
4238{
4239 status_t status = Track::start();
4240 if (status != NO_ERROR) {
4241 return status;
4242 }
4243
4244 mActive = true;
4245 mRetryCount = 127;
4246 return status;
4247}
4248
4249void AudioFlinger::PlaybackThread::OutputTrack::stop()
4250{
4251 Track::stop();
4252 clearBufferQueue();
4253 mOutBuffer.frameCount = 0;
4254 mActive = false;
4255}
4256
4257bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4258{
4259 Buffer *pInBuffer;
4260 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004261 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004262 bool outputBufferFull = false;
4263 inBuffer.frameCount = frames;
4264 inBuffer.i16 = data;
4265
4266 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4267
4268 if (!mActive && frames != 0) {
4269 start();
4270 sp<ThreadBase> thread = mThread.promote();
4271 if (thread != 0) {
4272 MixerThread *mixerThread = (MixerThread *)thread.get();
4273 if (mCblk->frameCount > frames){
4274 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4275 uint32_t startFrames = (mCblk->frameCount - frames);
4276 pInBuffer = new Buffer;
4277 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4278 pInBuffer->frameCount = startFrames;
4279 pInBuffer->i16 = pInBuffer->mBuffer;
4280 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4281 mBufferQueue.add(pInBuffer);
4282 } else {
4283 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
4284 }
4285 }
4286 }
4287 }
4288
4289 while (waitTimeLeftMs) {
4290 // First write pending buffers, then new data
4291 if (mBufferQueue.size()) {
4292 pInBuffer = mBufferQueue.itemAt(0);
4293 } else {
4294 pInBuffer = &inBuffer;
4295 }
4296
4297 if (pInBuffer->frameCount == 0) {
4298 break;
4299 }
4300
4301 if (mOutBuffer.frameCount == 0) {
4302 mOutBuffer.frameCount = pInBuffer->frameCount;
4303 nsecs_t startTime = systemTime();
4304 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
4305 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
4306 outputBufferFull = true;
4307 break;
4308 }
4309 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4310 if (waitTimeLeftMs >= waitTimeMs) {
4311 waitTimeLeftMs -= waitTimeMs;
4312 } else {
4313 waitTimeLeftMs = 0;
4314 }
4315 }
4316
4317 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4318 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4319 mCblk->stepUser(outFrames);
4320 pInBuffer->frameCount -= outFrames;
4321 pInBuffer->i16 += outFrames * channelCount;
4322 mOutBuffer.frameCount -= outFrames;
4323 mOutBuffer.i16 += outFrames * channelCount;
4324
4325 if (pInBuffer->frameCount == 0) {
4326 if (mBufferQueue.size()) {
4327 mBufferQueue.removeAt(0);
4328 delete [] pInBuffer->mBuffer;
4329 delete pInBuffer;
4330 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4331 } else {
4332 break;
4333 }
4334 }
4335 }
4336
4337 // If we could not write all frames, allocate a buffer and queue it for next time.
4338 if (inBuffer.frameCount) {
4339 sp<ThreadBase> thread = mThread.promote();
4340 if (thread != 0 && !thread->standby()) {
4341 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4342 pInBuffer = new Buffer;
4343 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4344 pInBuffer->frameCount = inBuffer.frameCount;
4345 pInBuffer->i16 = pInBuffer->mBuffer;
4346 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4347 mBufferQueue.add(pInBuffer);
4348 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4349 } else {
4350 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
4351 }
4352 }
4353 }
4354
4355 // Calling write() with a 0 length buffer, means that no more data will be written:
4356 // If no more buffers are pending, fill output track buffer to make sure it is started
4357 // by output mixer.
4358 if (frames == 0 && mBufferQueue.size() == 0) {
4359 if (mCblk->user < mCblk->frameCount) {
4360 frames = mCblk->frameCount - mCblk->user;
4361 pInBuffer = new Buffer;
4362 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4363 pInBuffer->frameCount = frames;
4364 pInBuffer->i16 = pInBuffer->mBuffer;
4365 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4366 mBufferQueue.add(pInBuffer);
4367 } else if (mActive) {
4368 stop();
4369 }
4370 }
4371
4372 return outputBufferFull;
4373}
4374
4375status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4376{
4377 int active;
4378 status_t result;
4379 audio_track_cblk_t* cblk = mCblk;
4380 uint32_t framesReq = buffer->frameCount;
4381
4382// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
4383 buffer->frameCount = 0;
4384
4385 uint32_t framesAvail = cblk->framesAvailable();
4386
4387
4388 if (framesAvail == 0) {
4389 Mutex::Autolock _l(cblk->lock);
4390 goto start_loop_here;
4391 while (framesAvail == 0) {
4392 active = mActive;
4393 if (UNLIKELY(!active)) {
4394 LOGV("Not active and NO_MORE_BUFFERS");
4395 return AudioTrack::NO_MORE_BUFFERS;
4396 }
4397 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4398 if (result != NO_ERROR) {
4399 return AudioTrack::NO_MORE_BUFFERS;
4400 }
4401 // read the server count again
4402 start_loop_here:
4403 framesAvail = cblk->framesAvailable_l();
4404 }
4405 }
4406
4407// if (framesAvail < framesReq) {
4408// return AudioTrack::NO_MORE_BUFFERS;
4409// }
4410
4411 if (framesReq > framesAvail) {
4412 framesReq = framesAvail;
4413 }
4414
4415 uint32_t u = cblk->user;
4416 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4417
4418 if (u + framesReq > bufferEnd) {
4419 framesReq = bufferEnd - u;
4420 }
4421
4422 buffer->frameCount = framesReq;
4423 buffer->raw = (void *)cblk->buffer(u);
4424 return NO_ERROR;
4425}
4426
4427
4428void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4429{
4430 size_t size = mBufferQueue.size();
4431 Buffer *pBuffer;
4432
4433 for (size_t i = 0; i < size; i++) {
4434 pBuffer = mBufferQueue.itemAt(i);
4435 delete [] pBuffer->mBuffer;
4436 delete pBuffer;
4437 }
4438 mBufferQueue.clear();
4439}
4440
4441// ----------------------------------------------------------------------------
4442
4443AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4444 : RefBase(),
4445 mAudioFlinger(audioFlinger),
4446 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
Mike J. Chen500e5102011-08-15 13:28:26 -07004447 mPid(pid),
4448 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004449{
4450 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4451}
4452
4453// Client destructor must be called with AudioFlinger::mLock held
4454AudioFlinger::Client::~Client()
4455{
4456 mAudioFlinger->removeClient_l(mPid);
4457}
4458
4459const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4460{
4461 return mMemoryDealer;
4462}
4463
Mike J. Chen500e5102011-08-15 13:28:26 -07004464// Reserve one of the limited slots for a timed audio track associated
4465// with this client
4466bool AudioFlinger::Client::reserveTimedTrack()
4467{
4468 const int kMaxTimedTracksPerClient = 4;
4469
4470 Mutex::Autolock _l(mTimedTrackLock);
4471
4472 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4473 LOGW("can not create timed track - pid %d has exceeded the limit",
4474 mPid);
4475 return false;
4476 }
4477
4478 mTimedTrackCount++;
4479 return true;
4480}
4481
4482// Release a slot for a timed audio track
4483void AudioFlinger::Client::releaseTimedTrack()
4484{
4485 Mutex::Autolock _l(mTimedTrackLock);
4486 mTimedTrackCount--;
4487}
4488
Mathias Agopian65ab4712010-07-14 17:59:35 -07004489// ----------------------------------------------------------------------------
4490
4491AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4492 const sp<IAudioFlingerClient>& client,
4493 pid_t pid)
4494 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4495{
4496}
4497
4498AudioFlinger::NotificationClient::~NotificationClient()
4499{
4500 mClient.clear();
4501}
4502
4503void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4504{
4505 sp<NotificationClient> keep(this);
4506 {
4507 mAudioFlinger->removeNotificationClient(mPid);
4508 }
4509}
4510
4511// ----------------------------------------------------------------------------
4512
4513AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4514 : BnAudioTrack(),
4515 mTrack(track)
4516{
4517}
4518
4519AudioFlinger::TrackHandle::~TrackHandle() {
4520 // just stop the track on deletion, associated resources
4521 // will be freed from the main thread once all pending buffers have
4522 // been played. Unless it's not in the active track list, in which
4523 // case we free everything now...
4524 mTrack->destroy();
4525}
4526
4527status_t AudioFlinger::TrackHandle::start() {
4528 return mTrack->start();
4529}
4530
4531void AudioFlinger::TrackHandle::stop() {
4532 mTrack->stop();
4533}
4534
4535void AudioFlinger::TrackHandle::flush() {
4536 mTrack->flush();
4537}
4538
4539void AudioFlinger::TrackHandle::mute(bool e) {
4540 mTrack->mute(e);
4541}
4542
4543void AudioFlinger::TrackHandle::pause() {
4544 mTrack->pause();
4545}
4546
4547void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4548 mTrack->setVolume(left, right);
4549}
4550
4551sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4552 return mTrack->getCblk();
4553}
4554
4555status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4556{
4557 return mTrack->attachAuxEffect(EffectId);
4558}
4559
Mike J. Chen500e5102011-08-15 13:28:26 -07004560status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4561 sp<IMemory>* buffer) {
4562 if (!mTrack->isTimedTrack())
4563 return INVALID_OPERATION;
4564
4565 PlaybackThread::TimedTrack* tt =
4566 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4567 return tt->allocateTimedBuffer(size, buffer);
4568}
4569
4570status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4571 int64_t pts) {
4572 if (!mTrack->isTimedTrack())
4573 return INVALID_OPERATION;
4574
4575 PlaybackThread::TimedTrack* tt =
4576 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4577 return tt->queueTimedBuffer(buffer, pts);
4578}
4579
4580status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4581 const LinearTransform& xform, int target) {
4582
4583 if (!mTrack->isTimedTrack())
4584 return INVALID_OPERATION;
4585
4586 PlaybackThread::TimedTrack* tt =
4587 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4588 return tt->setMediaTimeTransform(
4589 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4590}
4591
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592status_t AudioFlinger::TrackHandle::onTransact(
4593 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4594{
4595 return BnAudioTrack::onTransact(code, data, reply, flags);
4596}
4597
4598// ----------------------------------------------------------------------------
4599
4600sp<IAudioRecord> AudioFlinger::openRecord(
4601 pid_t pid,
4602 int input,
4603 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004604 uint32_t format,
4605 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004606 int frameCount,
4607 uint32_t flags,
4608 int *sessionId,
4609 status_t *status)
4610{
4611 sp<RecordThread::RecordTrack> recordTrack;
4612 sp<RecordHandle> recordHandle;
4613 sp<Client> client;
4614 wp<Client> wclient;
4615 status_t lStatus;
4616 RecordThread *thread;
4617 size_t inFrameCount;
4618 int lSessionId;
4619
4620 // check calling permissions
4621 if (!recordingAllowed()) {
4622 lStatus = PERMISSION_DENIED;
4623 goto Exit;
4624 }
4625
4626 // add client to list
4627 { // scope for mLock
4628 Mutex::Autolock _l(mLock);
4629 thread = checkRecordThread_l(input);
4630 if (thread == NULL) {
4631 lStatus = BAD_VALUE;
4632 goto Exit;
4633 }
4634
4635 wclient = mClients.valueFor(pid);
4636 if (wclient != NULL) {
4637 client = wclient.promote();
4638 } else {
4639 client = new Client(this, pid);
4640 mClients.add(pid, client);
4641 }
4642
4643 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004644 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645 lSessionId = *sessionId;
4646 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004647 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004648 if (sessionId != NULL) {
4649 *sessionId = lSessionId;
4650 }
4651 }
4652 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004653 recordTrack = thread->createRecordTrack_l(client,
4654 sampleRate,
4655 format,
4656 channelMask,
4657 frameCount,
4658 flags,
4659 lSessionId,
4660 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004661 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004662 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004663 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4664 // destructor is called by the TrackBase destructor with mLock held
4665 client.clear();
4666 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 goto Exit;
4668 }
4669
4670 // return to handle to client
4671 recordHandle = new RecordHandle(recordTrack);
4672 lStatus = NO_ERROR;
4673
4674Exit:
4675 if (status) {
4676 *status = lStatus;
4677 }
4678 return recordHandle;
4679}
4680
4681// ----------------------------------------------------------------------------
4682
4683AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4684 : BnAudioRecord(),
4685 mRecordTrack(recordTrack)
4686{
4687}
4688
4689AudioFlinger::RecordHandle::~RecordHandle() {
4690 stop();
4691}
4692
4693status_t AudioFlinger::RecordHandle::start() {
4694 LOGV("RecordHandle::start()");
4695 return mRecordTrack->start();
4696}
4697
4698void AudioFlinger::RecordHandle::stop() {
4699 LOGV("RecordHandle::stop()");
4700 mRecordTrack->stop();
4701}
4702
4703sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4704 return mRecordTrack->getCblk();
4705}
4706
4707status_t AudioFlinger::RecordHandle::onTransact(
4708 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4709{
4710 return BnAudioRecord::onTransact(code, data, reply, flags);
4711}
4712
4713// ----------------------------------------------------------------------------
4714
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004715AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4716 AudioStreamIn *input,
4717 uint32_t sampleRate,
4718 uint32_t channels,
4719 int id,
4720 uint32_t device) :
4721 ThreadBase(audioFlinger, id, device),
4722 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004724 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004725
4726 snprintf(mName, kNameLength, "AudioIn_%d", id);
4727
Dima Zavinfce7a472011-04-19 22:30:36 -07004728 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004729 mReqSampleRate = sampleRate;
4730 readInputParameters();
4731}
4732
4733
4734AudioFlinger::RecordThread::~RecordThread()
4735{
4736 delete[] mRsmpInBuffer;
4737 if (mResampler != 0) {
4738 delete mResampler;
4739 delete[] mRsmpOutBuffer;
4740 }
4741}
4742
4743void AudioFlinger::RecordThread::onFirstRef()
4744{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004745 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746}
4747
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004748status_t AudioFlinger::RecordThread::readyToRun()
4749{
4750 status_t status = initCheck();
4751 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4752 return status;
4753}
4754
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755bool AudioFlinger::RecordThread::threadLoop()
4756{
4757 AudioBufferProvider::Buffer buffer;
4758 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004759 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004760
Eric Laurent44d98482010-09-30 16:12:31 -07004761 nsecs_t lastWarning = 0;
4762
Eric Laurentfeb0db62011-07-22 09:04:31 -07004763 acquireWakeLock();
4764
Mathias Agopian65ab4712010-07-14 17:59:35 -07004765 // start recording
4766 while (!exitPending()) {
4767
4768 processConfigEvents();
4769
4770 { // scope for mLock
4771 Mutex::Autolock _l(mLock);
4772 checkForNewParameters_l();
4773 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4774 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004775 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004776 mStandby = true;
4777 }
4778
4779 if (exitPending()) break;
4780
Eric Laurentfeb0db62011-07-22 09:04:31 -07004781 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004782 LOGV("RecordThread: loop stopping");
4783 // go to sleep
4784 mWaitWorkCV.wait(mLock);
4785 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004786 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787 continue;
4788 }
4789 if (mActiveTrack != 0) {
4790 if (mActiveTrack->mState == TrackBase::PAUSING) {
4791 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004792 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004793 mStandby = true;
4794 }
4795 mActiveTrack.clear();
4796 mStartStopCond.broadcast();
4797 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4798 if (mReqChannelCount != mActiveTrack->channelCount()) {
4799 mActiveTrack.clear();
4800 mStartStopCond.broadcast();
4801 } else if (mBytesRead != 0) {
4802 // record start succeeds only if first read from audio input
4803 // succeeds
4804 if (mBytesRead > 0) {
4805 mActiveTrack->mState = TrackBase::ACTIVE;
4806 } else {
4807 mActiveTrack.clear();
4808 }
4809 mStartStopCond.broadcast();
4810 }
4811 mStandby = false;
4812 }
4813 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004814 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004815 }
4816
4817 if (mActiveTrack != 0) {
4818 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4819 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004820 unlockEffectChains(effectChains);
4821 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822 continue;
4823 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004824 for (size_t i = 0; i < effectChains.size(); i ++) {
4825 effectChains[i]->process_l();
4826 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004827
Mathias Agopian65ab4712010-07-14 17:59:35 -07004828 buffer.frameCount = mFrameCount;
Mike J. Chen500e5102011-08-15 13:28:26 -07004829 if (LIKELY(mActiveTrack->getNextBuffer(
4830 &buffer, AudioBufferProvider::kInvalidPTS) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 size_t framesOut = buffer.frameCount;
4832 if (mResampler == 0) {
4833 // no resampling
4834 while (framesOut) {
4835 size_t framesIn = mFrameCount - mRsmpInIndex;
4836 if (framesIn) {
4837 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4838 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4839 if (framesIn > framesOut)
4840 framesIn = framesOut;
4841 mRsmpInIndex += framesIn;
4842 framesOut -= framesIn;
4843 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004844 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004845 memcpy(dst, src, framesIn * mFrameSize);
4846 } else {
4847 int16_t *src16 = (int16_t *)src;
4848 int16_t *dst16 = (int16_t *)dst;
4849 if (mChannelCount == 1) {
4850 while (framesIn--) {
4851 *dst16++ = *src16;
4852 *dst16++ = *src16++;
4853 }
4854 } else {
4855 while (framesIn--) {
4856 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4857 src16 += 2;
4858 }
4859 }
4860 }
4861 }
4862 if (framesOut && mFrameCount == mRsmpInIndex) {
4863 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004864 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004865 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004866 framesOut = 0;
4867 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004868 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004869 mRsmpInIndex = 0;
4870 }
4871 if (mBytesRead < 0) {
4872 LOGE("Error reading audio input");
4873 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4874 // Force input into standby so that it tries to
4875 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004876 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004877 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004878 }
4879 mRsmpInIndex = mFrameCount;
4880 framesOut = 0;
4881 buffer.frameCount = 0;
4882 }
4883 }
4884 }
4885 } else {
4886 // resampling
4887
4888 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4889 // alter output frame count as if we were expecting stereo samples
4890 if (mChannelCount == 1 && mReqChannelCount == 1) {
4891 framesOut >>= 1;
4892 }
4893 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4894 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4895 // are 32 bit aligned which should be always true.
4896 if (mChannelCount == 2 && mReqChannelCount == 1) {
4897 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4898 // the resampler always outputs stereo samples: do post stereo to mono conversion
4899 int16_t *src = (int16_t *)mRsmpOutBuffer;
4900 int16_t *dst = buffer.i16;
4901 while (framesOut--) {
4902 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4903 src += 2;
4904 }
4905 } else {
4906 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4907 }
4908
4909 }
4910 mActiveTrack->releaseBuffer(&buffer);
4911 mActiveTrack->overflow();
4912 }
4913 // client isn't retrieving buffers fast enough
4914 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004915 if (!mActiveTrack->setOverflow()) {
4916 nsecs_t now = systemTime();
4917 if ((now - lastWarning) > kWarningThrottle) {
4918 LOGW("RecordThread: buffer overflow");
4919 lastWarning = now;
4920 }
4921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004922 // Release the processor for a while before asking for a new buffer.
4923 // This will give the application more chance to read from the buffer and
4924 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004925 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004926 }
4927 }
Eric Laurentec437d82011-07-26 20:54:46 -07004928 // enable changes in effect chain
4929 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004930 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 }
4932
4933 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004934 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 }
4936 mActiveTrack.clear();
4937
4938 mStartStopCond.broadcast();
4939
Eric Laurentfeb0db62011-07-22 09:04:31 -07004940 releaseWakeLock();
4941
Mathias Agopian65ab4712010-07-14 17:59:35 -07004942 LOGV("RecordThread %p exiting", this);
4943 return false;
4944}
4945
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004946
4947sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4948 const sp<AudioFlinger::Client>& client,
4949 uint32_t sampleRate,
4950 int format,
4951 int channelMask,
4952 int frameCount,
4953 uint32_t flags,
4954 int sessionId,
4955 status_t *status)
4956{
4957 sp<RecordTrack> track;
4958 status_t lStatus;
4959
4960 lStatus = initCheck();
4961 if (lStatus != NO_ERROR) {
4962 LOGE("Audio driver not initialized.");
4963 goto Exit;
4964 }
4965
4966 { // scope for mLock
4967 Mutex::Autolock _l(mLock);
4968
4969 track = new RecordTrack(this, client, sampleRate,
4970 format, channelMask, frameCount, flags, sessionId);
4971
4972 if (track->getCblk() == NULL) {
4973 lStatus = NO_MEMORY;
4974 goto Exit;
4975 }
4976
4977 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004978 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4979 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004980 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004981 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4982 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004983 }
4984 lStatus = NO_ERROR;
4985
4986Exit:
4987 if (status) {
4988 *status = lStatus;
4989 }
4990 return track;
4991}
4992
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4994{
4995 LOGV("RecordThread::start");
4996 sp <ThreadBase> strongMe = this;
4997 status_t status = NO_ERROR;
4998 {
4999 AutoMutex lock(&mLock);
5000 if (mActiveTrack != 0) {
5001 if (recordTrack != mActiveTrack.get()) {
5002 status = -EBUSY;
5003 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
5004 mActiveTrack->mState = TrackBase::ACTIVE;
5005 }
5006 return status;
5007 }
5008
5009 recordTrack->mState = TrackBase::IDLE;
5010 mActiveTrack = recordTrack;
5011 mLock.unlock();
5012 status_t status = AudioSystem::startInput(mId);
5013 mLock.lock();
5014 if (status != NO_ERROR) {
5015 mActiveTrack.clear();
5016 return status;
5017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005018 mRsmpInIndex = mFrameCount;
5019 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005020 if (mResampler != NULL) {
5021 mResampler->reset();
5022 }
5023 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005024 // signal thread to start
5025 LOGV("Signal record thread");
5026 mWaitWorkCV.signal();
5027 // do not wait for mStartStopCond if exiting
5028 if (mExiting) {
5029 mActiveTrack.clear();
5030 status = INVALID_OPERATION;
5031 goto startError;
5032 }
5033 mStartStopCond.wait(mLock);
5034 if (mActiveTrack == 0) {
5035 LOGV("Record failed to start");
5036 status = BAD_VALUE;
5037 goto startError;
5038 }
5039 LOGV("Record started OK");
5040 return status;
5041 }
5042startError:
5043 AudioSystem::stopInput(mId);
5044 return status;
5045}
5046
5047void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
5048 LOGV("RecordThread::stop");
5049 sp <ThreadBase> strongMe = this;
5050 {
5051 AutoMutex lock(&mLock);
5052 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5053 mActiveTrack->mState = TrackBase::PAUSING;
5054 // do not wait for mStartStopCond if exiting
5055 if (mExiting) {
5056 return;
5057 }
5058 mStartStopCond.wait(mLock);
5059 // if we have been restarted, recordTrack == mActiveTrack.get() here
5060 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5061 mLock.unlock();
5062 AudioSystem::stopInput(mId);
5063 mLock.lock();
5064 LOGV("Record stopped OK");
5065 }
5066 }
5067 }
5068}
5069
5070status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5071{
5072 const size_t SIZE = 256;
5073 char buffer[SIZE];
5074 String8 result;
5075 pid_t pid = 0;
5076
5077 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5078 result.append(buffer);
5079
5080 if (mActiveTrack != 0) {
5081 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005082 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005083 mActiveTrack->dump(buffer, SIZE);
5084 result.append(buffer);
5085
5086 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5087 result.append(buffer);
5088 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5089 result.append(buffer);
5090 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
5091 result.append(buffer);
5092 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5093 result.append(buffer);
5094 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5095 result.append(buffer);
5096
5097
5098 } else {
5099 result.append("No record client\n");
5100 }
5101 write(fd, result.string(), result.size());
5102
5103 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005104 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005105
5106 return NO_ERROR;
5107}
5108
Mike J. Chen500e5102011-08-15 13:28:26 -07005109status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110{
5111 size_t framesReq = buffer->frameCount;
5112 size_t framesReady = mFrameCount - mRsmpInIndex;
5113 int channelCount;
5114
5115 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005116 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005117 if (mBytesRead < 0) {
5118 LOGE("RecordThread::getNextBuffer() Error reading audio input");
5119 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5120 // Force input into standby so that it tries to
5121 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005122 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005123 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005124 }
5125 buffer->raw = 0;
5126 buffer->frameCount = 0;
5127 return NOT_ENOUGH_DATA;
5128 }
5129 mRsmpInIndex = 0;
5130 framesReady = mFrameCount;
5131 }
5132
5133 if (framesReq > framesReady) {
5134 framesReq = framesReady;
5135 }
5136
5137 if (mChannelCount == 1 && mReqChannelCount == 2) {
5138 channelCount = 1;
5139 } else {
5140 channelCount = 2;
5141 }
5142 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5143 buffer->frameCount = framesReq;
5144 return NO_ERROR;
5145}
5146
5147void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5148{
5149 mRsmpInIndex += buffer->frameCount;
5150 buffer->frameCount = 0;
5151}
5152
5153bool AudioFlinger::RecordThread::checkForNewParameters_l()
5154{
5155 bool reconfig = false;
5156
5157 while (!mNewParameters.isEmpty()) {
5158 status_t status = NO_ERROR;
5159 String8 keyValuePair = mNewParameters[0];
5160 AudioParameter param = AudioParameter(keyValuePair);
5161 int value;
5162 int reqFormat = mFormat;
5163 int reqSamplingRate = mReqSampleRate;
5164 int reqChannelCount = mReqChannelCount;
5165
5166 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5167 reqSamplingRate = value;
5168 reconfig = true;
5169 }
5170 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5171 reqFormat = value;
5172 reconfig = true;
5173 }
5174 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005175 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005176 reconfig = true;
5177 }
5178 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5179 // do not accept frame count changes if tracks are open as the track buffer
5180 // size depends on frame count and correct behavior would not be garantied
5181 // if frame count is changed after track creation
5182 if (mActiveTrack != 0) {
5183 status = INVALID_OPERATION;
5184 } else {
5185 reconfig = true;
5186 }
5187 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005188 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5189 // forward device change to effects that have requested to be
5190 // aware of attached audio device.
5191 for (size_t i = 0; i < mEffectChains.size(); i++) {
5192 mEffectChains[i]->setDevice_l(value);
5193 }
5194 // store input device and output device but do not forward output device to audio HAL.
5195 // Note that status is ignored by the caller for output device
5196 // (see AudioFlinger::setParameters()
5197 if (value & AUDIO_DEVICE_OUT_ALL) {
5198 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5199 status = BAD_VALUE;
5200 } else {
5201 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005202 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5203 if (mTrack != NULL) {
5204 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005205 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005206 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5207 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5208 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005209 }
5210 mDevice |= (uint32_t)value;
5211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005213 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005215 mInput->stream->common.standby(&mInput->stream->common);
5216 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005217 }
5218 if (reconfig) {
5219 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005220 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005221 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005222 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5223 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005224 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 status = NO_ERROR;
5226 }
5227 if (status == NO_ERROR) {
5228 readInputParameters();
5229 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5230 }
5231 }
5232 }
5233
5234 mNewParameters.removeAt(0);
5235
5236 mParamStatus = status;
5237 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005238 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5239 // already timed out waiting for the status and will never signal the condition.
5240 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005241 }
5242 return reconfig;
5243}
5244
5245String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5246{
Dima Zavinfce7a472011-04-19 22:30:36 -07005247 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005248 String8 out_s8 = String8();
5249
5250 Mutex::Autolock _l(mLock);
5251 if (initCheck() != NO_ERROR) {
5252 return out_s8;
5253 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005254
Dima Zavin799a70e2011-04-18 16:57:27 -07005255 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005256 out_s8 = String8(s);
5257 free(s);
5258 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005259}
5260
5261void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5262 AudioSystem::OutputDescriptor desc;
5263 void *param2 = 0;
5264
5265 switch (event) {
5266 case AudioSystem::INPUT_OPENED:
5267 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005268 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005269 desc.samplingRate = mSampleRate;
5270 desc.format = mFormat;
5271 desc.frameCount = mFrameCount;
5272 desc.latency = 0;
5273 param2 = &desc;
5274 break;
5275
5276 case AudioSystem::INPUT_CLOSED:
5277 default:
5278 break;
5279 }
5280 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5281}
5282
5283void AudioFlinger::RecordThread::readInputParameters()
5284{
5285 if (mRsmpInBuffer) delete mRsmpInBuffer;
5286 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
5287 if (mResampler) delete mResampler;
5288 mResampler = 0;
5289
Dima Zavin799a70e2011-04-18 16:57:27 -07005290 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005291 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5292 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005293 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5294 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
5295 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005296 mFrameCount = mInputBytes / mFrameSize;
5297 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5298
5299 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5300 {
5301 int channelCount;
5302 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5303 // stereo to mono post process as the resampler always outputs stereo.
5304 if (mChannelCount == 1 && mReqChannelCount == 2) {
5305 channelCount = 1;
5306 } else {
5307 channelCount = 2;
5308 }
5309 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5310 mResampler->setSampleRate(mSampleRate);
5311 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5312 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5313
5314 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5315 if (mChannelCount == 1 && mReqChannelCount == 1) {
5316 mFrameCount >>= 1;
5317 }
5318
5319 }
5320 mRsmpInIndex = mFrameCount;
5321}
5322
5323unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5324{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005325 Mutex::Autolock _l(mLock);
5326 if (initCheck() != NO_ERROR) {
5327 return 0;
5328 }
5329
Dima Zavin799a70e2011-04-18 16:57:27 -07005330 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331}
5332
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005333uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5334{
5335 Mutex::Autolock _l(mLock);
5336 uint32_t result = 0;
5337 if (getEffectChain_l(sessionId) != 0) {
5338 result = EFFECT_SESSION;
5339 }
5340
5341 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5342 result |= TRACK_SESSION;
5343 }
5344
5345 return result;
5346}
5347
Eric Laurent59bd0da2011-08-01 09:52:20 -07005348AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5349{
5350 Mutex::Autolock _l(mLock);
5351 return mTrack;
5352}
5353
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005354AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
5355{
5356 Mutex::Autolock _l(mLock);
5357 return mInput;
5358}
5359
5360AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5361{
5362 Mutex::Autolock _l(mLock);
5363 AudioStreamIn *input = mInput;
5364 mInput = NULL;
5365 return input;
5366}
5367
5368// this method must always be called either with ThreadBase mLock held or inside the thread loop
5369audio_stream_t* AudioFlinger::RecordThread::stream()
5370{
5371 if (mInput == NULL) {
5372 return NULL;
5373 }
5374 return &mInput->stream->common;
5375}
5376
5377
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378// ----------------------------------------------------------------------------
5379
5380int AudioFlinger::openOutput(uint32_t *pDevices,
5381 uint32_t *pSamplingRate,
5382 uint32_t *pFormat,
5383 uint32_t *pChannels,
5384 uint32_t *pLatencyMs,
5385 uint32_t flags)
5386{
5387 status_t status;
5388 PlaybackThread *thread = NULL;
5389 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5390 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5391 uint32_t format = pFormat ? *pFormat : 0;
5392 uint32_t channels = pChannels ? *pChannels : 0;
5393 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005394 audio_stream_out_t *outStream;
5395 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396
5397 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5398 pDevices ? *pDevices : 0,
5399 samplingRate,
5400 format,
5401 channels,
5402 flags);
5403
5404 if (pDevices == NULL || *pDevices == 0) {
5405 return 0;
5406 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005407
Mathias Agopian65ab4712010-07-14 17:59:35 -07005408 Mutex::Autolock _l(mLock);
5409
Dima Zavin799a70e2011-04-18 16:57:27 -07005410 outHwDev = findSuitableHwDev_l(*pDevices);
5411 if (outHwDev == NULL)
5412 return 0;
5413
5414 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
5415 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005416 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005417 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 samplingRate,
5419 format,
5420 channels,
5421 status);
5422
5423 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07005424 if (outStream != NULL) {
5425 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005426 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005427
Dima Zavinfce7a472011-04-19 22:30:36 -07005428 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5429 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5430 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005431 thread = new DirectOutputThread(this, output, id, *pDevices);
5432 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
5433 } else {
5434 thread = new MixerThread(this, output, id, *pDevices);
5435 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005436 }
5437 mPlaybackThreads.add(id, thread);
5438
5439 if (pSamplingRate) *pSamplingRate = samplingRate;
5440 if (pFormat) *pFormat = format;
5441 if (pChannels) *pChannels = channels;
5442 if (pLatencyMs) *pLatencyMs = thread->latency();
5443
5444 // notify client processes of the new output creation
5445 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5446 return id;
5447 }
5448
5449 return 0;
5450}
5451
5452int AudioFlinger::openDuplicateOutput(int output1, int output2)
5453{
5454 Mutex::Autolock _l(mLock);
5455 MixerThread *thread1 = checkMixerThread_l(output1);
5456 MixerThread *thread2 = checkMixerThread_l(output2);
5457
5458 if (thread1 == NULL || thread2 == NULL) {
5459 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
5460 return 0;
5461 }
5462
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005463 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005464 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5465 thread->addOutputTrack(thread2);
5466 mPlaybackThreads.add(id, thread);
5467 // notify client processes of the new output creation
5468 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5469 return id;
5470}
5471
5472status_t AudioFlinger::closeOutput(int output)
5473{
5474 // keep strong reference on the playback thread so that
5475 // it is not destroyed while exit() is executed
5476 sp <PlaybackThread> thread;
5477 {
5478 Mutex::Autolock _l(mLock);
5479 thread = checkPlaybackThread_l(output);
5480 if (thread == NULL) {
5481 return BAD_VALUE;
5482 }
5483
5484 LOGV("closeOutput() %d", output);
5485
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005486 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005487 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005488 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5490 dupThread->removeOutputTrack((MixerThread *)thread.get());
5491 }
5492 }
5493 }
5494 void *param2 = 0;
5495 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5496 mPlaybackThreads.removeItem(output);
5497 }
5498 thread->exit();
5499
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005500 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005501 AudioStreamOut *out = thread->clearOutput();
5502 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005503 out->hwDev->close_output_stream(out->hwDev, out->stream);
5504 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 }
5506 return NO_ERROR;
5507}
5508
5509status_t AudioFlinger::suspendOutput(int output)
5510{
5511 Mutex::Autolock _l(mLock);
5512 PlaybackThread *thread = checkPlaybackThread_l(output);
5513
5514 if (thread == NULL) {
5515 return BAD_VALUE;
5516 }
5517
5518 LOGV("suspendOutput() %d", output);
5519 thread->suspend();
5520
5521 return NO_ERROR;
5522}
5523
5524status_t AudioFlinger::restoreOutput(int output)
5525{
5526 Mutex::Autolock _l(mLock);
5527 PlaybackThread *thread = checkPlaybackThread_l(output);
5528
5529 if (thread == NULL) {
5530 return BAD_VALUE;
5531 }
5532
5533 LOGV("restoreOutput() %d", output);
5534
5535 thread->restore();
5536
5537 return NO_ERROR;
5538}
5539
5540int AudioFlinger::openInput(uint32_t *pDevices,
5541 uint32_t *pSamplingRate,
5542 uint32_t *pFormat,
5543 uint32_t *pChannels,
5544 uint32_t acoustics)
5545{
5546 status_t status;
5547 RecordThread *thread = NULL;
5548 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5549 uint32_t format = pFormat ? *pFormat : 0;
5550 uint32_t channels = pChannels ? *pChannels : 0;
5551 uint32_t reqSamplingRate = samplingRate;
5552 uint32_t reqFormat = format;
5553 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005554 audio_stream_in_t *inStream;
5555 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556
5557 if (pDevices == NULL || *pDevices == 0) {
5558 return 0;
5559 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005560
Mathias Agopian65ab4712010-07-14 17:59:35 -07005561 Mutex::Autolock _l(mLock);
5562
Dima Zavin799a70e2011-04-18 16:57:27 -07005563 inHwDev = findSuitableHwDev_l(*pDevices);
5564 if (inHwDev == NULL)
5565 return 0;
5566
5567 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5568 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005569 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005570 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005572 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005573 samplingRate,
5574 format,
5575 channels,
5576 acoustics,
5577 status);
5578
5579 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5580 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5581 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005582 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005583 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005584 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005585 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005586 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005587 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5588 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005589 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005590 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005591 }
5592
Dima Zavin799a70e2011-04-18 16:57:27 -07005593 if (inStream != NULL) {
5594 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5595
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005596 int id = nextUniqueId();
5597 // Start record thread
5598 // RecorThread require both input and output device indication to forward to audio
5599 // pre processing modules
5600 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5601 thread = new RecordThread(this,
5602 input,
5603 reqSamplingRate,
5604 reqChannels,
5605 id,
5606 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005607 mRecordThreads.add(id, thread);
5608 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
5609 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5610 if (pFormat) *pFormat = format;
5611 if (pChannels) *pChannels = reqChannels;
5612
Dima Zavin799a70e2011-04-18 16:57:27 -07005613 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005614
5615 // notify client processes of the new input creation
5616 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5617 return id;
5618 }
5619
5620 return 0;
5621}
5622
5623status_t AudioFlinger::closeInput(int input)
5624{
5625 // keep strong reference on the record thread so that
5626 // it is not destroyed while exit() is executed
5627 sp <RecordThread> thread;
5628 {
5629 Mutex::Autolock _l(mLock);
5630 thread = checkRecordThread_l(input);
5631 if (thread == NULL) {
5632 return BAD_VALUE;
5633 }
5634
5635 LOGV("closeInput() %d", input);
5636 void *param2 = 0;
5637 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5638 mRecordThreads.removeItem(input);
5639 }
5640 thread->exit();
5641
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005642 AudioStreamIn *in = thread->clearInput();
5643 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005644 in->hwDev->close_input_stream(in->hwDev, in->stream);
5645 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005646
5647 return NO_ERROR;
5648}
5649
5650status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5651{
5652 Mutex::Autolock _l(mLock);
5653 MixerThread *dstThread = checkMixerThread_l(output);
5654 if (dstThread == NULL) {
5655 LOGW("setStreamOutput() bad output id %d", output);
5656 return BAD_VALUE;
5657 }
5658
5659 LOGV("setStreamOutput() stream %d to output %d", stream, output);
5660 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5661
Eric Laurent9f6530f2011-08-30 10:18:54 -07005662 dstThread->setStreamValid(stream, true);
5663
Mathias Agopian65ab4712010-07-14 17:59:35 -07005664 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5665 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5666 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005667 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005668 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005669 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005670 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005671 }
Eric Laurentde070132010-07-13 04:45:46 -07005672 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005673
5674 return NO_ERROR;
5675}
5676
5677
5678int AudioFlinger::newAudioSessionId()
5679{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005680 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005681}
5682
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005683void AudioFlinger::acquireAudioSessionId(int audioSession)
5684{
5685 Mutex::Autolock _l(mLock);
5686 int caller = IPCThreadState::self()->getCallingPid();
5687 LOGV("acquiring %d from %d", audioSession, caller);
5688 int num = mAudioSessionRefs.size();
5689 for (int i = 0; i< num; i++) {
5690 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5691 if (ref->sessionid == audioSession && ref->pid == caller) {
5692 ref->cnt++;
5693 LOGV(" incremented refcount to %d", ref->cnt);
5694 return;
5695 }
5696 }
5697 AudioSessionRef *ref = new AudioSessionRef();
5698 ref->sessionid = audioSession;
5699 ref->pid = caller;
5700 ref->cnt = 1;
5701 mAudioSessionRefs.push(ref);
5702 LOGV(" added new entry for %d", ref->sessionid);
5703}
5704
5705void AudioFlinger::releaseAudioSessionId(int audioSession)
5706{
5707 Mutex::Autolock _l(mLock);
5708 int caller = IPCThreadState::self()->getCallingPid();
5709 LOGV("releasing %d from %d", audioSession, caller);
5710 int num = mAudioSessionRefs.size();
5711 for (int i = 0; i< num; i++) {
5712 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5713 if (ref->sessionid == audioSession && ref->pid == caller) {
5714 ref->cnt--;
5715 LOGV(" decremented refcount to %d", ref->cnt);
5716 if (ref->cnt == 0) {
5717 mAudioSessionRefs.removeAt(i);
5718 delete ref;
5719 purgeStaleEffects_l();
5720 }
5721 return;
5722 }
5723 }
5724 LOGW("session id %d not found for pid %d", audioSession, caller);
5725}
5726
5727void AudioFlinger::purgeStaleEffects_l() {
5728
5729 LOGV("purging stale effects");
5730
5731 Vector< sp<EffectChain> > chains;
5732
5733 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5734 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5735 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5736 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005737 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5738 chains.push(ec);
5739 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005740 }
5741 }
5742 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5743 sp<RecordThread> t = mRecordThreads.valueAt(i);
5744 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5745 sp<EffectChain> ec = t->mEffectChains[j];
5746 chains.push(ec);
5747 }
5748 }
5749
5750 for (size_t i = 0; i < chains.size(); i++) {
5751 sp<EffectChain> ec = chains[i];
5752 int sessionid = ec->sessionId();
5753 sp<ThreadBase> t = ec->mThread.promote();
5754 if (t == 0) {
5755 continue;
5756 }
5757 size_t numsessionrefs = mAudioSessionRefs.size();
5758 bool found = false;
5759 for (size_t k = 0; k < numsessionrefs; k++) {
5760 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5761 if (ref->sessionid == sessionid) {
5762 LOGV(" session %d still exists for %d with %d refs",
5763 sessionid, ref->pid, ref->cnt);
5764 found = true;
5765 break;
5766 }
5767 }
5768 if (!found) {
5769 // remove all effects from the chain
5770 while (ec->mEffects.size()) {
5771 sp<EffectModule> effect = ec->mEffects[0];
5772 effect->unPin();
5773 Mutex::Autolock _l (t->mLock);
5774 t->removeEffect_l(effect);
5775 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5776 sp<EffectHandle> handle = effect->mHandles[j].promote();
5777 if (handle != 0) {
5778 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005779 if (handle->mHasControl && handle->mEnabled) {
5780 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5781 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005782 }
5783 }
5784 AudioSystem::unregisterEffect(effect->id());
5785 }
5786 }
5787 }
5788 return;
5789}
5790
Mathias Agopian65ab4712010-07-14 17:59:35 -07005791// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5792AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5793{
5794 PlaybackThread *thread = NULL;
5795 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5796 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5797 }
5798 return thread;
5799}
5800
5801// checkMixerThread_l() must be called with AudioFlinger::mLock held
5802AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5803{
5804 PlaybackThread *thread = checkPlaybackThread_l(output);
5805 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005806 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807 thread = NULL;
5808 }
5809 }
5810 return (MixerThread *)thread;
5811}
5812
5813// checkRecordThread_l() must be called with AudioFlinger::mLock held
5814AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5815{
5816 RecordThread *thread = NULL;
5817 if (mRecordThreads.indexOfKey(input) >= 0) {
5818 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5819 }
5820 return thread;
5821}
5822
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005823uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005824{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005825 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826}
5827
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005828AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5829{
5830 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5831 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005832 AudioStreamOut *output = thread->getOutput();
5833 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005834 return thread;
5835 }
5836 }
5837 return NULL;
5838}
5839
5840uint32_t AudioFlinger::primaryOutputDevice_l()
5841{
5842 PlaybackThread *thread = primaryPlaybackThread_l();
5843
5844 if (thread == NULL) {
5845 return 0;
5846 }
5847
5848 return thread->device();
5849}
5850
5851
Mathias Agopian65ab4712010-07-14 17:59:35 -07005852// ----------------------------------------------------------------------------
5853// Effect management
5854// ----------------------------------------------------------------------------
5855
5856
Mathias Agopian65ab4712010-07-14 17:59:35 -07005857status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5858{
5859 Mutex::Autolock _l(mLock);
5860 return EffectQueryNumberEffects(numEffects);
5861}
5862
5863status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5864{
5865 Mutex::Autolock _l(mLock);
5866 return EffectQueryEffect(index, descriptor);
5867}
5868
5869status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5870{
5871 Mutex::Autolock _l(mLock);
5872 return EffectGetDescriptor(pUuid, descriptor);
5873}
5874
5875
Mathias Agopian65ab4712010-07-14 17:59:35 -07005876sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5877 effect_descriptor_t *pDesc,
5878 const sp<IEffectClient>& effectClient,
5879 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005880 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005881 int sessionId,
5882 status_t *status,
5883 int *id,
5884 int *enabled)
5885{
5886 status_t lStatus = NO_ERROR;
5887 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005888 effect_descriptor_t desc;
5889 sp<Client> client;
5890 wp<Client> wclient;
5891
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005892 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5893 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894
5895 if (pDesc == NULL) {
5896 lStatus = BAD_VALUE;
5897 goto Exit;
5898 }
5899
Eric Laurent84e9a102010-09-23 16:10:16 -07005900 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005901 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005902 lStatus = PERMISSION_DENIED;
5903 goto Exit;
5904 }
5905
Dima Zavinfce7a472011-04-19 22:30:36 -07005906 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005907 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005908 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005909 lStatus = PERMISSION_DENIED;
5910 goto Exit;
5911 }
5912
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005913 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005914 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005915 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005916 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005917 lStatus = BAD_VALUE;
5918 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005919 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005920 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005921 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005922 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005923 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005924 }
5925 }
5926
Mathias Agopian65ab4712010-07-14 17:59:35 -07005927 {
5928 Mutex::Autolock _l(mLock);
5929
Mathias Agopian65ab4712010-07-14 17:59:35 -07005930
5931 if (!EffectIsNullUuid(&pDesc->uuid)) {
5932 // if uuid is specified, request effect descriptor
5933 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5934 if (lStatus < 0) {
5935 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5936 goto Exit;
5937 }
5938 } else {
5939 // if uuid is not specified, look for an available implementation
5940 // of the required type in effect factory
5941 if (EffectIsNullUuid(&pDesc->type)) {
5942 LOGW("createEffect() no effect type");
5943 lStatus = BAD_VALUE;
5944 goto Exit;
5945 }
5946 uint32_t numEffects = 0;
5947 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005948 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005949 bool found = false;
5950
5951 lStatus = EffectQueryNumberEffects(&numEffects);
5952 if (lStatus < 0) {
5953 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5954 goto Exit;
5955 }
5956 for (uint32_t i = 0; i < numEffects; i++) {
5957 lStatus = EffectQueryEffect(i, &desc);
5958 if (lStatus < 0) {
5959 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5960 continue;
5961 }
5962 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5963 // If matching type found save effect descriptor. If the session is
5964 // 0 and the effect is not auxiliary, continue enumeration in case
5965 // an auxiliary version of this effect type is available
5966 found = true;
5967 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005968 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005969 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5970 break;
5971 }
5972 }
5973 }
5974 if (!found) {
5975 lStatus = BAD_VALUE;
5976 LOGW("createEffect() effect not found");
5977 goto Exit;
5978 }
5979 // For same effect type, chose auxiliary version over insert version if
5980 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005981 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005982 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5983 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5984 }
5985 }
5986
5987 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005988 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005989 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5990 lStatus = INVALID_OPERATION;
5991 goto Exit;
5992 }
5993
Eric Laurent59255e42011-07-27 19:49:51 -07005994 // check recording permission for visualizer
5995 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5996 !recordingAllowed()) {
5997 lStatus = PERMISSION_DENIED;
5998 goto Exit;
5999 }
6000
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001 // return effect descriptor
6002 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
6003
6004 // If output is not specified try to find a matching audio session ID in one of the
6005 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07006006 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
6007 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006008 // Note: io is never 0 when creating an effect on an input
6009 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07006010 // look for the thread where the specified audio session is present
6011 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
6012 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006013 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07006014 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07006015 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006016 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006017 if (io == 0) {
6018 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6019 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6020 io = mRecordThreads.keyAt(i);
6021 break;
6022 }
6023 }
6024 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006025 // If no output thread contains the requested session ID, default to
6026 // first output. The effect chain will be moved to the correct output
6027 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006028 if (io == 0 && mPlaybackThreads.size()) {
6029 io = mPlaybackThreads.keyAt(0);
6030 }
6031 LOGV("createEffect() got io %d for effect %s", io, desc.name);
6032 }
6033 ThreadBase *thread = checkRecordThread_l(io);
6034 if (thread == NULL) {
6035 thread = checkPlaybackThread_l(io);
6036 if (thread == NULL) {
6037 LOGE("createEffect() unknown output thread");
6038 lStatus = BAD_VALUE;
6039 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006040 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006041 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006042
Mathias Agopian65ab4712010-07-14 17:59:35 -07006043 wclient = mClients.valueFor(pid);
6044
6045 if (wclient != NULL) {
6046 client = wclient.promote();
6047 } else {
6048 client = new Client(this, pid);
6049 mClients.add(pid, client);
6050 }
6051
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006052 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006053 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6054 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006055 if (handle != 0 && id != NULL) {
6056 *id = handle->id();
6057 }
6058 }
6059
6060Exit:
6061 if(status) {
6062 *status = lStatus;
6063 }
6064 return handle;
6065}
6066
Eric Laurent59255e42011-07-27 19:49:51 -07006067status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006068{
6069 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006070 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006071 Mutex::Autolock _l(mLock);
6072 if (srcOutput == dstOutput) {
6073 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
6074 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006075 }
Eric Laurentde070132010-07-13 04:45:46 -07006076 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6077 if (srcThread == NULL) {
6078 LOGW("moveEffects() bad srcOutput %d", srcOutput);
6079 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006080 }
Eric Laurentde070132010-07-13 04:45:46 -07006081 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6082 if (dstThread == NULL) {
6083 LOGW("moveEffects() bad dstOutput %d", dstOutput);
6084 return BAD_VALUE;
6085 }
6086
6087 Mutex::Autolock _dl(dstThread->mLock);
6088 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006089 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006090
Mathias Agopian65ab4712010-07-14 17:59:35 -07006091 return NO_ERROR;
6092}
6093
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006094// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006095status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006096 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006097 AudioFlinger::PlaybackThread *dstThread,
6098 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006099{
6100 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006101 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006102
Eric Laurent59255e42011-07-27 19:49:51 -07006103 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006104 if (chain == 0) {
6105 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006106 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006107 return INVALID_OPERATION;
6108 }
6109
Eric Laurent39e94f82010-07-28 01:32:47 -07006110 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006111 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07006112 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07006113 // removed.
6114 srcThread->removeEffectChain_l(chain);
6115
6116 // transfer all effects one by one so that new effect chain is created on new thread with
6117 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07006118 int dstOutput = dstThread->id();
6119 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006120 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006121 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6122 while (effect != 0) {
6123 srcThread->removeEffect_l(effect);
6124 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07006125 // removeEffect_l() has stopped the effect if it was active so it must be restarted
6126 if (effect->state() == EffectModule::ACTIVE ||
6127 effect->state() == EffectModule::STOPPING) {
6128 effect->start();
6129 }
Eric Laurent39e94f82010-07-28 01:32:47 -07006130 // if the move request is not received from audio policy manager, the effect must be
6131 // re-registered with the new strategy and output
6132 if (dstChain == 0) {
6133 dstChain = effect->chain().promote();
6134 if (dstChain == 0) {
6135 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
6136 srcThread->addEffect_l(effect);
6137 return NO_INIT;
6138 }
6139 strategy = dstChain->strategy();
6140 }
6141 if (reRegister) {
6142 AudioSystem::unregisterEffect(effect->id());
6143 AudioSystem::registerEffect(&effect->desc(),
6144 dstOutput,
6145 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006146 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006147 effect->id());
6148 }
Eric Laurentde070132010-07-13 04:45:46 -07006149 effect = chain->getEffectFromId_l(0);
6150 }
6151
6152 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153}
6154
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006155
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006157sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 const sp<AudioFlinger::Client>& client,
6159 const sp<IEffectClient>& effectClient,
6160 int32_t priority,
6161 int sessionId,
6162 effect_descriptor_t *desc,
6163 int *enabled,
6164 status_t *status
6165 )
6166{
6167 sp<EffectModule> effect;
6168 sp<EffectHandle> handle;
6169 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006171 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 bool effectCreated = false;
6173 bool effectRegistered = false;
6174
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006175 lStatus = initCheck();
6176 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006178 goto Exit;
6179 }
6180
6181 // Do not allow effects with session ID 0 on direct output or duplicating threads
6182 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07006184 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
6185 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 lStatus = BAD_VALUE;
6187 goto Exit;
6188 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006189 // Only Pre processor effects are allowed on input threads and only on input threads
6190 if ((mType == RECORD &&
6191 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
6192 (mType != RECORD &&
6193 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
6194 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
6195 desc->name, desc->flags, mType);
6196 lStatus = BAD_VALUE;
6197 goto Exit;
6198 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006199
6200 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
6201
6202 { // scope for mLock
6203 Mutex::Autolock _l(mLock);
6204
6205 // check for existing effect chain with the requested audio session
6206 chain = getEffectChain_l(sessionId);
6207 if (chain == 0) {
6208 // create a new chain for this session
6209 LOGV("createEffect_l() new effect chain for session %d", sessionId);
6210 chain = new EffectChain(this, sessionId);
6211 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006212 chain->setStrategy(getStrategyForSession_l(sessionId));
6213 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006215 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006216 }
6217
6218 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
6219
6220 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006221 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006222 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006223 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006224 if (lStatus != NO_ERROR) {
6225 goto Exit;
6226 }
6227 effectRegistered = true;
6228 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006229 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230 lStatus = effect->status();
6231 if (lStatus != NO_ERROR) {
6232 goto Exit;
6233 }
Eric Laurentcab11242010-07-15 12:50:15 -07006234 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006235 if (lStatus != NO_ERROR) {
6236 goto Exit;
6237 }
6238 effectCreated = true;
6239
6240 effect->setDevice(mDevice);
6241 effect->setMode(mAudioFlinger->getMode());
6242 }
6243 // create effect handle and connect it to effect module
6244 handle = new EffectHandle(effect, client, effectClient, priority);
6245 lStatus = effect->addHandle(handle);
6246 if (enabled) {
6247 *enabled = (int)effect->isEnabled();
6248 }
6249 }
6250
6251Exit:
6252 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006253 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006254 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006255 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006256 }
6257 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006258 AudioSystem::unregisterEffect(effect->id());
6259 }
6260 if (chainCreated) {
6261 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 }
6263 handle.clear();
6264 }
6265
6266 if(status) {
6267 *status = lStatus;
6268 }
6269 return handle;
6270}
6271
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006272sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6273{
6274 sp<EffectModule> effect;
6275
6276 sp<EffectChain> chain = getEffectChain_l(sessionId);
6277 if (chain != 0) {
6278 effect = chain->getEffectFromId_l(effectId);
6279 }
6280 return effect;
6281}
6282
Eric Laurentde070132010-07-13 04:45:46 -07006283// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6284// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006285status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006286{
6287 // check for existing effect chain with the requested audio session
6288 int sessionId = effect->sessionId();
6289 sp<EffectChain> chain = getEffectChain_l(sessionId);
6290 bool chainCreated = false;
6291
6292 if (chain == 0) {
6293 // create a new chain for this session
6294 LOGV("addEffect_l() new effect chain for session %d", sessionId);
6295 chain = new EffectChain(this, sessionId);
6296 addEffectChain_l(chain);
6297 chain->setStrategy(getStrategyForSession_l(sessionId));
6298 chainCreated = true;
6299 }
6300 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
6301
6302 if (chain->getEffectFromId_l(effect->id()) != 0) {
6303 LOGW("addEffect_l() %p effect %s already present in chain %p",
6304 this, effect->desc().name, chain.get());
6305 return BAD_VALUE;
6306 }
6307
6308 status_t status = chain->addEffect_l(effect);
6309 if (status != NO_ERROR) {
6310 if (chainCreated) {
6311 removeEffectChain_l(chain);
6312 }
6313 return status;
6314 }
6315
6316 effect->setDevice(mDevice);
6317 effect->setMode(mAudioFlinger->getMode());
6318 return NO_ERROR;
6319}
6320
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006321void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006322
6323 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006325 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6326 detachAuxEffect_l(effect->id());
6327 }
6328
6329 sp<EffectChain> chain = effect->chain().promote();
6330 if (chain != 0) {
6331 // remove effect chain if removing last effect
6332 if (chain->removeEffect_l(effect) == 0) {
6333 removeEffectChain_l(chain);
6334 }
6335 } else {
6336 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
6337 }
6338}
6339
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006340void AudioFlinger::ThreadBase::lockEffectChains_l(
6341 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6342{
6343 effectChains = mEffectChains;
6344 for (size_t i = 0; i < mEffectChains.size(); i++) {
6345 mEffectChains[i]->lock();
6346 }
6347}
6348
6349void AudioFlinger::ThreadBase::unlockEffectChains(
6350 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6351{
6352 for (size_t i = 0; i < effectChains.size(); i++) {
6353 effectChains[i]->unlock();
6354 }
6355}
6356
6357sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6358{
6359 Mutex::Autolock _l(mLock);
6360 return getEffectChain_l(sessionId);
6361}
6362
6363sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6364{
6365 sp<EffectChain> chain;
6366
6367 size_t size = mEffectChains.size();
6368 for (size_t i = 0; i < size; i++) {
6369 if (mEffectChains[i]->sessionId() == sessionId) {
6370 chain = mEffectChains[i];
6371 break;
6372 }
6373 }
6374 return chain;
6375}
6376
6377void AudioFlinger::ThreadBase::setMode(uint32_t mode)
6378{
6379 Mutex::Autolock _l(mLock);
6380 size_t size = mEffectChains.size();
6381 for (size_t i = 0; i < size; i++) {
6382 mEffectChains[i]->setMode_l(mode);
6383 }
6384}
6385
6386void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006387 const wp<EffectHandle>& handle,
6388 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006389
Mathias Agopian65ab4712010-07-14 17:59:35 -07006390 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006391 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006392 // delete the effect module if removing last handle on it
6393 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006394 if (!effect->isPinned() || unpiniflast) {
6395 removeEffect_l(effect);
6396 AudioSystem::unregisterEffect(effect->id());
6397 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006398 }
6399}
6400
6401status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6402{
6403 int session = chain->sessionId();
6404 int16_t *buffer = mMixBuffer;
6405 bool ownsBuffer = false;
6406
6407 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
6408 if (session > 0) {
6409 // Only one effect chain can be present in direct output thread and it uses
6410 // the mix buffer as input
6411 if (mType != DIRECT) {
6412 size_t numSamples = mFrameCount * mChannelCount;
6413 buffer = new int16_t[numSamples];
6414 memset(buffer, 0, numSamples * sizeof(int16_t));
6415 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
6416 ownsBuffer = true;
6417 }
6418
6419 // Attach all tracks with same session ID to this chain.
6420 for (size_t i = 0; i < mTracks.size(); ++i) {
6421 sp<Track> track = mTracks[i];
6422 if (session == track->sessionId()) {
6423 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
6424 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006425 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006426 }
6427 }
6428
6429 // indicate all active tracks in the chain
6430 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6431 sp<Track> track = mActiveTracks[i].promote();
6432 if (track == 0) continue;
6433 if (session == track->sessionId()) {
6434 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006435 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006436 }
6437 }
6438 }
6439
6440 chain->setInBuffer(buffer, ownsBuffer);
6441 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006442 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006443 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006444 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6445 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006446 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006447 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6448 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006449 // Effect chain for other sessions are inserted at beginning of effect
6450 // chains list to be processed before output mix effects. Relative order between other
6451 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 size_t size = mEffectChains.size();
6453 size_t i = 0;
6454 for (i = 0; i < size; i++) {
6455 if (mEffectChains[i]->sessionId() < session) break;
6456 }
6457 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006458 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459
6460 return NO_ERROR;
6461}
6462
6463size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6464{
6465 int session = chain->sessionId();
6466
6467 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
6468
6469 for (size_t i = 0; i < mEffectChains.size(); i++) {
6470 if (chain == mEffectChains[i]) {
6471 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006472 // detach all active tracks from the chain
6473 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6474 sp<Track> track = mActiveTracks[i].promote();
6475 if (track == 0) continue;
6476 if (session == track->sessionId()) {
6477 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6478 chain.get(), session);
6479 chain->decActiveTrackCnt();
6480 }
6481 }
6482
Mathias Agopian65ab4712010-07-14 17:59:35 -07006483 // detach all tracks with same session ID from this chain
6484 for (size_t i = 0; i < mTracks.size(); ++i) {
6485 sp<Track> track = mTracks[i];
6486 if (session == track->sessionId()) {
6487 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006488 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489 }
6490 }
Eric Laurentde070132010-07-13 04:45:46 -07006491 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 }
6493 }
6494 return mEffectChains.size();
6495}
6496
Eric Laurentde070132010-07-13 04:45:46 -07006497status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6498 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499{
6500 Mutex::Autolock _l(mLock);
6501 return attachAuxEffect_l(track, EffectId);
6502}
6503
Eric Laurentde070132010-07-13 04:45:46 -07006504status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6505 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006506{
6507 status_t status = NO_ERROR;
6508
6509 if (EffectId == 0) {
6510 track->setAuxBuffer(0, NULL);
6511 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006512 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6513 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006514 if (effect != 0) {
6515 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6516 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6517 } else {
6518 status = INVALID_OPERATION;
6519 }
6520 } else {
6521 status = BAD_VALUE;
6522 }
6523 }
6524 return status;
6525}
6526
6527void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6528{
6529 for (size_t i = 0; i < mTracks.size(); ++i) {
6530 sp<Track> track = mTracks[i];
6531 if (track->auxEffectId() == effectId) {
6532 attachAuxEffect_l(track, 0);
6533 }
6534 }
6535}
6536
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006537status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6538{
6539 // only one chain per input thread
6540 if (mEffectChains.size() != 0) {
6541 return INVALID_OPERATION;
6542 }
6543 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6544
6545 chain->setInBuffer(NULL);
6546 chain->setOutBuffer(NULL);
6547
Eric Laurent59255e42011-07-27 19:49:51 -07006548 checkSuspendOnAddEffectChain_l(chain);
6549
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006550 mEffectChains.add(chain);
6551
6552 return NO_ERROR;
6553}
6554
6555size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6556{
6557 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6558 LOGW_IF(mEffectChains.size() != 1,
6559 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6560 chain.get(), mEffectChains.size(), this);
6561 if (mEffectChains.size() == 1) {
6562 mEffectChains.removeAt(0);
6563 }
6564 return 0;
6565}
6566
Mathias Agopian65ab4712010-07-14 17:59:35 -07006567// ----------------------------------------------------------------------------
6568// EffectModule implementation
6569// ----------------------------------------------------------------------------
6570
6571#undef LOG_TAG
6572#define LOG_TAG "AudioFlinger::EffectModule"
6573
6574AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6575 const wp<AudioFlinger::EffectChain>& chain,
6576 effect_descriptor_t *desc,
6577 int id,
6578 int sessionId)
6579 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006580 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006581{
6582 LOGV("Constructor %p", this);
6583 int lStatus;
6584 sp<ThreadBase> thread = mThread.promote();
6585 if (thread == 0) {
6586 return;
6587 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006588
6589 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6590
6591 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006592 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006593
6594 if (mStatus != NO_ERROR) {
6595 return;
6596 }
6597 lStatus = init();
6598 if (lStatus < 0) {
6599 mStatus = lStatus;
6600 goto Error;
6601 }
6602
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006603 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6604 mPinned = true;
6605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6607 return;
6608Error:
6609 EffectRelease(mEffectInterface);
6610 mEffectInterface = NULL;
6611 LOGV("Constructor Error %d", mStatus);
6612}
6613
6614AudioFlinger::EffectModule::~EffectModule()
6615{
6616 LOGV("Destructor %p", this);
6617 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006618 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6619 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6620 sp<ThreadBase> thread = mThread.promote();
6621 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006622 audio_stream_t *stream = thread->stream();
6623 if (stream != NULL) {
6624 stream->remove_audio_effect(stream, mEffectInterface);
6625 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006626 }
6627 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006628 // release effect engine
6629 EffectRelease(mEffectInterface);
6630 }
6631}
6632
6633status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6634{
6635 status_t status;
6636
6637 Mutex::Autolock _l(mLock);
6638 // First handle in mHandles has highest priority and controls the effect module
6639 int priority = handle->priority();
6640 size_t size = mHandles.size();
6641 sp<EffectHandle> h;
6642 size_t i;
6643 for (i = 0; i < size; i++) {
6644 h = mHandles[i].promote();
6645 if (h == 0) continue;
6646 if (h->priority() <= priority) break;
6647 }
6648 // if inserted in first place, move effect control from previous owner to this handle
6649 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006650 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006651 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006652 enabled = h->enabled();
6653 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006654 }
Eric Laurent59255e42011-07-27 19:49:51 -07006655 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006656 status = NO_ERROR;
6657 } else {
6658 status = ALREADY_EXISTS;
6659 }
Eric Laurent59255e42011-07-27 19:49:51 -07006660 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006661 mHandles.insertAt(handle, i);
6662 return status;
6663}
6664
6665size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6666{
6667 Mutex::Autolock _l(mLock);
6668 size_t size = mHandles.size();
6669 size_t i;
6670 for (i = 0; i < size; i++) {
6671 if (mHandles[i] == handle) break;
6672 }
6673 if (i == size) {
6674 return size;
6675 }
Eric Laurent59255e42011-07-27 19:49:51 -07006676 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6677
6678 bool enabled = false;
6679 EffectHandle *hdl = handle.unsafe_get();
6680 if (hdl) {
6681 LOGV("removeHandle() unsafe_get OK");
6682 enabled = hdl->enabled();
6683 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684 mHandles.removeAt(i);
6685 size = mHandles.size();
6686 // if removed from first place, move effect control from this handle to next in line
6687 if (i == 0 && size != 0) {
6688 sp<EffectHandle> h = mHandles[0].promote();
6689 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006690 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006691 }
6692 }
6693
Eric Laurentec437d82011-07-26 20:54:46 -07006694 // Prevent calls to process() and other functions on effect interface from now on.
6695 // The effect engine will be released by the destructor when the last strong reference on
6696 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006697 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006698 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006699 }
6700
Mathias Agopian65ab4712010-07-14 17:59:35 -07006701 return size;
6702}
6703
Eric Laurent59255e42011-07-27 19:49:51 -07006704sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6705{
6706 Mutex::Autolock _l(mLock);
6707 sp<EffectHandle> handle;
6708 if (mHandles.size() != 0) {
6709 handle = mHandles[0].promote();
6710 }
6711 return handle;
6712}
6713
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006714void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006715{
Eric Laurent59255e42011-07-27 19:49:51 -07006716 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006717 // keep a strong reference on this EffectModule to avoid calling the
6718 // destructor before we exit
6719 sp<EffectModule> keep(this);
6720 {
6721 sp<ThreadBase> thread = mThread.promote();
6722 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006723 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006724 }
6725 }
6726}
6727
6728void AudioFlinger::EffectModule::updateState() {
6729 Mutex::Autolock _l(mLock);
6730
6731 switch (mState) {
6732 case RESTART:
6733 reset_l();
6734 // FALL THROUGH
6735
6736 case STARTING:
6737 // clear auxiliary effect input buffer for next accumulation
6738 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6739 memset(mConfig.inputCfg.buffer.raw,
6740 0,
6741 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6742 }
6743 start_l();
6744 mState = ACTIVE;
6745 break;
6746 case STOPPING:
6747 stop_l();
6748 mDisableWaitCnt = mMaxDisableWaitCnt;
6749 mState = STOPPED;
6750 break;
6751 case STOPPED:
6752 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6753 // turn off sequence.
6754 if (--mDisableWaitCnt == 0) {
6755 reset_l();
6756 mState = IDLE;
6757 }
6758 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006759 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006760 break;
6761 }
6762}
6763
6764void AudioFlinger::EffectModule::process()
6765{
6766 Mutex::Autolock _l(mLock);
6767
Eric Laurentec437d82011-07-26 20:54:46 -07006768 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006769 mConfig.inputCfg.buffer.raw == NULL ||
6770 mConfig.outputCfg.buffer.raw == NULL) {
6771 return;
6772 }
6773
Eric Laurent8f45bd72010-08-31 13:50:07 -07006774 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006775 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6776 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6777 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6778 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006779 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006780 }
6781
6782 // do the actual processing in the effect engine
6783 int ret = (*mEffectInterface)->process(mEffectInterface,
6784 &mConfig.inputCfg.buffer,
6785 &mConfig.outputCfg.buffer);
6786
6787 // force transition to IDLE state when engine is ready
6788 if (mState == STOPPED && ret == -ENODATA) {
6789 mDisableWaitCnt = 1;
6790 }
6791
6792 // clear auxiliary effect input buffer for next accumulation
6793 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006794 memset(mConfig.inputCfg.buffer.raw, 0,
6795 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006796 }
6797 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006798 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6799 // If an insert effect is idle and input buffer is different from output buffer,
6800 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006801 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006802 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006803 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6804 int16_t *in = mConfig.inputCfg.buffer.s16;
6805 int16_t *out = mConfig.outputCfg.buffer.s16;
6806 for (size_t i = 0; i < frameCnt; i++) {
6807 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006809 }
6810 }
6811}
6812
6813void AudioFlinger::EffectModule::reset_l()
6814{
6815 if (mEffectInterface == NULL) {
6816 return;
6817 }
6818 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6819}
6820
6821status_t AudioFlinger::EffectModule::configure()
6822{
6823 uint32_t channels;
6824 if (mEffectInterface == NULL) {
6825 return NO_INIT;
6826 }
6827
6828 sp<ThreadBase> thread = mThread.promote();
6829 if (thread == 0) {
6830 return DEAD_OBJECT;
6831 }
6832
6833 // TODO: handle configuration of effects replacing track process
6834 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006835 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006836 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006837 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 }
6839
6840 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006841 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006842 } else {
6843 mConfig.inputCfg.channels = channels;
6844 }
6845 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006846 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6847 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006848 mConfig.inputCfg.samplingRate = thread->sampleRate();
6849 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6850 mConfig.inputCfg.bufferProvider.cookie = NULL;
6851 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6852 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6853 mConfig.outputCfg.bufferProvider.cookie = NULL;
6854 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6855 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6856 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6857 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006858 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006859 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860 // - in other sessions:
6861 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6862 // other effect: overwrites output buffer: input buffer == output buffer
6863 // Auxiliary effect:
6864 // accumulates in output buffer: input buffer != output buffer
6865 // Therefore: accumulate <=> input buffer != output buffer
6866 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6867 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6868 } else {
6869 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6870 }
6871 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6872 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6873 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6874 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6875
Eric Laurentde070132010-07-13 04:45:46 -07006876 LOGV("configure() %p thread %p buffer %p framecount %d",
6877 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6878
Mathias Agopian65ab4712010-07-14 17:59:35 -07006879 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006880 uint32_t size = sizeof(int);
6881 status_t status = (*mEffectInterface)->command(mEffectInterface,
6882 EFFECT_CMD_CONFIGURE,
6883 sizeof(effect_config_t),
6884 &mConfig,
6885 &size,
6886 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006887 if (status == 0) {
6888 status = cmdStatus;
6889 }
6890
6891 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6892 (1000 * mConfig.outputCfg.buffer.frameCount);
6893
6894 return status;
6895}
6896
6897status_t AudioFlinger::EffectModule::init()
6898{
6899 Mutex::Autolock _l(mLock);
6900 if (mEffectInterface == NULL) {
6901 return NO_INIT;
6902 }
6903 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006904 uint32_t size = sizeof(status_t);
6905 status_t status = (*mEffectInterface)->command(mEffectInterface,
6906 EFFECT_CMD_INIT,
6907 0,
6908 NULL,
6909 &size,
6910 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911 if (status == 0) {
6912 status = cmdStatus;
6913 }
6914 return status;
6915}
6916
Eric Laurentec35a142011-10-05 17:42:25 -07006917status_t AudioFlinger::EffectModule::start()
6918{
6919 Mutex::Autolock _l(mLock);
6920 return start_l();
6921}
6922
Mathias Agopian65ab4712010-07-14 17:59:35 -07006923status_t AudioFlinger::EffectModule::start_l()
6924{
6925 if (mEffectInterface == NULL) {
6926 return NO_INIT;
6927 }
6928 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006929 uint32_t size = sizeof(status_t);
6930 status_t status = (*mEffectInterface)->command(mEffectInterface,
6931 EFFECT_CMD_ENABLE,
6932 0,
6933 NULL,
6934 &size,
6935 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006936 if (status == 0) {
6937 status = cmdStatus;
6938 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006939 if (status == 0 &&
6940 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6941 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6942 sp<ThreadBase> thread = mThread.promote();
6943 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006944 audio_stream_t *stream = thread->stream();
6945 if (stream != NULL) {
6946 stream->add_audio_effect(stream, mEffectInterface);
6947 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006948 }
6949 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006950 return status;
6951}
6952
Eric Laurentec437d82011-07-26 20:54:46 -07006953status_t AudioFlinger::EffectModule::stop()
6954{
6955 Mutex::Autolock _l(mLock);
6956 return stop_l();
6957}
6958
Mathias Agopian65ab4712010-07-14 17:59:35 -07006959status_t AudioFlinger::EffectModule::stop_l()
6960{
6961 if (mEffectInterface == NULL) {
6962 return NO_INIT;
6963 }
6964 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006965 uint32_t size = sizeof(status_t);
6966 status_t status = (*mEffectInterface)->command(mEffectInterface,
6967 EFFECT_CMD_DISABLE,
6968 0,
6969 NULL,
6970 &size,
6971 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006972 if (status == 0) {
6973 status = cmdStatus;
6974 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006975 if (status == 0 &&
6976 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6977 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6978 sp<ThreadBase> thread = mThread.promote();
6979 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006980 audio_stream_t *stream = thread->stream();
6981 if (stream != NULL) {
6982 stream->remove_audio_effect(stream, mEffectInterface);
6983 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006984 }
6985 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006986 return status;
6987}
6988
Eric Laurent25f43952010-07-28 05:40:18 -07006989status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6990 uint32_t cmdSize,
6991 void *pCmdData,
6992 uint32_t *replySize,
6993 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994{
6995 Mutex::Autolock _l(mLock);
6996// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6997
Eric Laurentec437d82011-07-26 20:54:46 -07006998 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999 return NO_INIT;
7000 }
Eric Laurent25f43952010-07-28 05:40:18 -07007001 status_t status = (*mEffectInterface)->command(mEffectInterface,
7002 cmdCode,
7003 cmdSize,
7004 pCmdData,
7005 replySize,
7006 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007007 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07007008 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007009 for (size_t i = 1; i < mHandles.size(); i++) {
7010 sp<EffectHandle> h = mHandles[i].promote();
7011 if (h != 0) {
7012 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
7013 }
7014 }
7015 }
7016 return status;
7017}
7018
7019status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
7020{
Eric Laurentdb7c0792011-08-10 10:37:50 -07007021
Mathias Agopian65ab4712010-07-14 17:59:35 -07007022 Mutex::Autolock _l(mLock);
7023 LOGV("setEnabled %p enabled %d", this, enabled);
7024
7025 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007026 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
7027 if (enabled && status != NO_ERROR) {
7028 return status;
7029 }
7030
Mathias Agopian65ab4712010-07-14 17:59:35 -07007031 switch (mState) {
7032 // going from disabled to enabled
7033 case IDLE:
7034 mState = STARTING;
7035 break;
7036 case STOPPED:
7037 mState = RESTART;
7038 break;
7039 case STOPPING:
7040 mState = ACTIVE;
7041 break;
7042
7043 // going from enabled to disabled
7044 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007045 mState = STOPPED;
7046 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007047 case STARTING:
7048 mState = IDLE;
7049 break;
7050 case ACTIVE:
7051 mState = STOPPING;
7052 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007053 case DESTROYED:
7054 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007055 }
7056 for (size_t i = 1; i < mHandles.size(); i++) {
7057 sp<EffectHandle> h = mHandles[i].promote();
7058 if (h != 0) {
7059 h->setEnabled(enabled);
7060 }
7061 }
7062 }
7063 return NO_ERROR;
7064}
7065
7066bool AudioFlinger::EffectModule::isEnabled()
7067{
7068 switch (mState) {
7069 case RESTART:
7070 case STARTING:
7071 case ACTIVE:
7072 return true;
7073 case IDLE:
7074 case STOPPING:
7075 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007076 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007077 default:
7078 return false;
7079 }
7080}
7081
Eric Laurent8f45bd72010-08-31 13:50:07 -07007082bool AudioFlinger::EffectModule::isProcessEnabled()
7083{
7084 switch (mState) {
7085 case RESTART:
7086 case ACTIVE:
7087 case STOPPING:
7088 case STOPPED:
7089 return true;
7090 case IDLE:
7091 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007092 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007093 default:
7094 return false;
7095 }
7096}
7097
Mathias Agopian65ab4712010-07-14 17:59:35 -07007098status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7099{
7100 Mutex::Autolock _l(mLock);
7101 status_t status = NO_ERROR;
7102
7103 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7104 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007105 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007106 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7107 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007108 status_t cmdStatus;
7109 uint32_t volume[2];
7110 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007111 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007112 volume[0] = *left;
7113 volume[1] = *right;
7114 if (controller) {
7115 pVolume = volume;
7116 }
Eric Laurent25f43952010-07-28 05:40:18 -07007117 status = (*mEffectInterface)->command(mEffectInterface,
7118 EFFECT_CMD_SET_VOLUME,
7119 size,
7120 volume,
7121 &size,
7122 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007123 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7124 *left = volume[0];
7125 *right = volume[1];
7126 }
7127 }
7128 return status;
7129}
7130
7131status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7132{
7133 Mutex::Autolock _l(mLock);
7134 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007135 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7136 // audio pre processing modules on RecordThread can receive both output and
7137 // input device indication in the same call
7138 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7139 if (dev) {
7140 status_t cmdStatus;
7141 uint32_t size = sizeof(status_t);
7142
7143 status = (*mEffectInterface)->command(mEffectInterface,
7144 EFFECT_CMD_SET_DEVICE,
7145 sizeof(uint32_t),
7146 &dev,
7147 &size,
7148 &cmdStatus);
7149 if (status == NO_ERROR) {
7150 status = cmdStatus;
7151 }
7152 }
7153 dev = device & AUDIO_DEVICE_IN_ALL;
7154 if (dev) {
7155 status_t cmdStatus;
7156 uint32_t size = sizeof(status_t);
7157
7158 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7159 EFFECT_CMD_SET_INPUT_DEVICE,
7160 sizeof(uint32_t),
7161 &dev,
7162 &size,
7163 &cmdStatus);
7164 if (status2 == NO_ERROR) {
7165 status2 = cmdStatus;
7166 }
7167 if (status == NO_ERROR) {
7168 status = status2;
7169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007170 }
7171 }
7172 return status;
7173}
7174
7175status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
7176{
7177 Mutex::Autolock _l(mLock);
7178 status_t status = NO_ERROR;
7179 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007180 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007181 uint32_t size = sizeof(status_t);
7182 status = (*mEffectInterface)->command(mEffectInterface,
7183 EFFECT_CMD_SET_AUDIO_MODE,
7184 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07007185 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007186 &size,
7187 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007188 if (status == NO_ERROR) {
7189 status = cmdStatus;
7190 }
7191 }
7192 return status;
7193}
7194
Eric Laurent59255e42011-07-27 19:49:51 -07007195void AudioFlinger::EffectModule::setSuspended(bool suspended)
7196{
7197 Mutex::Autolock _l(mLock);
7198 mSuspended = suspended;
7199}
7200bool AudioFlinger::EffectModule::suspended()
7201{
7202 Mutex::Autolock _l(mLock);
7203 return mSuspended;
7204}
7205
Mathias Agopian65ab4712010-07-14 17:59:35 -07007206status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7207{
7208 const size_t SIZE = 256;
7209 char buffer[SIZE];
7210 String8 result;
7211
7212 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7213 result.append(buffer);
7214
7215 bool locked = tryLock(mLock);
7216 // failed to lock - AudioFlinger is probably deadlocked
7217 if (!locked) {
7218 result.append("\t\tCould not lock Fx mutex:\n");
7219 }
7220
7221 result.append("\t\tSession Status State Engine:\n");
7222 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7223 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7224 result.append(buffer);
7225
7226 result.append("\t\tDescriptor:\n");
7227 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7228 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7229 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7230 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7231 result.append(buffer);
7232 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7233 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7234 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7235 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7236 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007237 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007238 mDescriptor.apiVersion,
7239 mDescriptor.flags);
7240 result.append(buffer);
7241 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7242 mDescriptor.name);
7243 result.append(buffer);
7244 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7245 mDescriptor.implementor);
7246 result.append(buffer);
7247
7248 result.append("\t\t- Input configuration:\n");
7249 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7250 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7251 (uint32_t)mConfig.inputCfg.buffer.raw,
7252 mConfig.inputCfg.buffer.frameCount,
7253 mConfig.inputCfg.samplingRate,
7254 mConfig.inputCfg.channels,
7255 mConfig.inputCfg.format);
7256 result.append(buffer);
7257
7258 result.append("\t\t- Output configuration:\n");
7259 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7260 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7261 (uint32_t)mConfig.outputCfg.buffer.raw,
7262 mConfig.outputCfg.buffer.frameCount,
7263 mConfig.outputCfg.samplingRate,
7264 mConfig.outputCfg.channels,
7265 mConfig.outputCfg.format);
7266 result.append(buffer);
7267
7268 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7269 result.append(buffer);
7270 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7271 for (size_t i = 0; i < mHandles.size(); ++i) {
7272 sp<EffectHandle> handle = mHandles[i].promote();
7273 if (handle != 0) {
7274 handle->dump(buffer, SIZE);
7275 result.append(buffer);
7276 }
7277 }
7278
7279 result.append("\n");
7280
7281 write(fd, result.string(), result.length());
7282
7283 if (locked) {
7284 mLock.unlock();
7285 }
7286
7287 return NO_ERROR;
7288}
7289
7290// ----------------------------------------------------------------------------
7291// EffectHandle implementation
7292// ----------------------------------------------------------------------------
7293
7294#undef LOG_TAG
7295#define LOG_TAG "AudioFlinger::EffectHandle"
7296
7297AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7298 const sp<AudioFlinger::Client>& client,
7299 const sp<IEffectClient>& effectClient,
7300 int32_t priority)
7301 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007302 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007303 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007304{
7305 LOGV("constructor %p", this);
7306
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007307 if (client == 0) {
7308 return;
7309 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007310 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7311 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7312 if (mCblkMemory != 0) {
7313 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7314
7315 if (mCblk) {
7316 new(mCblk) effect_param_cblk_t();
7317 mBuffer = (uint8_t *)mCblk + bufOffset;
7318 }
7319 } else {
7320 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
7321 return;
7322 }
7323}
7324
7325AudioFlinger::EffectHandle::~EffectHandle()
7326{
7327 LOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007328 disconnect(false);
Eric Laurent59255e42011-07-27 19:49:51 -07007329 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007330}
7331
7332status_t AudioFlinger::EffectHandle::enable()
7333{
Eric Laurent59255e42011-07-27 19:49:51 -07007334 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007335 if (!mHasControl) return INVALID_OPERATION;
7336 if (mEffect == 0) return DEAD_OBJECT;
7337
Eric Laurentdb7c0792011-08-10 10:37:50 -07007338 if (mEnabled) {
7339 return NO_ERROR;
7340 }
7341
Eric Laurent59255e42011-07-27 19:49:51 -07007342 mEnabled = true;
7343
7344 sp<ThreadBase> thread = mEffect->thread().promote();
7345 if (thread != 0) {
7346 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7347 }
7348
7349 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7350 if (mEffect->suspended()) {
7351 return NO_ERROR;
7352 }
7353
Eric Laurentdb7c0792011-08-10 10:37:50 -07007354 status_t status = mEffect->setEnabled(true);
7355 if (status != NO_ERROR) {
7356 if (thread != 0) {
7357 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7358 }
7359 mEnabled = false;
7360 }
7361 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007362}
7363
7364status_t AudioFlinger::EffectHandle::disable()
7365{
Eric Laurent59255e42011-07-27 19:49:51 -07007366 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007367 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007368 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369
Eric Laurentdb7c0792011-08-10 10:37:50 -07007370 if (!mEnabled) {
7371 return NO_ERROR;
7372 }
Eric Laurent59255e42011-07-27 19:49:51 -07007373 mEnabled = false;
7374
7375 if (mEffect->suspended()) {
7376 return NO_ERROR;
7377 }
7378
7379 status_t status = mEffect->setEnabled(false);
7380
7381 sp<ThreadBase> thread = mEffect->thread().promote();
7382 if (thread != 0) {
7383 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7384 }
7385
7386 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007387}
7388
7389void AudioFlinger::EffectHandle::disconnect()
7390{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007391 disconnect(true);
7392}
7393
7394void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
7395{
7396 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007397 if (mEffect == 0) {
7398 return;
7399 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007400 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07007401
Eric Laurenta85a74a2011-10-19 11:44:54 -07007402 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007403 sp<ThreadBase> thread = mEffect->thread().promote();
7404 if (thread != 0) {
7405 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7406 }
Eric Laurent59255e42011-07-27 19:49:51 -07007407 }
7408
Mathias Agopian65ab4712010-07-14 17:59:35 -07007409 // release sp on module => module destructor can be called now
7410 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007411 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007412 if (mCblk) {
7413 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7414 }
7415 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07007416 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7417 mClient.clear();
7418 }
7419}
7420
Eric Laurent25f43952010-07-28 05:40:18 -07007421status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7422 uint32_t cmdSize,
7423 void *pCmdData,
7424 uint32_t *replySize,
7425 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007426{
Eric Laurent25f43952010-07-28 05:40:18 -07007427// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
7428// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007429
7430 // only get parameter command is permitted for applications not controlling the effect
7431 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7432 return INVALID_OPERATION;
7433 }
7434 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007435 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007436
7437 // handle commands that are not forwarded transparently to effect engine
7438 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7439 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7440 // no risk to block the whole media server process or mixer threads is we are stuck here
7441 Mutex::Autolock _l(mCblk->lock);
7442 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7443 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7444 mCblk->serverIndex = 0;
7445 mCblk->clientIndex = 0;
7446 return BAD_VALUE;
7447 }
7448 status_t status = NO_ERROR;
7449 while (mCblk->serverIndex < mCblk->clientIndex) {
7450 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007451 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 int *p = (int *)(mBuffer + mCblk->serverIndex);
7453 int size = *p++;
7454 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
7455 LOGW("command(): invalid parameter block size");
7456 break;
7457 }
7458 effect_param_t *param = (effect_param_t *)p;
7459 if (param->psize == 0 || param->vsize == 0) {
7460 LOGW("command(): null parameter or value size");
7461 mCblk->serverIndex += size;
7462 continue;
7463 }
Eric Laurent25f43952010-07-28 05:40:18 -07007464 uint32_t psize = sizeof(effect_param_t) +
7465 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7466 param->vsize;
7467 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7468 psize,
7469 p,
7470 &rsize,
7471 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007472 // stop at first error encountered
7473 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007475 *(int *)pReplyData = reply;
7476 break;
7477 } else if (reply != NO_ERROR) {
7478 *(int *)pReplyData = reply;
7479 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007480 }
7481 mCblk->serverIndex += size;
7482 }
7483 mCblk->serverIndex = 0;
7484 mCblk->clientIndex = 0;
7485 return status;
7486 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007487 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007488 return enable();
7489 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007490 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007491 return disable();
7492 }
7493
7494 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7495}
7496
7497sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7498 return mCblkMemory;
7499}
7500
Eric Laurent59255e42011-07-27 19:49:51 -07007501void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007502{
7503 LOGV("setControl %p control %d", this, hasControl);
7504
7505 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007506 mEnabled = enabled;
7507
Mathias Agopian65ab4712010-07-14 17:59:35 -07007508 if (signal && mEffectClient != 0) {
7509 mEffectClient->controlStatusChanged(hasControl);
7510 }
7511}
7512
Eric Laurent25f43952010-07-28 05:40:18 -07007513void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7514 uint32_t cmdSize,
7515 void *pCmdData,
7516 uint32_t replySize,
7517 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007518{
7519 if (mEffectClient != 0) {
7520 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7521 }
7522}
7523
7524
7525
7526void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7527{
7528 if (mEffectClient != 0) {
7529 mEffectClient->enableStatusChanged(enabled);
7530 }
7531}
7532
7533status_t AudioFlinger::EffectHandle::onTransact(
7534 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7535{
7536 return BnEffect::onTransact(code, data, reply, flags);
7537}
7538
7539
7540void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7541{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007542 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007543
7544 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7545 (mClient == NULL) ? getpid() : mClient->pid(),
7546 mPriority,
7547 mHasControl,
7548 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007549 mCblk ? mCblk->clientIndex : 0,
7550 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007551 );
7552
7553 if (locked) {
7554 mCblk->lock.unlock();
7555 }
7556}
7557
7558#undef LOG_TAG
7559#define LOG_TAG "AudioFlinger::EffectChain"
7560
7561AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7562 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07007563 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
7564 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7565 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007566{
Dima Zavinfce7a472011-04-19 22:30:36 -07007567 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007568}
7569
7570AudioFlinger::EffectChain::~EffectChain()
7571{
7572 if (mOwnInBuffer) {
7573 delete mInBuffer;
7574 }
7575
7576}
7577
Eric Laurent59255e42011-07-27 19:49:51 -07007578// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007579sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007580{
7581 sp<EffectModule> effect;
7582 size_t size = mEffects.size();
7583
7584 for (size_t i = 0; i < size; i++) {
7585 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7586 effect = mEffects[i];
7587 break;
7588 }
7589 }
7590 return effect;
7591}
7592
Eric Laurent59255e42011-07-27 19:49:51 -07007593// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007594sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007595{
7596 sp<EffectModule> effect;
7597 size_t size = mEffects.size();
7598
7599 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007600 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7601 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602 effect = mEffects[i];
7603 break;
7604 }
7605 }
7606 return effect;
7607}
7608
Eric Laurent59255e42011-07-27 19:49:51 -07007609// getEffectFromType_l() must be called with ThreadBase::mLock held
7610sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7611 const effect_uuid_t *type)
7612{
7613 sp<EffectModule> effect;
7614 size_t size = mEffects.size();
7615
7616 for (size_t i = 0; i < size; i++) {
7617 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7618 effect = mEffects[i];
7619 break;
7620 }
7621 }
7622 return effect;
7623}
7624
Mathias Agopian65ab4712010-07-14 17:59:35 -07007625// Must be called with EffectChain::mLock locked
7626void AudioFlinger::EffectChain::process_l()
7627{
Eric Laurentdac69112010-09-28 14:09:57 -07007628 sp<ThreadBase> thread = mThread.promote();
7629 if (thread == 0) {
7630 LOGW("process_l(): cannot promote mixer thread");
7631 return;
7632 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007633 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7634 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07007635 bool tracksOnSession = false;
7636 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07007637 tracksOnSession = (trackCnt() != 0);
7638 }
7639
7640 // if no track is active, input buffer must be cleared here as the mixer process
7641 // will not do it
7642 if (tracksOnSession &&
7643 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007644 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07007645 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07007646 }
7647
Mathias Agopian65ab4712010-07-14 17:59:35 -07007648 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07007649 // do not process effect if no track is present in same audio session
7650 if (isGlobalSession || tracksOnSession) {
7651 for (size_t i = 0; i < size; i++) {
7652 mEffects[i]->process();
7653 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007654 }
7655 for (size_t i = 0; i < size; i++) {
7656 mEffects[i]->updateState();
7657 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007658}
7659
Eric Laurentcab11242010-07-15 12:50:15 -07007660// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007661status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007662{
7663 effect_descriptor_t desc = effect->desc();
7664 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7665
7666 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007667 effect->setChain(this);
7668 sp<ThreadBase> thread = mThread.promote();
7669 if (thread == 0) {
7670 return NO_INIT;
7671 }
7672 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007673
7674 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7675 // Auxiliary effects are inserted at the beginning of mEffects vector as
7676 // they are processed first and accumulated in chain input buffer
7677 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007678
Mathias Agopian65ab4712010-07-14 17:59:35 -07007679 // the input buffer for auxiliary effect contains mono samples in
7680 // 32 bit format. This is to avoid saturation in AudoMixer
7681 // accumulation stage. Saturation is done in EffectModule::process() before
7682 // calling the process in effect engine
7683 size_t numSamples = thread->frameCount();
7684 int32_t *buffer = new int32_t[numSamples];
7685 memset(buffer, 0, numSamples * sizeof(int32_t));
7686 effect->setInBuffer((int16_t *)buffer);
7687 // auxiliary effects output samples to chain input buffer for further processing
7688 // by insert effects
7689 effect->setOutBuffer(mInBuffer);
7690 } else {
7691 // Insert effects are inserted at the end of mEffects vector as they are processed
7692 // after track and auxiliary effects.
7693 // Insert effect order as a function of indicated preference:
7694 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7695 // another effect is present
7696 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7697 // last effect claiming first position
7698 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7699 // first effect claiming last position
7700 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7701 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7702 // already present
7703
7704 int size = (int)mEffects.size();
7705 int idx_insert = size;
7706 int idx_insert_first = -1;
7707 int idx_insert_last = -1;
7708
7709 for (int i = 0; i < size; i++) {
7710 effect_descriptor_t d = mEffects[i]->desc();
7711 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7712 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7713 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7714 // check invalid effect chaining combinations
7715 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7716 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007717 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007718 return INVALID_OPERATION;
7719 }
7720 // remember position of first insert effect and by default
7721 // select this as insert position for new effect
7722 if (idx_insert == size) {
7723 idx_insert = i;
7724 }
7725 // remember position of last insert effect claiming
7726 // first position
7727 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7728 idx_insert_first = i;
7729 }
7730 // remember position of first insert effect claiming
7731 // last position
7732 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7733 idx_insert_last == -1) {
7734 idx_insert_last = i;
7735 }
7736 }
7737 }
7738
7739 // modify idx_insert from first position if needed
7740 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7741 if (idx_insert_last != -1) {
7742 idx_insert = idx_insert_last;
7743 } else {
7744 idx_insert = size;
7745 }
7746 } else {
7747 if (idx_insert_first != -1) {
7748 idx_insert = idx_insert_first + 1;
7749 }
7750 }
7751
7752 // always read samples from chain input buffer
7753 effect->setInBuffer(mInBuffer);
7754
7755 // if last effect in the chain, output samples to chain
7756 // output buffer, otherwise to chain input buffer
7757 if (idx_insert == size) {
7758 if (idx_insert != 0) {
7759 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7760 mEffects[idx_insert-1]->configure();
7761 }
7762 effect->setOutBuffer(mOutBuffer);
7763 } else {
7764 effect->setOutBuffer(mInBuffer);
7765 }
7766 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007767
Eric Laurentcab11242010-07-15 12:50:15 -07007768 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769 }
7770 effect->configure();
7771 return NO_ERROR;
7772}
7773
Eric Laurentcab11242010-07-15 12:50:15 -07007774// removeEffect_l() must be called with PlaybackThread::mLock held
7775size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007776{
7777 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007778 int size = (int)mEffects.size();
7779 int i;
7780 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7781
7782 for (i = 0; i < size; i++) {
7783 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007784 // calling stop here will remove pre-processing effect from the audio HAL.
7785 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7786 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007787 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7788 mEffects[i]->state() == EffectModule::STOPPING) {
7789 mEffects[i]->stop();
7790 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007791 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7792 delete[] effect->inBuffer();
7793 } else {
7794 if (i == size - 1 && i != 0) {
7795 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7796 mEffects[i - 1]->configure();
7797 }
7798 }
7799 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07007800 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007801 break;
7802 }
7803 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007804
7805 return mEffects.size();
7806}
7807
Eric Laurentcab11242010-07-15 12:50:15 -07007808// setDevice_l() must be called with PlaybackThread::mLock held
7809void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810{
7811 size_t size = mEffects.size();
7812 for (size_t i = 0; i < size; i++) {
7813 mEffects[i]->setDevice(device);
7814 }
7815}
7816
Eric Laurentcab11242010-07-15 12:50:15 -07007817// setMode_l() must be called with PlaybackThread::mLock held
7818void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007819{
7820 size_t size = mEffects.size();
7821 for (size_t i = 0; i < size; i++) {
7822 mEffects[i]->setMode(mode);
7823 }
7824}
7825
Eric Laurentcab11242010-07-15 12:50:15 -07007826// setVolume_l() must be called with PlaybackThread::mLock held
7827bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007828{
7829 uint32_t newLeft = *left;
7830 uint32_t newRight = *right;
7831 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007832 int ctrlIdx = -1;
7833 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007834
Eric Laurentcab11242010-07-15 12:50:15 -07007835 // first update volume controller
7836 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007837 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007838 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7839 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007840 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007841 break;
7842 }
7843 }
7844
7845 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007846 if (hasControl) {
7847 *left = mNewLeftVolume;
7848 *right = mNewRightVolume;
7849 }
7850 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007851 }
7852
7853 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007854 mLeftVolume = newLeft;
7855 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007856
7857 // second get volume update from volume controller
7858 if (ctrlIdx >= 0) {
7859 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007860 mNewLeftVolume = newLeft;
7861 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007862 }
7863 // then indicate volume to all other effects in chain.
7864 // Pass altered volume to effects before volume controller
7865 // and requested volume to effects after controller
7866 uint32_t lVol = newLeft;
7867 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007868
Mathias Agopian65ab4712010-07-14 17:59:35 -07007869 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007870 if ((int)i == ctrlIdx) continue;
7871 // this also works for ctrlIdx == -1 when there is no volume controller
7872 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873 lVol = *left;
7874 rVol = *right;
7875 }
7876 mEffects[i]->setVolume(&lVol, &rVol, false);
7877 }
7878 *left = newLeft;
7879 *right = newRight;
7880
7881 return hasControl;
7882}
7883
Mathias Agopian65ab4712010-07-14 17:59:35 -07007884status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7885{
7886 const size_t SIZE = 256;
7887 char buffer[SIZE];
7888 String8 result;
7889
7890 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7891 result.append(buffer);
7892
7893 bool locked = tryLock(mLock);
7894 // failed to lock - AudioFlinger is probably deadlocked
7895 if (!locked) {
7896 result.append("\tCould not lock mutex:\n");
7897 }
7898
Eric Laurentcab11242010-07-15 12:50:15 -07007899 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7900 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007901 mEffects.size(),
7902 (uint32_t)mInBuffer,
7903 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007904 mActiveTrackCnt);
7905 result.append(buffer);
7906 write(fd, result.string(), result.size());
7907
7908 for (size_t i = 0; i < mEffects.size(); ++i) {
7909 sp<EffectModule> effect = mEffects[i];
7910 if (effect != 0) {
7911 effect->dump(fd, args);
7912 }
7913 }
7914
7915 if (locked) {
7916 mLock.unlock();
7917 }
7918
7919 return NO_ERROR;
7920}
7921
Eric Laurent59255e42011-07-27 19:49:51 -07007922// must be called with ThreadBase::mLock held
7923void AudioFlinger::EffectChain::setEffectSuspended_l(
7924 const effect_uuid_t *type, bool suspend)
7925{
7926 sp<SuspendedEffectDesc> desc;
7927 // use effect type UUID timelow as key as there is no real risk of identical
7928 // timeLow fields among effect type UUIDs.
7929 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7930 if (suspend) {
7931 if (index >= 0) {
7932 desc = mSuspendedEffects.valueAt(index);
7933 } else {
7934 desc = new SuspendedEffectDesc();
7935 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7936 mSuspendedEffects.add(type->timeLow, desc);
7937 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7938 }
7939 if (desc->mRefCount++ == 0) {
7940 sp<EffectModule> effect = getEffectIfEnabled(type);
7941 if (effect != 0) {
7942 desc->mEffect = effect;
7943 effect->setSuspended(true);
7944 effect->setEnabled(false);
7945 }
7946 }
7947 } else {
7948 if (index < 0) {
7949 return;
7950 }
7951 desc = mSuspendedEffects.valueAt(index);
7952 if (desc->mRefCount <= 0) {
7953 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7954 desc->mRefCount = 1;
7955 }
7956 if (--desc->mRefCount == 0) {
7957 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7958 if (desc->mEffect != 0) {
7959 sp<EffectModule> effect = desc->mEffect.promote();
7960 if (effect != 0) {
7961 effect->setSuspended(false);
7962 sp<EffectHandle> handle = effect->controlHandle();
7963 if (handle != 0) {
7964 effect->setEnabled(handle->enabled());
7965 }
7966 }
7967 desc->mEffect.clear();
7968 }
7969 mSuspendedEffects.removeItemsAt(index);
7970 }
7971 }
7972}
7973
7974// must be called with ThreadBase::mLock held
7975void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7976{
7977 sp<SuspendedEffectDesc> desc;
7978
7979 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7980 if (suspend) {
7981 if (index >= 0) {
7982 desc = mSuspendedEffects.valueAt(index);
7983 } else {
7984 desc = new SuspendedEffectDesc();
7985 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7986 LOGV("setEffectSuspendedAll_l() add entry for 0");
7987 }
7988 if (desc->mRefCount++ == 0) {
7989 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7990 for (size_t i = 0; i < effects.size(); i++) {
7991 setEffectSuspended_l(&effects[i]->desc().type, true);
7992 }
7993 }
7994 } else {
7995 if (index < 0) {
7996 return;
7997 }
7998 desc = mSuspendedEffects.valueAt(index);
7999 if (desc->mRefCount <= 0) {
8000 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
8001 desc->mRefCount = 1;
8002 }
8003 if (--desc->mRefCount == 0) {
8004 Vector<const effect_uuid_t *> types;
8005 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
8006 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
8007 continue;
8008 }
8009 types.add(&mSuspendedEffects.valueAt(i)->mType);
8010 }
8011 for (size_t i = 0; i < types.size(); i++) {
8012 setEffectSuspended_l(types[i], false);
8013 }
8014 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
8015 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
8016 }
8017 }
8018}
8019
Eric Laurent6bffdb82011-09-23 08:40:41 -07008020
8021// The volume effect is used for automated tests only
8022#ifndef OPENSL_ES_H_
8023static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
8024 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
8025const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
8026#endif //OPENSL_ES_H_
8027
Eric Laurentdb7c0792011-08-10 10:37:50 -07008028bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
8029{
8030 // auxiliary effects and visualizer are never suspended on output mix
8031 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8032 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008033 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8034 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008035 return false;
8036 }
8037 return true;
8038}
8039
Eric Laurent59255e42011-07-27 19:49:51 -07008040Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
8041{
8042 Vector< sp<EffectModule> > effects;
8043 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008044 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07008045 continue;
8046 }
8047 effects.add(mEffects[i]);
8048 }
8049 return effects;
8050}
8051
8052sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8053 const effect_uuid_t *type)
8054{
8055 sp<EffectModule> effect;
8056 effect = getEffectFromType_l(type);
8057 if (effect != 0 && !effect->isEnabled()) {
8058 effect.clear();
8059 }
8060 return effect;
8061}
8062
8063void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8064 bool enabled)
8065{
8066 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
8067 if (enabled) {
8068 if (index < 0) {
8069 // if the effect is not suspend check if all effects are suspended
8070 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8071 if (index < 0) {
8072 return;
8073 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008074 if (!isEffectEligibleForSuspend(effect->desc())) {
8075 return;
8076 }
Eric Laurent59255e42011-07-27 19:49:51 -07008077 setEffectSuspended_l(&effect->desc().type, enabled);
8078 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008079 if (index < 0) {
8080 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
8081 return;
8082 }
Eric Laurent59255e42011-07-27 19:49:51 -07008083 }
8084 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
8085 effect->desc().type.timeLow);
8086 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8087 // if effect is requested to suspended but was not yet enabled, supend it now.
8088 if (desc->mEffect == 0) {
8089 desc->mEffect = effect;
8090 effect->setEnabled(false);
8091 effect->setSuspended(true);
8092 }
8093 } else {
8094 if (index < 0) {
8095 return;
8096 }
8097 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
8098 effect->desc().type.timeLow);
8099 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8100 desc->mEffect.clear();
8101 effect->setSuspended(false);
8102 }
8103}
8104
Mathias Agopian65ab4712010-07-14 17:59:35 -07008105#undef LOG_TAG
8106#define LOG_TAG "AudioFlinger"
8107
8108// ----------------------------------------------------------------------------
8109
8110status_t AudioFlinger::onTransact(
8111 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8112{
8113 return BnAudioFlinger::onTransact(code, data, reply, flags);
8114}
8115
Mathias Agopian65ab4712010-07-14 17:59:35 -07008116}; // namespace android