blob: dc96e1d3099240f080567c9e5e4f6342706cbde8 [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. Chen535235c2011-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. Chen535235c2011-08-15 13:28:26 -0700158 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterVolumeSW(1.0f),
159 mMasterVolumeSupportLvl(MVS_NONE), mMasterMute(false), mNextUniqueId(1),
Jason Simmonsca426b42011-08-29 16:16:49 -0700160 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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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. Chen535235c2011-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();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001058}
1059
1060void AudioFlinger::ThreadBase::exit()
1061{
1062 // keep a strong ref on ourself so that we wont get
1063 // destroyed in the middle of requestExitAndWait()
1064 sp <ThreadBase> strongMe = this;
1065
1066 LOGV("ThreadBase::exit");
1067 {
1068 AutoMutex lock(&mLock);
1069 mExiting = true;
1070 requestExit();
1071 mWaitWorkCV.signal();
1072 }
1073 requestExitAndWait();
1074}
1075
1076uint32_t AudioFlinger::ThreadBase::sampleRate() const
1077{
1078 return mSampleRate;
1079}
1080
1081int AudioFlinger::ThreadBase::channelCount() const
1082{
1083 return (int)mChannelCount;
1084}
1085
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001086uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001087{
1088 return mFormat;
1089}
1090
1091size_t AudioFlinger::ThreadBase::frameCount() const
1092{
1093 return mFrameCount;
1094}
1095
1096status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1097{
1098 status_t status;
1099
1100 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1101 Mutex::Autolock _l(mLock);
1102
1103 mNewParameters.add(keyValuePairs);
1104 mWaitWorkCV.signal();
1105 // wait condition with timeout in case the thread loop has exited
1106 // before the request could be processed
Eric Laurent60cd0a02011-09-13 11:40:21 -07001107 if (mParamCond.waitRelative(mLock, kSetParametersTimeout) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001108 status = mParamStatus;
1109 mWaitWorkCV.signal();
1110 } else {
1111 status = TIMED_OUT;
1112 }
1113 return status;
1114}
1115
1116void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1117{
1118 Mutex::Autolock _l(mLock);
1119 sendConfigEvent_l(event, param);
1120}
1121
1122// sendConfigEvent_l() must be called with ThreadBase::mLock held
1123void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1124{
1125 ConfigEvent *configEvent = new ConfigEvent();
1126 configEvent->mEvent = event;
1127 configEvent->mParam = param;
1128 mConfigEvents.add(configEvent);
1129 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1130 mWaitWorkCV.signal();
1131}
1132
1133void AudioFlinger::ThreadBase::processConfigEvents()
1134{
1135 mLock.lock();
1136 while(!mConfigEvents.isEmpty()) {
1137 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1138 ConfigEvent *configEvent = mConfigEvents[0];
1139 mConfigEvents.removeAt(0);
1140 // release mLock before locking AudioFlinger mLock: lock order is always
1141 // AudioFlinger then ThreadBase to avoid cross deadlock
1142 mLock.unlock();
1143 mAudioFlinger->mLock.lock();
1144 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1145 mAudioFlinger->mLock.unlock();
1146 delete configEvent;
1147 mLock.lock();
1148 }
1149 mLock.unlock();
1150}
1151
1152status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1153{
1154 const size_t SIZE = 256;
1155 char buffer[SIZE];
1156 String8 result;
1157
1158 bool locked = tryLock(mLock);
1159 if (!locked) {
1160 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1161 write(fd, buffer, strlen(buffer));
1162 }
1163
1164 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1165 result.append(buffer);
1166 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1167 result.append(buffer);
1168 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1169 result.append(buffer);
1170 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1171 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001172 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1173 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001174 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1175 result.append(buffer);
1176 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1177 result.append(buffer);
1178
1179 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1180 result.append(buffer);
1181 result.append(" Index Command");
1182 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1183 snprintf(buffer, SIZE, "\n %02d ", i);
1184 result.append(buffer);
1185 result.append(mNewParameters[i]);
1186 }
1187
1188 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1189 result.append(buffer);
1190 snprintf(buffer, SIZE, " Index event param\n");
1191 result.append(buffer);
1192 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1193 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1194 result.append(buffer);
1195 }
1196 result.append("\n");
1197
1198 write(fd, result.string(), result.size());
1199
1200 if (locked) {
1201 mLock.unlock();
1202 }
1203 return NO_ERROR;
1204}
1205
Eric Laurent1d2bff02011-07-24 17:49:51 -07001206status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1207{
1208 const size_t SIZE = 256;
1209 char buffer[SIZE];
1210 String8 result;
1211
1212 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1213 write(fd, buffer, strlen(buffer));
1214
1215 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1216 sp<EffectChain> chain = mEffectChains[i];
1217 if (chain != 0) {
1218 chain->dump(fd, args);
1219 }
1220 }
1221 return NO_ERROR;
1222}
1223
Eric Laurentfeb0db62011-07-22 09:04:31 -07001224void AudioFlinger::ThreadBase::acquireWakeLock()
1225{
1226 Mutex::Autolock _l(mLock);
1227 acquireWakeLock_l();
1228}
1229
1230void AudioFlinger::ThreadBase::acquireWakeLock_l()
1231{
1232 if (mPowerManager == 0) {
1233 // use checkService() to avoid blocking if power service is not up yet
1234 sp<IBinder> binder =
1235 defaultServiceManager()->checkService(String16("power"));
1236 if (binder == 0) {
1237 LOGW("Thread %s cannot connect to the power manager service", mName);
1238 } else {
1239 mPowerManager = interface_cast<IPowerManager>(binder);
1240 binder->linkToDeath(mDeathRecipient);
1241 }
1242 }
1243 if (mPowerManager != 0) {
1244 sp<IBinder> binder = new BBinder();
1245 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1246 binder,
1247 String16(mName));
1248 if (status == NO_ERROR) {
1249 mWakeLockToken = binder;
1250 }
1251 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1252 }
1253}
1254
1255void AudioFlinger::ThreadBase::releaseWakeLock()
1256{
1257 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001258 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001259}
1260
1261void AudioFlinger::ThreadBase::releaseWakeLock_l()
1262{
1263 if (mWakeLockToken != 0) {
1264 LOGV("releaseWakeLock_l() %s", mName);
1265 if (mPowerManager != 0) {
1266 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1267 }
1268 mWakeLockToken.clear();
1269 }
1270}
1271
1272void AudioFlinger::ThreadBase::clearPowerManager()
1273{
1274 Mutex::Autolock _l(mLock);
1275 releaseWakeLock_l();
1276 mPowerManager.clear();
1277}
1278
1279void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1280{
1281 sp<ThreadBase> thread = mThread.promote();
1282 if (thread != 0) {
1283 thread->clearPowerManager();
1284 }
1285 LOGW("power manager service died !!!");
1286}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001287
Eric Laurent59255e42011-07-27 19:49:51 -07001288void AudioFlinger::ThreadBase::setEffectSuspended(
1289 const effect_uuid_t *type, bool suspend, int sessionId)
1290{
1291 Mutex::Autolock _l(mLock);
1292 setEffectSuspended_l(type, suspend, sessionId);
1293}
1294
1295void AudioFlinger::ThreadBase::setEffectSuspended_l(
1296 const effect_uuid_t *type, bool suspend, int sessionId)
1297{
1298 sp<EffectChain> chain;
1299 chain = getEffectChain_l(sessionId);
1300 if (chain != 0) {
1301 if (type != NULL) {
1302 chain->setEffectSuspended_l(type, suspend);
1303 } else {
1304 chain->setEffectSuspendedAll_l(suspend);
1305 }
1306 }
1307
1308 updateSuspendedSessions_l(type, suspend, sessionId);
1309}
1310
1311void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1312{
1313 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1314 if (index < 0) {
1315 return;
1316 }
1317
1318 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1319 mSuspendedSessions.editValueAt(index);
1320
1321 for (size_t i = 0; i < sessionEffects.size(); i++) {
1322 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1323 for (int j = 0; j < desc->mRefCount; j++) {
1324 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1325 chain->setEffectSuspendedAll_l(true);
1326 } else {
1327 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1328 desc->mType.timeLow);
1329 chain->setEffectSuspended_l(&desc->mType, true);
1330 }
1331 }
1332 }
1333}
1334
Eric Laurent59255e42011-07-27 19:49:51 -07001335void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1336 bool suspend,
1337 int sessionId)
1338{
1339 int index = mSuspendedSessions.indexOfKey(sessionId);
1340
1341 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1342
1343 if (suspend) {
1344 if (index >= 0) {
1345 sessionEffects = mSuspendedSessions.editValueAt(index);
1346 } else {
1347 mSuspendedSessions.add(sessionId, sessionEffects);
1348 }
1349 } else {
1350 if (index < 0) {
1351 return;
1352 }
1353 sessionEffects = mSuspendedSessions.editValueAt(index);
1354 }
1355
1356
1357 int key = EffectChain::kKeyForSuspendAll;
1358 if (type != NULL) {
1359 key = type->timeLow;
1360 }
1361 index = sessionEffects.indexOfKey(key);
1362
1363 sp <SuspendedSessionDesc> desc;
1364 if (suspend) {
1365 if (index >= 0) {
1366 desc = sessionEffects.valueAt(index);
1367 } else {
1368 desc = new SuspendedSessionDesc();
1369 if (type != NULL) {
1370 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1371 }
1372 sessionEffects.add(key, desc);
1373 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1374 }
1375 desc->mRefCount++;
1376 } else {
1377 if (index < 0) {
1378 return;
1379 }
1380 desc = sessionEffects.valueAt(index);
1381 if (--desc->mRefCount == 0) {
1382 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1383 sessionEffects.removeItemsAt(index);
1384 if (sessionEffects.isEmpty()) {
1385 LOGV("updateSuspendedSessions_l() restore removing session %d",
1386 sessionId);
1387 mSuspendedSessions.removeItem(sessionId);
1388 }
1389 }
1390 }
1391 if (!sessionEffects.isEmpty()) {
1392 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1393 }
1394}
1395
1396void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1397 bool enabled,
1398 int sessionId)
1399{
1400 Mutex::Autolock _l(mLock);
1401
Eric Laurentdb7c0792011-08-10 10:37:50 -07001402 if (mType != RECORD) {
1403 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1404 // another session. This gives the priority to well behaved effect control panels
1405 // and applications not using global effects.
1406 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1407 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1408 }
1409 }
Eric Laurent59255e42011-07-27 19:49:51 -07001410
1411 sp<EffectChain> chain = getEffectChain_l(sessionId);
1412 if (chain != 0) {
1413 chain->checkSuspendOnEffectEnabled(effect, enabled);
1414 }
1415}
1416
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417// ----------------------------------------------------------------------------
1418
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001419AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1420 AudioStreamOut* output,
1421 int id,
1422 uint32_t device)
1423 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001425 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001426{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001427 snprintf(mName, kNameLength, "AudioOut_%d", id);
1428
Mathias Agopian65ab4712010-07-14 17:59:35 -07001429 readOutputParameters();
1430
Mike J. Chen535235c2011-08-15 13:28:26 -07001431 mMasterVolume = mAudioFlinger->masterVolumeSW();
1432
Mathias Agopian65ab4712010-07-14 17:59:35 -07001433 mMasterMute = mAudioFlinger->masterMute();
1434
Dima Zavinfce7a472011-04-19 22:30:36 -07001435 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1437 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001438 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 }
1440}
1441
1442AudioFlinger::PlaybackThread::~PlaybackThread()
1443{
1444 delete [] mMixBuffer;
1445}
1446
1447status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1448{
1449 dumpInternals(fd, args);
1450 dumpTracks(fd, args);
1451 dumpEffectChains(fd, args);
1452 return NO_ERROR;
1453}
1454
1455status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1456{
1457 const size_t SIZE = 256;
1458 char buffer[SIZE];
1459 String8 result;
1460
1461 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1462 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001463 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 -07001464 for (size_t i = 0; i < mTracks.size(); ++i) {
1465 sp<Track> track = mTracks[i];
1466 if (track != 0) {
1467 track->dump(buffer, SIZE);
1468 result.append(buffer);
1469 }
1470 }
1471
1472 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1473 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001474 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 -07001475 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1476 wp<Track> wTrack = mActiveTracks[i];
1477 if (wTrack != 0) {
1478 sp<Track> track = wTrack.promote();
1479 if (track != 0) {
1480 track->dump(buffer, SIZE);
1481 result.append(buffer);
1482 }
1483 }
1484 }
1485 write(fd, result.string(), result.size());
1486 return NO_ERROR;
1487}
1488
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1490{
1491 const size_t SIZE = 256;
1492 char buffer[SIZE];
1493 String8 result;
1494
1495 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1496 result.append(buffer);
1497 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1498 result.append(buffer);
1499 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1500 result.append(buffer);
1501 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1502 result.append(buffer);
1503 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1504 result.append(buffer);
1505 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1506 result.append(buffer);
1507 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1508 result.append(buffer);
1509 write(fd, result.string(), result.size());
1510
1511 dumpBase(fd, args);
1512
1513 return NO_ERROR;
1514}
1515
1516// Thread virtuals
1517status_t AudioFlinger::PlaybackThread::readyToRun()
1518{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001519 status_t status = initCheck();
1520 if (status == NO_ERROR) {
1521 LOGI("AudioFlinger's thread %p ready to run", this);
1522 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001524 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001525 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001526}
1527
1528void AudioFlinger::PlaybackThread::onFirstRef()
1529{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001530 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001531}
1532
1533// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1534sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1535 const sp<AudioFlinger::Client>& client,
1536 int streamType,
1537 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001538 uint32_t format,
1539 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001540 int frameCount,
1541 const sp<IMemory>& sharedBuffer,
1542 int sessionId,
Mike J. Chen535235c2011-08-15 13:28:26 -07001543 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 status_t *status)
1545{
1546 sp<Track> track;
1547 status_t lStatus;
1548
1549 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001550 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1551 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1552 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1553 "for output %p with format %d",
1554 sampleRate, format, channelMask, mOutput, mFormat);
1555 lStatus = BAD_VALUE;
1556 goto Exit;
1557 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558 }
1559 } else {
1560 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1561 if (sampleRate > mSampleRate*2) {
1562 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1563 lStatus = BAD_VALUE;
1564 goto Exit;
1565 }
1566 }
1567
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001568 lStatus = initCheck();
1569 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001570 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001571 goto Exit;
1572 }
1573
1574 { // scope for mLock
1575 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001576
1577 // all tracks in same audio session must share the same routing strategy otherwise
1578 // conflicts will happen when tracks are moved from one output to another by audio policy
1579 // manager
1580 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001581 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001582 for (size_t i = 0; i < mTracks.size(); ++i) {
1583 sp<Track> t = mTracks[i];
1584 if (t != 0) {
1585 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001586 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001587 lStatus = BAD_VALUE;
1588 goto Exit;
1589 }
1590 }
1591 }
1592
Mike J. Chen535235c2011-08-15 13:28:26 -07001593 if (!isTimed) {
1594 track = new Track(this, client, streamType, sampleRate, format,
1595 channelMask, frameCount, sharedBuffer, sessionId);
1596 } else {
1597 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1598 channelMask, frameCount, sharedBuffer, sessionId);
1599 }
1600 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001601 lStatus = NO_MEMORY;
1602 goto Exit;
1603 }
1604 mTracks.add(track);
1605
1606 sp<EffectChain> chain = getEffectChain_l(sessionId);
1607 if (chain != 0) {
1608 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1609 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001610 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001611 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001612 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001613
1614 // invalidate track immediately if the stream type was moved to another thread since
1615 // createTrack() was called by the client process.
1616 if (!mStreamTypes[streamType].valid) {
1617 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1618 this, streamType);
1619 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1620 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001621 }
1622 lStatus = NO_ERROR;
1623
1624Exit:
1625 if(status) {
1626 *status = lStatus;
1627 }
1628 return track;
1629}
1630
1631uint32_t AudioFlinger::PlaybackThread::latency() const
1632{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001633 Mutex::Autolock _l(mLock);
1634 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001635 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001636 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001637 return 0;
1638 }
1639}
1640
1641status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1642{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 mMasterVolume = value;
1644 return NO_ERROR;
1645}
1646
1647status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1648{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001649 mMasterMute = muted;
1650 return NO_ERROR;
1651}
1652
1653float AudioFlinger::PlaybackThread::masterVolume() const
1654{
1655 return mMasterVolume;
1656}
1657
1658bool AudioFlinger::PlaybackThread::masterMute() const
1659{
1660 return mMasterMute;
1661}
1662
1663status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1664{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001665 mStreamTypes[stream].volume = value;
1666 return NO_ERROR;
1667}
1668
1669status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1670{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001671 mStreamTypes[stream].mute = muted;
1672 return NO_ERROR;
1673}
1674
1675float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1676{
1677 return mStreamTypes[stream].volume;
1678}
1679
1680bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1681{
1682 return mStreamTypes[stream].mute;
1683}
1684
Mathias Agopian65ab4712010-07-14 17:59:35 -07001685// addTrack_l() must be called with ThreadBase::mLock held
1686status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1687{
1688 status_t status = ALREADY_EXISTS;
1689
1690 // set retry count for buffer fill
1691 track->mRetryCount = kMaxTrackStartupRetries;
1692 if (mActiveTracks.indexOf(track) < 0) {
1693 // the track is newly added, make sure it fills up all its
1694 // buffers before playing. This is to ensure the client will
1695 // effectively get the latency it requested.
1696 track->mFillingUpStatus = Track::FS_FILLING;
1697 track->mResetDone = false;
1698 mActiveTracks.add(track);
1699 if (track->mainBuffer() != mMixBuffer) {
1700 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1701 if (chain != 0) {
1702 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001703 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001704 }
1705 }
1706
1707 status = NO_ERROR;
1708 }
1709
1710 LOGV("mWaitWorkCV.broadcast");
1711 mWaitWorkCV.broadcast();
1712
1713 return status;
1714}
1715
1716// destroyTrack_l() must be called with ThreadBase::mLock held
1717void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1718{
1719 track->mState = TrackBase::TERMINATED;
1720 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001721 removeTrack_l(track);
1722 }
1723}
1724
1725void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1726{
1727 mTracks.remove(track);
1728 deleteTrackName_l(track->name());
1729 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1730 if (chain != 0) {
1731 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732 }
1733}
1734
1735String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1736{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001737 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001738 char *s;
1739
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001740 Mutex::Autolock _l(mLock);
1741 if (initCheck() != NO_ERROR) {
1742 return out_s8;
1743 }
1744
Dima Zavin799a70e2011-04-18 16:57:27 -07001745 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001746 out_s8 = String8(s);
1747 free(s);
1748 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749}
1750
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001751// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1753 AudioSystem::OutputDescriptor desc;
1754 void *param2 = 0;
1755
1756 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1757
1758 switch (event) {
1759 case AudioSystem::OUTPUT_OPENED:
1760 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001761 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001762 desc.samplingRate = mSampleRate;
1763 desc.format = mFormat;
1764 desc.frameCount = mFrameCount;
1765 desc.latency = latency();
1766 param2 = &desc;
1767 break;
1768
1769 case AudioSystem::STREAM_CONFIG_CHANGED:
1770 param2 = &param;
1771 case AudioSystem::OUTPUT_CLOSED:
1772 default:
1773 break;
1774 }
1775 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1776}
1777
1778void AudioFlinger::PlaybackThread::readOutputParameters()
1779{
Dima Zavin799a70e2011-04-18 16:57:27 -07001780 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001781 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1782 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001783 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1784 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1785 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001786
1787 // FIXME - Current mixer implementation only supports stereo output: Always
1788 // Allocate a stereo buffer even if HW output is mono.
1789 if (mMixBuffer != NULL) delete[] mMixBuffer;
1790 mMixBuffer = new int16_t[mFrameCount * 2];
1791 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1792
Eric Laurentde070132010-07-13 04:45:46 -07001793 // force reconfiguration of effect chains and engines to take new buffer size and audio
1794 // parameters into account
1795 // Note that mLock is not held when readOutputParameters() is called from the constructor
1796 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1797 // matter.
1798 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1799 Vector< sp<EffectChain> > effectChains = mEffectChains;
1800 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001801 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001802 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001803}
1804
1805status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1806{
1807 if (halFrames == 0 || dspFrames == 0) {
1808 return BAD_VALUE;
1809 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001810 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001811 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812 return INVALID_OPERATION;
1813 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001814 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001815
Dima Zavin799a70e2011-04-18 16:57:27 -07001816 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817}
1818
Eric Laurent39e94f82010-07-28 01:32:47 -07001819uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001820{
1821 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001822 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001823 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001824 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825 }
1826
1827 for (size_t i = 0; i < mTracks.size(); ++i) {
1828 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001829 if (sessionId == track->sessionId() &&
1830 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001831 result |= TRACK_SESSION;
1832 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001833 }
1834 }
1835
Eric Laurent39e94f82010-07-28 01:32:47 -07001836 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001837}
1838
Eric Laurentde070132010-07-13 04:45:46 -07001839uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1840{
Dima Zavinfce7a472011-04-19 22:30:36 -07001841 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001842 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001843 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1844 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001845 }
1846 for (size_t i = 0; i < mTracks.size(); i++) {
1847 sp<Track> track = mTracks[i];
1848 if (sessionId == track->sessionId() &&
1849 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001850 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001851 }
1852 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001853 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001854}
1855
Mathias Agopian65ab4712010-07-14 17:59:35 -07001856
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001857AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1858{
1859 Mutex::Autolock _l(mLock);
1860 return mOutput;
1861}
1862
1863AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1864{
1865 Mutex::Autolock _l(mLock);
1866 AudioStreamOut *output = mOutput;
1867 mOutput = NULL;
1868 return output;
1869}
1870
1871// this method must always be called either with ThreadBase mLock held or inside the thread loop
1872audio_stream_t* AudioFlinger::PlaybackThread::stream()
1873{
1874 if (mOutput == NULL) {
1875 return NULL;
1876 }
1877 return &mOutput->stream->common;
1878}
1879
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880// ----------------------------------------------------------------------------
1881
Dima Zavin799a70e2011-04-18 16:57:27 -07001882AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 : PlaybackThread(audioFlinger, output, id, device),
1884 mAudioMixer(0)
1885{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001886 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1888
1889 // FIXME - Current mixer implementation only supports stereo output
1890 if (mChannelCount == 1) {
1891 LOGE("Invalid audio hardware channel count");
1892 }
1893}
1894
1895AudioFlinger::MixerThread::~MixerThread()
1896{
1897 delete mAudioMixer;
1898}
1899
1900bool AudioFlinger::MixerThread::threadLoop()
1901{
1902 Vector< sp<Track> > tracksToRemove;
1903 uint32_t mixerStatus = MIXER_IDLE;
1904 nsecs_t standbyTime = systemTime();
1905 size_t mixBufferSize = mFrameCount * mFrameSize;
1906 // FIXME: Relaxed timing because of a certain device that can't meet latency
1907 // Should be reduced to 2x after the vendor fixes the driver issue
1908 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1909 nsecs_t lastWarning = 0;
1910 bool longStandbyExit = false;
1911 uint32_t activeSleepTime = activeSleepTimeUs();
1912 uint32_t idleSleepTime = idleSleepTimeUs();
1913 uint32_t sleepTime = idleSleepTime;
1914 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001915#ifdef DEBUG_CPU_USAGE
1916 ThreadCpuUsage cpu;
1917 const CentralTendencyStatistics& stats = cpu.statistics();
1918#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919
Eric Laurentfeb0db62011-07-22 09:04:31 -07001920 acquireWakeLock();
1921
Mike J. Chen535235c2011-08-15 13:28:26 -07001922 LocalClock lc;
1923 uint64_t localTimeFreq;
1924 localTimeFreq = lc.getLocalFreq();
1925
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 while (!exitPending())
1927 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001928#ifdef DEBUG_CPU_USAGE
1929 cpu.sampleAndEnable();
1930 unsigned n = stats.n();
1931 // cpu.elapsed() is expensive, so don't call it every loop
1932 if ((n & 127) == 1) {
1933 long long elapsed = cpu.elapsed();
1934 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1935 double perLoop = elapsed / (double) n;
1936 double perLoop100 = perLoop * 0.01;
1937 double mean = stats.mean();
1938 double stddev = stats.stddev();
1939 double minimum = stats.minimum();
1940 double maximum = stats.maximum();
1941 cpu.resetStatistics();
1942 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",
1943 elapsed * .000000001, n, perLoop * .000001,
1944 mean * .001,
1945 stddev * .001,
1946 minimum * .001,
1947 maximum * .001,
1948 mean / perLoop100,
1949 stddev / perLoop100,
1950 minimum / perLoop100,
1951 maximum / perLoop100);
1952 }
1953 }
1954#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001955 processConfigEvents();
1956
1957 mixerStatus = MIXER_IDLE;
1958 { // scope for mLock
1959
1960 Mutex::Autolock _l(mLock);
1961
1962 if (checkForNewParameters_l()) {
1963 mixBufferSize = mFrameCount * mFrameSize;
1964 // FIXME: Relaxed timing because of a certain device that can't meet latency
1965 // Should be reduced to 2x after the vendor fixes the driver issue
1966 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1967 activeSleepTime = activeSleepTimeUs();
1968 idleSleepTime = idleSleepTimeUs();
1969 }
1970
1971 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1972
1973 // put audio hardware into standby after short delay
1974 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1975 mSuspended) {
1976 if (!mStandby) {
1977 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001978 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979 mStandby = true;
1980 mBytesWritten = 0;
1981 }
1982
1983 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1984 // we're about to wait, flush the binder command buffer
1985 IPCThreadState::self()->flushCommands();
1986
1987 if (exitPending()) break;
1988
Eric Laurentfeb0db62011-07-22 09:04:31 -07001989 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 // wait until we have something to do...
1991 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1992 mWaitWorkCV.wait(mLock);
1993 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001994 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001995
1996 if (mMasterMute == false) {
1997 char value[PROPERTY_VALUE_MAX];
1998 property_get("ro.audio.silent", value, "0");
1999 if (atoi(value)) {
2000 LOGD("Silence is golden");
2001 setMasterMute(true);
2002 }
2003 }
2004
2005 standbyTime = systemTime() + kStandbyTimeInNsecs;
2006 sleepTime = idleSleepTime;
2007 continue;
2008 }
2009 }
2010
2011 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2012
2013 // prevent any changes in effect chain list and in each effect chain
2014 // during mixing and effect process as the audio buffers could be deleted
2015 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002016 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 }
2018
2019 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mike J. Chen535235c2011-08-15 13:28:26 -07002020 // obtain the presentation timestamp of the next output buffer
2021 int64_t pts;
John Grossmandcdbcc52011-08-29 10:26:47 -07002022 status_t status = INVALID_OPERATION;
2023
2024 if (NULL != mOutput->stream->get_next_write_timestamp) {
2025 status = mOutput->stream->get_next_write_timestamp(
2026 mOutput->stream, &pts);
2027 }
2028
Mike J. Chen535235c2011-08-15 13:28:26 -07002029 if (status != NO_ERROR) {
2030 pts = AudioBufferProvider::kInvalidPTS;
2031 }
2032
Mathias Agopian65ab4712010-07-14 17:59:35 -07002033 // mix buffers...
Mike J. Chen535235c2011-08-15 13:28:26 -07002034 mAudioMixer->process(pts);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002035 sleepTime = 0;
2036 standbyTime = systemTime() + kStandbyTimeInNsecs;
2037 //TODO: delay standby when effects have a tail
2038 } else {
2039 // If no tracks are ready, sleep once for the duration of an output
2040 // buffer size, then write 0s to the output
2041 if (sleepTime == 0) {
2042 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2043 sleepTime = activeSleepTime;
2044 } else {
2045 sleepTime = idleSleepTime;
2046 }
2047 } else if (mBytesWritten != 0 ||
2048 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2049 memset (mMixBuffer, 0, mixBufferSize);
2050 sleepTime = 0;
2051 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2052 }
2053 // TODO add standby time extension fct of effect tail
2054 }
2055
2056 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002057 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002058 }
2059 // sleepTime == 0 means we must write to audio hardware
2060 if (sleepTime == 0) {
2061 for (size_t i = 0; i < effectChains.size(); i ++) {
2062 effectChains[i]->process_l();
2063 }
2064 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002065 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002066 mLastWriteTime = systemTime();
2067 mInWrite = true;
2068 mBytesWritten += mixBufferSize;
2069
Dima Zavin799a70e2011-04-18 16:57:27 -07002070 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002071 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2072 mNumWrites++;
2073 mInWrite = false;
2074 nsecs_t now = systemTime();
2075 nsecs_t delta = now - mLastWriteTime;
2076 if (delta > maxPeriod) {
2077 mNumDelayedWrites++;
2078 if ((now - lastWarning) > kWarningThrottle) {
2079 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2080 ns2ms(delta), mNumDelayedWrites, this);
2081 lastWarning = now;
2082 }
2083 if (mStandby) {
2084 longStandbyExit = true;
2085 }
2086 }
2087 mStandby = false;
2088 } else {
2089 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002090 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 usleep(sleepTime);
2092 }
2093
2094 // finally let go of all our tracks, without the lock held
2095 // since we can't guarantee the destructors won't acquire that
2096 // same lock.
2097 tracksToRemove.clear();
2098
2099 // Effect chains will be actually deleted here if they were removed from
2100 // mEffectChains list during mixing or effects processing
2101 effectChains.clear();
2102 }
2103
2104 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002105 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002106 }
2107
Eric Laurentfeb0db62011-07-22 09:04:31 -07002108 releaseWakeLock();
2109
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 LOGV("MixerThread %p exiting", this);
2111 return false;
2112}
2113
2114// prepareTracks_l() must be called with ThreadBase::mLock held
2115uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2116{
2117
2118 uint32_t mixerStatus = MIXER_IDLE;
2119 // find out which tracks need to be processed
2120 size_t count = activeTracks.size();
2121 size_t mixedTracks = 0;
2122 size_t tracksWithEffect = 0;
2123
2124 float masterVolume = mMasterVolume;
2125 bool masterMute = mMasterMute;
2126
Eric Laurent571d49c2010-08-11 05:20:11 -07002127 if (masterMute) {
2128 masterVolume = 0;
2129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002130 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002131 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002132 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002133 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002134 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002135 masterVolume = (float)((v + (1 << 23)) >> 24);
2136 chain.clear();
2137 }
2138
2139 for (size_t i=0 ; i<count ; i++) {
2140 sp<Track> t = activeTracks[i].promote();
2141 if (t == 0) continue;
2142
2143 Track* const track = t.get();
2144 audio_track_cblk_t* cblk = track->cblk();
2145
2146 // The first time a track is added we wait
2147 // for all its buffers to be filled before processing it
2148 mAudioMixer->setActiveTrack(track->name());
Mike J. Chen535235c2011-08-15 13:28:26 -07002149 if (track->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002150 !track->isPaused() && !track->isTerminated())
2151 {
2152 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
2153
2154 mixedTracks++;
2155
2156 // track->mainBuffer() != mMixBuffer means there is an effect chain
2157 // connected to the track
2158 chain.clear();
2159 if (track->mainBuffer() != mMixBuffer) {
2160 chain = getEffectChain_l(track->sessionId());
2161 // Delegate volume control to effect in track effect chain if needed
2162 if (chain != 0) {
2163 tracksWithEffect++;
2164 } else {
2165 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2166 track->name(), track->sessionId());
2167 }
2168 }
2169
2170
2171 int param = AudioMixer::VOLUME;
2172 if (track->mFillingUpStatus == Track::FS_FILLED) {
2173 // no ramp for the first volume setting
2174 track->mFillingUpStatus = Track::FS_ACTIVE;
2175 if (track->mState == TrackBase::RESUMING) {
2176 track->mState = TrackBase::ACTIVE;
2177 param = AudioMixer::RAMP_VOLUME;
2178 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002179 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 } else if (cblk->server != 0) {
2181 // If the track is stopped before the first frame was mixed,
2182 // do not apply ramp
2183 param = AudioMixer::RAMP_VOLUME;
2184 }
2185
2186 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002187 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002188 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002189 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002190 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002191 if (track->isPausing()) {
2192 track->setPaused();
2193 }
2194 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002195
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 // read original volumes with volume control
2197 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002198 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002199 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2200 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201
Eric Laurente0aed6d2010-09-10 17:44:44 -07002202 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002203 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002204 // Delegate volume control to effect in track effect chain if needed
2205 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2206 // Do not ramp volume if volume is controlled by effect
2207 param = AudioMixer::VOLUME;
2208 track->mHasVolumeController = true;
2209 } else {
2210 // force no volume ramp when volume controller was just disabled or removed
2211 // from effect chain to avoid volume spike
2212 if (track->mHasVolumeController) {
2213 param = AudioMixer::VOLUME;
2214 }
2215 track->mHasVolumeController = false;
2216 }
2217
2218 // Convert volumes from 8.24 to 4.12 format
2219 int16_t left, right, aux;
2220 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2221 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2222 left = int16_t(v_clamped);
2223 v_clamped = (vr + (1 << 11)) >> 12;
2224 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2225 right = int16_t(v_clamped);
2226
2227 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2228 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002229
Mathias Agopian65ab4712010-07-14 17:59:35 -07002230 // XXX: these things DON'T need to be done each time
2231 mAudioMixer->setBufferProvider(track);
2232 mAudioMixer->enable(AudioMixer::MIXING);
2233
2234 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2235 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2236 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2237 mAudioMixer->setParameter(
2238 AudioMixer::TRACK,
2239 AudioMixer::FORMAT, (void *)track->format());
2240 mAudioMixer->setParameter(
2241 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002242 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002243 mAudioMixer->setParameter(
2244 AudioMixer::RESAMPLE,
2245 AudioMixer::SAMPLE_RATE,
2246 (void *)(cblk->sampleRate));
2247 mAudioMixer->setParameter(
2248 AudioMixer::TRACK,
2249 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2250 mAudioMixer->setParameter(
2251 AudioMixer::TRACK,
2252 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2253
2254 // reset retry count
2255 track->mRetryCount = kMaxTrackRetries;
2256 mixerStatus = MIXER_TRACKS_READY;
2257 } else {
2258 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2259 if (track->isStopped()) {
2260 track->reset();
2261 }
2262 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2263 // We have consumed all the buffers of this track.
2264 // Remove it from the list of active tracks.
2265 tracksToRemove->add(track);
2266 } else {
2267 // No buffers for this track. Give it a few chances to
2268 // fill a buffer, then remove it from active list.
2269 if (--(track->mRetryCount) <= 0) {
2270 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2271 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002272 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002273 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 } else if (mixerStatus != MIXER_TRACKS_READY) {
2275 mixerStatus = MIXER_TRACKS_ENABLED;
2276 }
2277 }
2278 mAudioMixer->disable(AudioMixer::MIXING);
2279 }
2280 }
2281
2282 // remove all the tracks that need to be...
2283 count = tracksToRemove->size();
2284 if (UNLIKELY(count)) {
2285 for (size_t i=0 ; i<count ; i++) {
2286 const sp<Track>& track = tracksToRemove->itemAt(i);
2287 mActiveTracks.remove(track);
2288 if (track->mainBuffer() != mMixBuffer) {
2289 chain = getEffectChain_l(track->sessionId());
2290 if (chain != 0) {
2291 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002292 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002293 }
2294 }
2295 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002296 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002297 }
2298 }
2299 }
2300
2301 // mix buffer must be cleared if all tracks are connected to an
2302 // effect chain as in this case the mixer will not write to
2303 // mix buffer and track effects will accumulate into it
2304 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2305 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2306 }
2307
2308 return mixerStatus;
2309}
2310
2311void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2312{
Eric Laurentde070132010-07-13 04:45:46 -07002313 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2314 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002315 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002316
Mathias Agopian65ab4712010-07-14 17:59:35 -07002317 size_t size = mTracks.size();
2318 for (size_t i = 0; i < size; i++) {
2319 sp<Track> t = mTracks[i];
2320 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002321 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002322 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002323 }
2324 }
2325}
2326
Eric Laurent9f6530f2011-08-30 10:18:54 -07002327void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2328{
2329 LOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
2330 this, streamType, valid);
2331 Mutex::Autolock _l(mLock);
2332
2333 mStreamTypes[streamType].valid = valid;
2334}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002335
2336// getTrackName_l() must be called with ThreadBase::mLock held
2337int AudioFlinger::MixerThread::getTrackName_l()
2338{
2339 return mAudioMixer->getTrackName();
2340}
2341
2342// deleteTrackName_l() must be called with ThreadBase::mLock held
2343void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2344{
2345 LOGV("remove track (%d) and delete from mixer", name);
2346 mAudioMixer->deleteTrackName(name);
2347}
2348
2349// checkForNewParameters_l() must be called with ThreadBase::mLock held
2350bool AudioFlinger::MixerThread::checkForNewParameters_l()
2351{
2352 bool reconfig = false;
2353
2354 while (!mNewParameters.isEmpty()) {
2355 status_t status = NO_ERROR;
2356 String8 keyValuePair = mNewParameters[0];
2357 AudioParameter param = AudioParameter(keyValuePair);
2358 int value;
2359
2360 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2361 reconfig = true;
2362 }
2363 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002364 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002365 status = BAD_VALUE;
2366 } else {
2367 reconfig = true;
2368 }
2369 }
2370 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002371 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002372 status = BAD_VALUE;
2373 } else {
2374 reconfig = true;
2375 }
2376 }
2377 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2378 // do not accept frame count changes if tracks are open as the track buffer
2379 // size depends on frame count and correct behavior would not be garantied
2380 // if frame count is changed after track creation
2381 if (!mTracks.isEmpty()) {
2382 status = INVALID_OPERATION;
2383 } else {
2384 reconfig = true;
2385 }
2386 }
2387 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002388 // when changing the audio output device, call addBatteryData to notify
2389 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002390 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002391 uint32_t params = 0;
2392 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002393 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002394 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2395 }
2396
2397 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002398 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002399 // check if any other device (except speaker) is on
2400 if (value & deviceWithoutSpeaker ) {
2401 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2402 }
2403
2404 if (params != 0) {
2405 addBatteryData(params);
2406 }
2407 }
2408
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 // forward device change to effects that have requested to be
2410 // aware of attached audio device.
2411 mDevice = (uint32_t)value;
2412 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002413 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002414 }
2415 }
2416
2417 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002418 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002419 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002420 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002421 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002422 mStandby = true;
2423 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002424 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002425 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 }
2427 if (status == NO_ERROR && reconfig) {
2428 delete mAudioMixer;
2429 readOutputParameters();
2430 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2431 for (size_t i = 0; i < mTracks.size() ; i++) {
2432 int name = getTrackName_l();
2433 if (name < 0) break;
2434 mTracks[i]->mName = name;
2435 // limit track sample rate to 2 x new output sample rate
2436 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2437 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2438 }
2439 }
2440 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2441 }
2442 }
2443
2444 mNewParameters.removeAt(0);
2445
2446 mParamStatus = status;
2447 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002448 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2449 // already timed out waiting for the status and will never signal the condition.
2450 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451 }
2452 return reconfig;
2453}
2454
2455status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2456{
2457 const size_t SIZE = 256;
2458 char buffer[SIZE];
2459 String8 result;
2460
2461 PlaybackThread::dumpInternals(fd, args);
2462
2463 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2464 result.append(buffer);
2465 write(fd, result.string(), result.size());
2466 return NO_ERROR;
2467}
2468
2469uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2470{
Dima Zavin799a70e2011-04-18 16:57:27 -07002471 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472}
2473
2474uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2475{
Eric Laurent60e18242010-07-29 06:50:24 -07002476 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002477}
2478
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002479uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2480{
2481 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2482}
2483
Mathias Agopian65ab4712010-07-14 17:59:35 -07002484// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002485AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002486 : PlaybackThread(audioFlinger, output, id, device)
2487{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002488 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002489}
2490
2491AudioFlinger::DirectOutputThread::~DirectOutputThread()
2492{
2493}
2494
2495
2496static inline int16_t clamp16(int32_t sample)
2497{
2498 if ((sample>>15) ^ (sample>>31))
2499 sample = 0x7FFF ^ (sample>>31);
2500 return sample;
2501}
2502
2503static inline
2504int32_t mul(int16_t in, int16_t v)
2505{
2506#if defined(__arm__) && !defined(__thumb__)
2507 int32_t out;
2508 asm( "smulbb %[out], %[in], %[v] \n"
2509 : [out]"=r"(out)
2510 : [in]"%r"(in), [v]"r"(v)
2511 : );
2512 return out;
2513#else
2514 return in * int32_t(v);
2515#endif
2516}
2517
2518void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2519{
2520 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002521 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522 return;
2523 }
2524
2525 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002526 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002527 size_t count = mFrameCount * mChannelCount;
2528 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2529 int16_t *dst = mMixBuffer + count-1;
2530 while(count--) {
2531 *dst-- = (int16_t)(*src--^0x80) << 8;
2532 }
2533 }
2534
2535 size_t frameCount = mFrameCount;
2536 int16_t *out = mMixBuffer;
2537 if (ramp) {
2538 if (mChannelCount == 1) {
2539 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2540 int32_t vlInc = d / (int32_t)frameCount;
2541 int32_t vl = ((int32_t)mLeftVolShort << 16);
2542 do {
2543 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2544 out++;
2545 vl += vlInc;
2546 } while (--frameCount);
2547
2548 } else {
2549 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2550 int32_t vlInc = d / (int32_t)frameCount;
2551 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2552 int32_t vrInc = d / (int32_t)frameCount;
2553 int32_t vl = ((int32_t)mLeftVolShort << 16);
2554 int32_t vr = ((int32_t)mRightVolShort << 16);
2555 do {
2556 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2557 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2558 out += 2;
2559 vl += vlInc;
2560 vr += vrInc;
2561 } while (--frameCount);
2562 }
2563 } else {
2564 if (mChannelCount == 1) {
2565 do {
2566 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2567 out++;
2568 } while (--frameCount);
2569 } else {
2570 do {
2571 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2572 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2573 out += 2;
2574 } while (--frameCount);
2575 }
2576 }
2577
2578 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002579 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002580 size_t count = mFrameCount * mChannelCount;
2581 int16_t *src = mMixBuffer;
2582 uint8_t *dst = (uint8_t *)mMixBuffer;
2583 while(count--) {
2584 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2585 }
2586 }
2587
2588 mLeftVolShort = leftVol;
2589 mRightVolShort = rightVol;
2590}
2591
2592bool AudioFlinger::DirectOutputThread::threadLoop()
2593{
2594 uint32_t mixerStatus = MIXER_IDLE;
2595 sp<Track> trackToRemove;
2596 sp<Track> activeTrack;
2597 nsecs_t standbyTime = systemTime();
2598 int8_t *curBuf;
2599 size_t mixBufferSize = mFrameCount*mFrameSize;
2600 uint32_t activeSleepTime = activeSleepTimeUs();
2601 uint32_t idleSleepTime = idleSleepTimeUs();
2602 uint32_t sleepTime = idleSleepTime;
2603 // use shorter standby delay as on normal output to release
2604 // hardware resources as soon as possible
2605 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2606
Eric Laurentfeb0db62011-07-22 09:04:31 -07002607 acquireWakeLock();
2608
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609 while (!exitPending())
2610 {
2611 bool rampVolume;
2612 uint16_t leftVol;
2613 uint16_t rightVol;
2614 Vector< sp<EffectChain> > effectChains;
2615
2616 processConfigEvents();
2617
2618 mixerStatus = MIXER_IDLE;
2619
2620 { // scope for the mLock
2621
2622 Mutex::Autolock _l(mLock);
2623
2624 if (checkForNewParameters_l()) {
2625 mixBufferSize = mFrameCount*mFrameSize;
2626 activeSleepTime = activeSleepTimeUs();
2627 idleSleepTime = idleSleepTimeUs();
2628 standbyDelay = microseconds(activeSleepTime*2);
2629 }
2630
2631 // put audio hardware into standby after short delay
2632 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2633 mSuspended) {
2634 // wait until we have something to do...
2635 if (!mStandby) {
2636 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002637 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002638 mStandby = true;
2639 mBytesWritten = 0;
2640 }
2641
2642 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2643 // we're about to wait, flush the binder command buffer
2644 IPCThreadState::self()->flushCommands();
2645
2646 if (exitPending()) break;
2647
Eric Laurentfeb0db62011-07-22 09:04:31 -07002648 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2650 mWaitWorkCV.wait(mLock);
2651 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002652 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653
2654 if (mMasterMute == false) {
2655 char value[PROPERTY_VALUE_MAX];
2656 property_get("ro.audio.silent", value, "0");
2657 if (atoi(value)) {
2658 LOGD("Silence is golden");
2659 setMasterMute(true);
2660 }
2661 }
2662
2663 standbyTime = systemTime() + standbyDelay;
2664 sleepTime = idleSleepTime;
2665 continue;
2666 }
2667 }
2668
2669 effectChains = mEffectChains;
2670
2671 // find out which tracks need to be processed
2672 if (mActiveTracks.size() != 0) {
2673 sp<Track> t = mActiveTracks[0].promote();
2674 if (t == 0) continue;
2675
2676 Track* const track = t.get();
2677 audio_track_cblk_t* cblk = track->cblk();
2678
2679 // The first time a track is added we wait
2680 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002681 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002682 !track->isPaused() && !track->isTerminated())
2683 {
2684 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2685
2686 if (track->mFillingUpStatus == Track::FS_FILLED) {
2687 track->mFillingUpStatus = Track::FS_ACTIVE;
2688 mLeftVolFloat = mRightVolFloat = 0;
2689 mLeftVolShort = mRightVolShort = 0;
2690 if (track->mState == TrackBase::RESUMING) {
2691 track->mState = TrackBase::ACTIVE;
2692 rampVolume = true;
2693 }
2694 } else if (cblk->server != 0) {
2695 // If the track is stopped before the first frame was mixed,
2696 // do not apply ramp
2697 rampVolume = true;
2698 }
2699 // compute volume for this track
2700 float left, right;
2701 if (track->isMuted() || mMasterMute || track->isPausing() ||
2702 mStreamTypes[track->type()].mute) {
2703 left = right = 0;
2704 if (track->isPausing()) {
2705 track->setPaused();
2706 }
2707 } else {
2708 float typeVolume = mStreamTypes[track->type()].volume;
2709 float v = mMasterVolume * typeVolume;
2710 float v_clamped = v * cblk->volume[0];
2711 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2712 left = v_clamped/MAX_GAIN;
2713 v_clamped = v * cblk->volume[1];
2714 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2715 right = v_clamped/MAX_GAIN;
2716 }
2717
2718 if (left != mLeftVolFloat || right != mRightVolFloat) {
2719 mLeftVolFloat = left;
2720 mRightVolFloat = right;
2721
2722 // If audio HAL implements volume control,
2723 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002724 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002725 left = 1.0f;
2726 right = 1.0f;
2727 }
2728
2729 // Convert volumes from float to 8.24
2730 uint32_t vl = (uint32_t)(left * (1 << 24));
2731 uint32_t vr = (uint32_t)(right * (1 << 24));
2732
2733 // Delegate volume control to effect in track effect chain if needed
2734 // only one effect chain can be present on DirectOutputThread, so if
2735 // there is one, the track is connected to it
2736 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002737 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002738 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002739 rampVolume = false;
2740 }
2741 }
2742
2743 // Convert volumes from 8.24 to 4.12 format
2744 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2745 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2746 leftVol = (uint16_t)v_clamped;
2747 v_clamped = (vr + (1 << 11)) >> 12;
2748 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2749 rightVol = (uint16_t)v_clamped;
2750 } else {
2751 leftVol = mLeftVolShort;
2752 rightVol = mRightVolShort;
2753 rampVolume = false;
2754 }
2755
2756 // reset retry count
2757 track->mRetryCount = kMaxTrackRetriesDirect;
2758 activeTrack = t;
2759 mixerStatus = MIXER_TRACKS_READY;
2760 } else {
2761 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2762 if (track->isStopped()) {
2763 track->reset();
2764 }
2765 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2766 // We have consumed all the buffers of this track.
2767 // Remove it from the list of active tracks.
2768 trackToRemove = track;
2769 } else {
2770 // No buffers for this track. Give it a few chances to
2771 // fill a buffer, then remove it from active list.
2772 if (--(track->mRetryCount) <= 0) {
2773 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2774 trackToRemove = track;
2775 } else {
2776 mixerStatus = MIXER_TRACKS_ENABLED;
2777 }
2778 }
2779 }
2780 }
2781
2782 // remove all the tracks that need to be...
2783 if (UNLIKELY(trackToRemove != 0)) {
2784 mActiveTracks.remove(trackToRemove);
2785 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002786 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2787 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002788 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002789 }
2790 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002791 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002792 }
2793 }
2794
Eric Laurentde070132010-07-13 04:45:46 -07002795 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002796 }
2797
2798 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2799 AudioBufferProvider::Buffer buffer;
2800 size_t frameCount = mFrameCount;
2801 curBuf = (int8_t *)mMixBuffer;
2802 // output audio to hardware
2803 while (frameCount) {
2804 buffer.frameCount = frameCount;
Mike J. Chen535235c2011-08-15 13:28:26 -07002805 activeTrack->getNextBuffer(&buffer,
2806 AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002807 if (UNLIKELY(buffer.raw == 0)) {
2808 memset(curBuf, 0, frameCount * mFrameSize);
2809 break;
2810 }
2811 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2812 frameCount -= buffer.frameCount;
2813 curBuf += buffer.frameCount * mFrameSize;
2814 activeTrack->releaseBuffer(&buffer);
2815 }
2816 sleepTime = 0;
2817 standbyTime = systemTime() + standbyDelay;
2818 } else {
2819 if (sleepTime == 0) {
2820 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2821 sleepTime = activeSleepTime;
2822 } else {
2823 sleepTime = idleSleepTime;
2824 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002825 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2827 sleepTime = 0;
2828 }
2829 }
2830
2831 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002832 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833 }
2834 // sleepTime == 0 means we must write to audio hardware
2835 if (sleepTime == 0) {
2836 if (mixerStatus == MIXER_TRACKS_READY) {
2837 applyVolume(leftVol, rightVol, rampVolume);
2838 }
2839 for (size_t i = 0; i < effectChains.size(); i ++) {
2840 effectChains[i]->process_l();
2841 }
Eric Laurentde070132010-07-13 04:45:46 -07002842 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002843
2844 mLastWriteTime = systemTime();
2845 mInWrite = true;
2846 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002847 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002848 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2849 mNumWrites++;
2850 mInWrite = false;
2851 mStandby = false;
2852 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002853 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002854 usleep(sleepTime);
2855 }
2856
2857 // finally let go of removed track, without the lock held
2858 // since we can't guarantee the destructors won't acquire that
2859 // same lock.
2860 trackToRemove.clear();
2861 activeTrack.clear();
2862
2863 // Effect chains will be actually deleted here if they were removed from
2864 // mEffectChains list during mixing or effects processing
2865 effectChains.clear();
2866 }
2867
2868 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002869 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002870 }
2871
Eric Laurentfeb0db62011-07-22 09:04:31 -07002872 releaseWakeLock();
2873
Mathias Agopian65ab4712010-07-14 17:59:35 -07002874 LOGV("DirectOutputThread %p exiting", this);
2875 return false;
2876}
2877
2878// getTrackName_l() must be called with ThreadBase::mLock held
2879int AudioFlinger::DirectOutputThread::getTrackName_l()
2880{
2881 return 0;
2882}
2883
2884// deleteTrackName_l() must be called with ThreadBase::mLock held
2885void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2886{
2887}
2888
2889// checkForNewParameters_l() must be called with ThreadBase::mLock held
2890bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2891{
2892 bool reconfig = false;
2893
2894 while (!mNewParameters.isEmpty()) {
2895 status_t status = NO_ERROR;
2896 String8 keyValuePair = mNewParameters[0];
2897 AudioParameter param = AudioParameter(keyValuePair);
2898 int value;
2899
2900 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2901 // do not accept frame count changes if tracks are open as the track buffer
2902 // size depends on frame count and correct behavior would not be garantied
2903 // if frame count is changed after track creation
2904 if (!mTracks.isEmpty()) {
2905 status = INVALID_OPERATION;
2906 } else {
2907 reconfig = true;
2908 }
2909 }
2910 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002911 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002912 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002913 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002914 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002915 mStandby = true;
2916 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002917 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002918 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 }
2920 if (status == NO_ERROR && reconfig) {
2921 readOutputParameters();
2922 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2923 }
2924 }
2925
2926 mNewParameters.removeAt(0);
2927
2928 mParamStatus = status;
2929 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002930 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2931 // already timed out waiting for the status and will never signal the condition.
2932 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002933 }
2934 return reconfig;
2935}
2936
2937uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2938{
2939 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002940 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002941 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002942 } else {
2943 time = 10000;
2944 }
2945 return time;
2946}
2947
2948uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2949{
2950 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002951 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002952 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002953 } else {
2954 time = 10000;
2955 }
2956 return time;
2957}
2958
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002959uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2960{
2961 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002962 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002963 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2964 } else {
2965 time = 10000;
2966 }
2967 return time;
2968}
2969
2970
Mathias Agopian65ab4712010-07-14 17:59:35 -07002971// ----------------------------------------------------------------------------
2972
2973AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2974 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2975{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002976 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002977 addOutputTrack(mainThread);
2978}
2979
2980AudioFlinger::DuplicatingThread::~DuplicatingThread()
2981{
2982 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2983 mOutputTracks[i]->destroy();
2984 }
2985 mOutputTracks.clear();
2986}
2987
2988bool AudioFlinger::DuplicatingThread::threadLoop()
2989{
2990 Vector< sp<Track> > tracksToRemove;
2991 uint32_t mixerStatus = MIXER_IDLE;
2992 nsecs_t standbyTime = systemTime();
2993 size_t mixBufferSize = mFrameCount*mFrameSize;
2994 SortedVector< sp<OutputTrack> > outputTracks;
2995 uint32_t writeFrames = 0;
2996 uint32_t activeSleepTime = activeSleepTimeUs();
2997 uint32_t idleSleepTime = idleSleepTimeUs();
2998 uint32_t sleepTime = idleSleepTime;
2999 Vector< sp<EffectChain> > effectChains;
3000
Eric Laurentfeb0db62011-07-22 09:04:31 -07003001 acquireWakeLock();
3002
Mathias Agopian65ab4712010-07-14 17:59:35 -07003003 while (!exitPending())
3004 {
3005 processConfigEvents();
3006
3007 mixerStatus = MIXER_IDLE;
3008 { // scope for the mLock
3009
3010 Mutex::Autolock _l(mLock);
3011
3012 if (checkForNewParameters_l()) {
3013 mixBufferSize = mFrameCount*mFrameSize;
3014 updateWaitTime();
3015 activeSleepTime = activeSleepTimeUs();
3016 idleSleepTime = idleSleepTimeUs();
3017 }
3018
3019 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
3020
3021 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3022 outputTracks.add(mOutputTracks[i]);
3023 }
3024
3025 // put audio hardware into standby after short delay
3026 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3027 mSuspended) {
3028 if (!mStandby) {
3029 for (size_t i = 0; i < outputTracks.size(); i++) {
3030 outputTracks[i]->stop();
3031 }
3032 mStandby = true;
3033 mBytesWritten = 0;
3034 }
3035
3036 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3037 // we're about to wait, flush the binder command buffer
3038 IPCThreadState::self()->flushCommands();
3039 outputTracks.clear();
3040
3041 if (exitPending()) break;
3042
Eric Laurentfeb0db62011-07-22 09:04:31 -07003043 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003044 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
3045 mWaitWorkCV.wait(mLock);
3046 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003047 acquireWakeLock_l();
3048
Mathias Agopian65ab4712010-07-14 17:59:35 -07003049 if (mMasterMute == false) {
3050 char value[PROPERTY_VALUE_MAX];
3051 property_get("ro.audio.silent", value, "0");
3052 if (atoi(value)) {
3053 LOGD("Silence is golden");
3054 setMasterMute(true);
3055 }
3056 }
3057
3058 standbyTime = systemTime() + kStandbyTimeInNsecs;
3059 sleepTime = idleSleepTime;
3060 continue;
3061 }
3062 }
3063
3064 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3065
3066 // prevent any changes in effect chain list and in each effect chain
3067 // during mixing and effect process as the audio buffers could be deleted
3068 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003069 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 }
3071
3072 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3073 // mix buffers...
3074 if (outputsReady(outputTracks)) {
Mike J. Chen535235c2011-08-15 13:28:26 -07003075 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003076 } else {
3077 memset(mMixBuffer, 0, mixBufferSize);
3078 }
3079 sleepTime = 0;
3080 writeFrames = mFrameCount;
3081 } else {
3082 if (sleepTime == 0) {
3083 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3084 sleepTime = activeSleepTime;
3085 } else {
3086 sleepTime = idleSleepTime;
3087 }
3088 } else if (mBytesWritten != 0) {
3089 // flush remaining overflow buffers in output tracks
3090 for (size_t i = 0; i < outputTracks.size(); i++) {
3091 if (outputTracks[i]->isActive()) {
3092 sleepTime = 0;
3093 writeFrames = 0;
3094 memset(mMixBuffer, 0, mixBufferSize);
3095 break;
3096 }
3097 }
3098 }
3099 }
3100
3101 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003102 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003103 }
3104 // sleepTime == 0 means we must write to audio hardware
3105 if (sleepTime == 0) {
3106 for (size_t i = 0; i < effectChains.size(); i ++) {
3107 effectChains[i]->process_l();
3108 }
3109 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003110 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003111
3112 standbyTime = systemTime() + kStandbyTimeInNsecs;
3113 for (size_t i = 0; i < outputTracks.size(); i++) {
3114 outputTracks[i]->write(mMixBuffer, writeFrames);
3115 }
3116 mStandby = false;
3117 mBytesWritten += mixBufferSize;
3118 } else {
3119 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003120 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003121 usleep(sleepTime);
3122 }
3123
3124 // finally let go of all our tracks, without the lock held
3125 // since we can't guarantee the destructors won't acquire that
3126 // same lock.
3127 tracksToRemove.clear();
3128 outputTracks.clear();
3129
3130 // Effect chains will be actually deleted here if they were removed from
3131 // mEffectChains list during mixing or effects processing
3132 effectChains.clear();
3133 }
3134
Eric Laurentfeb0db62011-07-22 09:04:31 -07003135 releaseWakeLock();
3136
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137 return false;
3138}
3139
3140void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3141{
3142 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3143 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3144 this,
3145 mSampleRate,
3146 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003147 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003148 frameCount);
3149 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003150 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003151 mOutputTracks.add(outputTrack);
3152 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3153 updateWaitTime();
3154 }
3155}
3156
3157void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3158{
3159 Mutex::Autolock _l(mLock);
3160 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3161 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3162 mOutputTracks[i]->destroy();
3163 mOutputTracks.removeAt(i);
3164 updateWaitTime();
3165 return;
3166 }
3167 }
3168 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3169}
3170
3171void AudioFlinger::DuplicatingThread::updateWaitTime()
3172{
3173 mWaitTimeMs = UINT_MAX;
3174 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3175 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3176 if (strong != NULL) {
3177 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3178 if (waitTimeMs < mWaitTimeMs) {
3179 mWaitTimeMs = waitTimeMs;
3180 }
3181 }
3182 }
3183}
3184
3185
3186bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3187{
3188 for (size_t i = 0; i < outputTracks.size(); i++) {
3189 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3190 if (thread == 0) {
3191 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3192 return false;
3193 }
3194 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3195 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3196 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3197 return false;
3198 }
3199 }
3200 return true;
3201}
3202
3203uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3204{
3205 return (mWaitTimeMs * 1000) / 2;
3206}
3207
3208// ----------------------------------------------------------------------------
3209
3210// TrackBase constructor must be called with AudioFlinger::mLock held
3211AudioFlinger::ThreadBase::TrackBase::TrackBase(
3212 const wp<ThreadBase>& thread,
3213 const sp<Client>& client,
3214 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003215 uint32_t format,
3216 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003217 int frameCount,
3218 uint32_t flags,
3219 const sp<IMemory>& sharedBuffer,
3220 int sessionId)
3221 : RefBase(),
3222 mThread(thread),
3223 mClient(client),
3224 mCblk(0),
3225 mFrameCount(0),
3226 mState(IDLE),
3227 mClientTid(-1),
3228 mFormat(format),
3229 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3230 mSessionId(sessionId)
3231{
3232 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3233
3234 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3235 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003236 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003237 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3238 if (sharedBuffer == 0) {
3239 size += bufferSize;
3240 }
3241
3242 if (client != NULL) {
3243 mCblkMemory = client->heap()->allocate(size);
3244 if (mCblkMemory != 0) {
3245 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3246 if (mCblk) { // construct the shared structure in-place.
3247 new(mCblk) audio_track_cblk_t();
3248 // clear all buffers
3249 mCblk->frameCount = frameCount;
3250 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003251 mChannelCount = channelCount;
3252 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003253 if (sharedBuffer == 0) {
3254 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3255 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3256 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003257 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003258 mCblk->flags = CBLK_UNDERRUN_ON;
3259 } else {
3260 mBuffer = sharedBuffer->pointer();
3261 }
3262 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3263 }
3264 } else {
3265 LOGE("not enough memory for AudioTrack size=%u", size);
3266 client->heap()->dump("AudioTrack");
3267 return;
3268 }
3269 } else {
3270 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3271 if (mCblk) { // construct the shared structure in-place.
3272 new(mCblk) audio_track_cblk_t();
3273 // clear all buffers
3274 mCblk->frameCount = frameCount;
3275 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003276 mChannelCount = channelCount;
3277 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003278 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3279 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3280 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003281 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003282 mCblk->flags = CBLK_UNDERRUN_ON;
3283 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3284 }
3285 }
3286}
3287
3288AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3289{
3290 if (mCblk) {
3291 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3292 if (mClient == NULL) {
3293 delete mCblk;
3294 }
3295 }
3296 mCblkMemory.clear(); // and free the shared memory
3297 if (mClient != NULL) {
3298 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3299 mClient.clear();
3300 }
3301}
3302
3303void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3304{
3305 buffer->raw = 0;
3306 mFrameCount = buffer->frameCount;
3307 step();
3308 buffer->frameCount = 0;
3309}
3310
3311bool AudioFlinger::ThreadBase::TrackBase::step() {
3312 bool result;
3313 audio_track_cblk_t* cblk = this->cblk();
3314
3315 result = cblk->stepServer(mFrameCount);
3316 if (!result) {
3317 LOGV("stepServer failed acquiring cblk mutex");
3318 mFlags |= STEPSERVER_FAILED;
3319 }
3320 return result;
3321}
3322
3323void AudioFlinger::ThreadBase::TrackBase::reset() {
3324 audio_track_cblk_t* cblk = this->cblk();
3325
3326 cblk->user = 0;
3327 cblk->server = 0;
3328 cblk->userBase = 0;
3329 cblk->serverBase = 0;
3330 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3331 LOGV("TrackBase::reset");
3332}
3333
3334sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3335{
3336 return mCblkMemory;
3337}
3338
3339int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3340 return (int)mCblk->sampleRate;
3341}
3342
3343int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003344 return (const int)mChannelCount;
3345}
3346
3347uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3348 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349}
3350
3351void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3352 audio_track_cblk_t* cblk = this->cblk();
3353 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3354 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3355
3356 // Check validity of returned pointer in case the track control block would have been corrupted.
3357 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3358 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3359 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 -07003360 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003362 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003363 return 0;
3364 }
3365
3366 return bufferStart;
3367}
3368
3369// ----------------------------------------------------------------------------
3370
3371// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3372AudioFlinger::PlaybackThread::Track::Track(
3373 const wp<ThreadBase>& thread,
3374 const sp<Client>& client,
3375 int streamType,
3376 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003377 uint32_t format,
3378 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003379 int frameCount,
3380 const sp<IMemory>& sharedBuffer,
3381 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003382 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003383 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3384 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003385{
3386 if (mCblk != NULL) {
3387 sp<ThreadBase> baseThread = thread.promote();
3388 if (baseThread != 0) {
3389 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3390 mName = playbackThread->getTrackName_l();
3391 mMainBuffer = playbackThread->mixBuffer();
3392 }
3393 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3394 if (mName < 0) {
3395 LOGE("no more track names available");
3396 }
3397 mVolume[0] = 1.0f;
3398 mVolume[1] = 1.0f;
3399 mStreamType = streamType;
3400 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3401 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003402 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003403 }
3404}
3405
3406AudioFlinger::PlaybackThread::Track::~Track()
3407{
3408 LOGV("PlaybackThread::Track destructor");
3409 sp<ThreadBase> thread = mThread.promote();
3410 if (thread != 0) {
3411 Mutex::Autolock _l(thread->mLock);
3412 mState = TERMINATED;
3413 }
3414}
3415
3416void AudioFlinger::PlaybackThread::Track::destroy()
3417{
3418 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3419 // by removing it from mTracks vector, so there is a risk that this Tracks's
3420 // desctructor is called. As the destructor needs to lock mLock,
3421 // we must acquire a strong reference on this Track before locking mLock
3422 // here so that the destructor is called only when exiting this function.
3423 // On the other hand, as long as Track::destroy() is only called by
3424 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3425 // this Track with its member mTrack.
3426 sp<Track> keep(this);
3427 { // scope for mLock
3428 sp<ThreadBase> thread = mThread.promote();
3429 if (thread != 0) {
3430 if (!isOutputTrack()) {
3431 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003432 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003433 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003434 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003435
3436 // to track the speaker usage
3437 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003438 }
3439 AudioSystem::releaseOutput(thread->id());
3440 }
3441 Mutex::Autolock _l(thread->mLock);
3442 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3443 playbackThread->destroyTrack_l(this);
3444 }
3445 }
3446}
3447
3448void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3449{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003450 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 -07003451 mName - AudioMixer::TRACK0,
3452 (mClient == NULL) ? getpid() : mClient->pid(),
3453 mStreamType,
3454 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003455 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003456 mSessionId,
3457 mFrameCount,
3458 mState,
3459 mMute,
3460 mFillingUpStatus,
3461 mCblk->sampleRate,
3462 mCblk->volume[0],
3463 mCblk->volume[1],
3464 mCblk->server,
3465 mCblk->user,
3466 (int)mMainBuffer,
3467 (int)mAuxBuffer);
3468}
3469
Mike J. Chen535235c2011-08-15 13:28:26 -07003470status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3471 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003472{
3473 audio_track_cblk_t* cblk = this->cblk();
3474 uint32_t framesReady;
3475 uint32_t framesReq = buffer->frameCount;
3476
3477 // Check if last stepServer failed, try to step now
3478 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3479 if (!step()) goto getNextBuffer_exit;
3480 LOGV("stepServer recovered");
3481 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3482 }
3483
3484 framesReady = cblk->framesReady();
3485
3486 if (LIKELY(framesReady)) {
3487 uint32_t s = cblk->server;
3488 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3489
3490 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3491 if (framesReq > framesReady) {
3492 framesReq = framesReady;
3493 }
3494 if (s + framesReq > bufferEnd) {
3495 framesReq = bufferEnd - s;
3496 }
3497
3498 buffer->raw = getBuffer(s, framesReq);
3499 if (buffer->raw == 0) goto getNextBuffer_exit;
3500
3501 buffer->frameCount = framesReq;
3502 return NO_ERROR;
3503 }
3504
3505getNextBuffer_exit:
3506 buffer->raw = 0;
3507 buffer->frameCount = 0;
3508 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3509 return NOT_ENOUGH_DATA;
3510}
3511
Mike J. Chen535235c2011-08-15 13:28:26 -07003512uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3513 return mCblk->framesReady();
3514}
3515
Mathias Agopian65ab4712010-07-14 17:59:35 -07003516bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003517 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003518
Mike J. Chen535235c2011-08-15 13:28:26 -07003519 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3521 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003522 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003523 return true;
3524 }
3525 return false;
3526}
3527
3528status_t AudioFlinger::PlaybackThread::Track::start()
3529{
3530 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003531 LOGV("start(%d), calling thread %d session %d",
3532 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003533 sp<ThreadBase> thread = mThread.promote();
3534 if (thread != 0) {
3535 Mutex::Autolock _l(thread->mLock);
3536 int state = mState;
3537 // here the track could be either new, or restarted
3538 // in both cases "unstop" the track
3539 if (mState == PAUSED) {
3540 mState = TrackBase::RESUMING;
3541 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3542 } else {
3543 mState = TrackBase::ACTIVE;
3544 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3545 }
3546
3547 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3548 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003549 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003550 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003551 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003552 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003553
3554 // to track the speaker usage
3555 if (status == NO_ERROR) {
3556 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3557 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 }
3559 if (status == NO_ERROR) {
3560 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3561 playbackThread->addTrack_l(this);
3562 } else {
3563 mState = state;
3564 }
3565 } else {
3566 status = BAD_VALUE;
3567 }
3568 return status;
3569}
3570
3571void AudioFlinger::PlaybackThread::Track::stop()
3572{
3573 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3574 sp<ThreadBase> thread = mThread.promote();
3575 if (thread != 0) {
3576 Mutex::Autolock _l(thread->mLock);
3577 int state = mState;
3578 if (mState > STOPPED) {
3579 mState = STOPPED;
3580 // If the track is not active (PAUSED and buffers full), flush buffers
3581 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3582 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3583 reset();
3584 }
3585 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3586 }
3587 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3588 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003589 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003590 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003591 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003593
3594 // to track the speaker usage
3595 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003596 }
3597 }
3598}
3599
3600void AudioFlinger::PlaybackThread::Track::pause()
3601{
3602 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3603 sp<ThreadBase> thread = mThread.promote();
3604 if (thread != 0) {
3605 Mutex::Autolock _l(thread->mLock);
3606 if (mState == ACTIVE || mState == RESUMING) {
3607 mState = PAUSING;
3608 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3609 if (!isOutputTrack()) {
3610 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003611 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003612 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003613 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003615
3616 // to track the speaker usage
3617 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 }
3619 }
3620 }
3621}
3622
3623void AudioFlinger::PlaybackThread::Track::flush()
3624{
3625 LOGV("flush(%d)", mName);
3626 sp<ThreadBase> thread = mThread.promote();
3627 if (thread != 0) {
3628 Mutex::Autolock _l(thread->mLock);
3629 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3630 return;
3631 }
3632 // No point remaining in PAUSED state after a flush => go to
3633 // STOPPED state
3634 mState = STOPPED;
3635
Eric Laurent38ccae22011-03-28 18:37:07 -07003636 // do not reset the track if it is still in the process of being stopped or paused.
3637 // this will be done by prepareTracks_l() when the track is stopped.
3638 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3639 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3640 reset();
3641 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003642 }
3643}
3644
3645void AudioFlinger::PlaybackThread::Track::reset()
3646{
3647 // Do not reset twice to avoid discarding data written just after a flush and before
3648 // the audioflinger thread detects the track is stopped.
3649 if (!mResetDone) {
3650 TrackBase::reset();
3651 // Force underrun condition to avoid false underrun callback until first data is
3652 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003653 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3654 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003655 mFillingUpStatus = FS_FILLING;
3656 mResetDone = true;
3657 }
3658}
3659
3660void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3661{
3662 mMute = muted;
3663}
3664
3665void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3666{
3667 mVolume[0] = left;
3668 mVolume[1] = right;
3669}
3670
3671status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3672{
3673 status_t status = DEAD_OBJECT;
3674 sp<ThreadBase> thread = mThread.promote();
3675 if (thread != 0) {
3676 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3677 status = playbackThread->attachAuxEffect(this, EffectId);
3678 }
3679 return status;
3680}
3681
3682void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3683{
3684 mAuxEffectId = EffectId;
3685 mAuxBuffer = buffer;
3686}
3687
Mike J. Chen535235c2011-08-15 13:28:26 -07003688// timed audio tracks
3689
3690sp<AudioFlinger::PlaybackThread::TimedTrack>
3691AudioFlinger::PlaybackThread::TimedTrack::create(
3692 const wp<ThreadBase>& thread,
3693 const sp<Client>& client,
3694 int streamType,
3695 uint32_t sampleRate,
3696 uint32_t format,
3697 uint32_t channelMask,
3698 int frameCount,
3699 const sp<IMemory>& sharedBuffer,
3700 int sessionId) {
3701 if (!client->reserveTimedTrack())
3702 return NULL;
3703
3704 sp<TimedTrack> track = new TimedTrack(
3705 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3706 sharedBuffer, sessionId);
3707
3708 if (track == NULL) {
3709 client->releaseTimedTrack();
3710 return NULL;
3711 }
3712
3713 return track;
3714}
3715
3716AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
3717 const wp<ThreadBase>& thread,
3718 const sp<Client>& client,
3719 int streamType,
3720 uint32_t sampleRate,
3721 uint32_t format,
3722 uint32_t channelMask,
3723 int frameCount,
3724 const sp<IMemory>& sharedBuffer,
3725 int sessionId)
3726 : Track(thread, client, streamType, sampleRate, format, channelMask,
3727 frameCount, sharedBuffer, sessionId),
3728 mTimedSilenceBuffer(NULL),
3729 mTimedSilenceBufferSize(0),
3730 mTimedAudioOutputOnTime(false),
3731 mMediaTimeTransformValid(false)
3732{
3733 LocalClock lc;
3734 mLocalTimeFreq = lc.getLocalFreq();
3735
3736 mLocalTimeToSampleTransform.a_zero = 0;
3737 mLocalTimeToSampleTransform.b_zero = 0;
3738 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3739 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3740 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3741 &mLocalTimeToSampleTransform.a_to_b_denom);
3742}
3743
3744AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3745 mClient->releaseTimedTrack();
3746 delete [] mTimedSilenceBuffer;
3747}
3748
3749status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3750 size_t size, sp<IMemory>* buffer) {
3751
3752 Mutex::Autolock _l(mTimedBufferQueueLock);
3753
3754 trimTimedBufferQueue_l();
3755
3756 // lazily initialize the shared memory heap for timed buffers
3757 if (mTimedMemoryDealer == NULL) {
3758 const int kTimedBufferHeapSize = 512 << 10;
3759
3760 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3761 "AudioFlingerTimed");
3762 if (mTimedMemoryDealer == NULL)
3763 return NO_MEMORY;
3764 }
3765
3766 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3767 if (newBuffer == NULL) {
3768 newBuffer = mTimedMemoryDealer->allocate(size);
3769 if (newBuffer == NULL)
3770 return NO_MEMORY;
3771 }
3772
3773 *buffer = newBuffer;
3774 return NO_ERROR;
3775}
3776
3777// caller must hold mTimedBufferQueueLock
3778void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3779 int64_t mediaTimeNow;
3780 {
3781 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3782 if (!mMediaTimeTransformValid)
3783 return;
3784
3785 int64_t targetTimeNow;
3786 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3787 ? CCHelper::getCommonTime(&targetTimeNow)
3788 : CCHelper::getLocalTime(&targetTimeNow);
3789
3790 if (OK != res)
3791 return;
3792
3793 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3794 &mediaTimeNow)) {
3795 return;
3796 }
3797 }
3798
3799 size_t trimIndex;
3800 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3801 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3802 break;
3803 }
3804
3805 if (trimIndex) {
3806 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3807 }
3808}
3809
3810status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3811 const sp<IMemory>& buffer, int64_t pts) {
3812
3813 {
3814 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3815 if (!mMediaTimeTransformValid)
3816 return INVALID_OPERATION;
3817 }
3818
3819 Mutex::Autolock _l(mTimedBufferQueueLock);
3820
3821 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3822
3823 return NO_ERROR;
3824}
3825
3826status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3827 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3828
3829 LOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3830 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3831 target);
3832
3833 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3834 target == TimedAudioTrack::COMMON_TIME)) {
3835 return BAD_VALUE;
3836 }
3837
3838 Mutex::Autolock lock(mMediaTimeTransformLock);
3839 mMediaTimeTransform = xform;
3840 mMediaTimeTransformTarget = target;
3841 mMediaTimeTransformValid = true;
3842
3843 return NO_ERROR;
3844}
3845
3846#define min(a, b) ((a) < (b) ? (a) : (b))
3847
3848// implementation of getNextBuffer for tracks whose buffers have timestamps
3849status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3850 AudioBufferProvider::Buffer* buffer, int64_t pts)
3851{
3852 if (pts == AudioBufferProvider::kInvalidPTS) {
3853 buffer->raw = 0;
3854 buffer->frameCount = 0;
3855 return INVALID_OPERATION;
3856 }
3857
3858 // get ahold of the output stream that these samples will be written to
3859 sp<ThreadBase> thread = mThread.promote();
3860 if (thread == NULL) {
3861 buffer->raw = 0;
3862 buffer->frameCount = 0;
3863 return INVALID_OPERATION;
3864 }
3865 PlaybackThread* playbackThread = static_cast<PlaybackThread*>(thread.get());
3866
3867 Mutex::Autolock _l(mTimedBufferQueueLock);
3868
3869 while (true) {
3870
3871 // if we have no timed buffers, then fail
3872 if (mTimedBufferQueue.isEmpty()) {
3873 buffer->raw = 0;
3874 buffer->frameCount = 0;
3875 return NOT_ENOUGH_DATA;
3876 }
3877
3878 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3879
3880 // calculate the PTS of the head of the timed buffer queue expressed in
3881 // local time
3882 int64_t headLocalPTS;
3883 {
3884 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3885
3886 assert(mMediaTimeTransformValid);
3887
3888 if (mMediaTimeTransform.a_to_b_denom == 0) {
3889 // the transform represents a pause, so yield silence
3890 timedYieldSilence(buffer->frameCount, buffer);
3891 return NO_ERROR;
3892 }
3893
3894 int64_t transformedPTS;
3895 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3896 &transformedPTS)) {
3897 // the transform failed. this shouldn't happen, but if it does
3898 // then just drop this buffer
3899 LOGW("timedGetNextBuffer transform failed");
3900 buffer->raw = 0;
3901 buffer->frameCount = 0;
3902 mTimedBufferQueue.removeAt(0);
3903 return NO_ERROR;
3904 }
3905
3906 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3907 if (OK != CCHelper::commonTimeToLocalTime(transformedPTS,
3908 &headLocalPTS)) {
3909 buffer->raw = 0;
3910 buffer->frameCount = 0;
3911 return INVALID_OPERATION;
3912 }
3913 } else {
3914 headLocalPTS = transformedPTS;
3915 }
3916 }
3917
3918 // adjust the head buffer's PTS to reflect the portion of the head buffer
3919 // that has already been consumed
3920 int64_t effectivePTS = headLocalPTS +
3921 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3922
3923 // Calculate the delta in samples between the head of the input buffer
3924 // queue and the start of the next output buffer that will be written.
3925 // If the transformation fails because of over or underflow, it means
3926 // that the sample's position in the output stream is so far out of
3927 // whack that it should just be dropped.
3928 int64_t sampleDelta;
3929 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3930 LOGV("*** head buffer is too far from PTS: dropped buffer");
3931 mTimedBufferQueue.removeAt(0);
3932 continue;
3933 }
3934 if (!mLocalTimeToSampleTransform.doForwardTransform(
3935 (effectivePTS - pts) << 32, &sampleDelta)) {
3936 LOGV("*** too late during sample rate transform: dropped buffer");
3937 mTimedBufferQueue.removeAt(0);
3938 continue;
3939 }
3940
3941 LOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3942 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3943 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3944 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3945
3946 // if the delta between the ideal placement for the next input sample and
3947 // the current output position is within this threshold, then we will
3948 // concatenate the next input samples to the previous output
3949 const int64_t kSampleContinuityThreshold =
3950 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3951
3952 // if this is the first buffer of audio that we're emitting from this track
3953 // then it should be almost exactly on time.
3954 const int64_t kSampleStartupThreshold = 1LL << 32;
3955
3956 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3957 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3958 // the next input is close enough to being on time, so concatenate it
3959 // with the last output
3960 timedYieldSamples(buffer);
3961
3962 LOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3963 return NO_ERROR;
3964 } else if (sampleDelta > 0) {
3965 // the gap between the current output position and the proper start of
3966 // the next input sample is too big, so fill it with silence
3967 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3968
3969 timedYieldSilence(framesUntilNextInput, buffer);
3970 LOGV("*** silence: frameCount=%u", buffer->frameCount);
3971 return NO_ERROR;
3972 } else {
3973 // the next input sample is late
3974 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3975 size_t onTimeSamplePosition =
3976 head.position() + lateFrames * mCblk->frameSize;
3977
3978 if (onTimeSamplePosition > head.buffer()->size()) {
3979 // all the remaining samples in the head are too late, so
3980 // drop it and move on
3981 LOGV("*** too late: dropped buffer");
3982 mTimedBufferQueue.removeAt(0);
3983 continue;
3984 } else {
3985 // skip over the late samples
3986 head.setPosition(onTimeSamplePosition);
3987
3988 // yield the available samples
3989 timedYieldSamples(buffer);
3990
3991 LOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3992 return NO_ERROR;
3993 }
3994 }
3995 }
3996}
3997
3998// Yield samples from the timed buffer queue head up to the given output
3999// buffer's capacity.
4000//
4001// Caller must hold mTimedBufferQueueLock
4002void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
4003 AudioBufferProvider::Buffer* buffer) {
4004
4005 const TimedBuffer& head = mTimedBufferQueue[0];
4006
4007 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
4008 head.position());
4009
4010 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
4011 mCblk->frameSize);
4012 size_t framesRequested = buffer->frameCount;
4013 buffer->frameCount = min(framesLeftInHead, framesRequested);
4014
4015 mTimedAudioOutputOnTime = true;
4016}
4017
4018// Yield samples of silence up to the given output buffer's capacity
4019//
4020// Caller must hold mTimedBufferQueueLock
4021void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
4022 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4023
4024 // lazily allocate a buffer filled with silence
4025 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4026 delete [] mTimedSilenceBuffer;
4027 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4028 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4029 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4030 }
4031
4032 buffer->raw = mTimedSilenceBuffer;
4033 size_t framesRequested = buffer->frameCount;
4034 buffer->frameCount = min(numFrames, framesRequested);
4035
4036 mTimedAudioOutputOnTime = false;
4037}
4038
4039void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4040 AudioBufferProvider::Buffer* buffer) {
4041
4042 Mutex::Autolock _l(mTimedBufferQueueLock);
4043
4044 if (buffer->raw != mTimedSilenceBuffer) {
4045 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4046 head.setPosition(head.position() + buffer->frameCount * mCblk->frameSize);
4047 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4048 mTimedBufferQueue.removeAt(0);
4049 }
4050 }
4051
4052 buffer->raw = 0;
4053 buffer->frameCount = 0;
4054}
4055
4056uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4057 Mutex::Autolock _l(mTimedBufferQueueLock);
4058
4059 uint32_t frames = 0;
4060 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4061 const TimedBuffer& tb = mTimedBufferQueue[i];
4062 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4063 }
4064
4065 return frames;
4066}
4067
4068AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4069 : mPTS(0), mPosition(0) {}
4070
4071AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4072 const sp<IMemory>& buffer, int64_t pts)
4073 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4074
Mathias Agopian65ab4712010-07-14 17:59:35 -07004075// ----------------------------------------------------------------------------
4076
4077// RecordTrack constructor must be called with AudioFlinger::mLock held
4078AudioFlinger::RecordThread::RecordTrack::RecordTrack(
4079 const wp<ThreadBase>& thread,
4080 const sp<Client>& client,
4081 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004082 uint32_t format,
4083 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084 int frameCount,
4085 uint32_t flags,
4086 int sessionId)
4087 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004088 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 mOverflow(false)
4090{
4091 if (mCblk != NULL) {
4092 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004093 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004094 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004095 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004096 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004097 } else {
4098 mCblk->frameSize = sizeof(int8_t);
4099 }
4100 }
4101}
4102
4103AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4104{
4105 sp<ThreadBase> thread = mThread.promote();
4106 if (thread != 0) {
4107 AudioSystem::releaseInput(thread->id());
4108 }
4109}
4110
Mike J. Chen535235c2011-08-15 13:28:26 -07004111status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112{
4113 audio_track_cblk_t* cblk = this->cblk();
4114 uint32_t framesAvail;
4115 uint32_t framesReq = buffer->frameCount;
4116
4117 // Check if last stepServer failed, try to step now
4118 if (mFlags & TrackBase::STEPSERVER_FAILED) {
4119 if (!step()) goto getNextBuffer_exit;
4120 LOGV("stepServer recovered");
4121 mFlags &= ~TrackBase::STEPSERVER_FAILED;
4122 }
4123
4124 framesAvail = cblk->framesAvailable_l();
4125
4126 if (LIKELY(framesAvail)) {
4127 uint32_t s = cblk->server;
4128 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4129
4130 if (framesReq > framesAvail) {
4131 framesReq = framesAvail;
4132 }
4133 if (s + framesReq > bufferEnd) {
4134 framesReq = bufferEnd - s;
4135 }
4136
4137 buffer->raw = getBuffer(s, framesReq);
4138 if (buffer->raw == 0) goto getNextBuffer_exit;
4139
4140 buffer->frameCount = framesReq;
4141 return NO_ERROR;
4142 }
4143
4144getNextBuffer_exit:
4145 buffer->raw = 0;
4146 buffer->frameCount = 0;
4147 return NOT_ENOUGH_DATA;
4148}
4149
4150status_t AudioFlinger::RecordThread::RecordTrack::start()
4151{
4152 sp<ThreadBase> thread = mThread.promote();
4153 if (thread != 0) {
4154 RecordThread *recordThread = (RecordThread *)thread.get();
4155 return recordThread->start(this);
4156 } else {
4157 return BAD_VALUE;
4158 }
4159}
4160
4161void AudioFlinger::RecordThread::RecordTrack::stop()
4162{
4163 sp<ThreadBase> thread = mThread.promote();
4164 if (thread != 0) {
4165 RecordThread *recordThread = (RecordThread *)thread.get();
4166 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004167 TrackBase::reset();
4168 // Force overerrun condition to avoid false overrun callback until first data is
4169 // read from buffer
4170 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 }
4172}
4173
4174void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4175{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004176 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004177 (mClient == NULL) ? getpid() : mClient->pid(),
4178 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004179 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 mSessionId,
4181 mFrameCount,
4182 mState,
4183 mCblk->sampleRate,
4184 mCblk->server,
4185 mCblk->user);
4186}
4187
4188
4189// ----------------------------------------------------------------------------
4190
4191AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
4192 const wp<ThreadBase>& thread,
4193 DuplicatingThread *sourceThread,
4194 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004195 uint32_t format,
4196 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004197 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004198 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004199 mActive(false), mSourceThread(sourceThread)
4200{
4201
4202 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
4203 if (mCblk != NULL) {
4204 mCblk->flags |= CBLK_DIRECTION_OUT;
4205 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
4206 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
4207 mOutBuffer.frameCount = 0;
4208 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004209 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
4210 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4211 mCblk, mBuffer, mCblk->buffers,
4212 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213 } else {
4214 LOGW("Error creating output track on thread %p", playbackThread);
4215 }
4216}
4217
4218AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4219{
4220 clearBufferQueue();
4221}
4222
4223status_t AudioFlinger::PlaybackThread::OutputTrack::start()
4224{
4225 status_t status = Track::start();
4226 if (status != NO_ERROR) {
4227 return status;
4228 }
4229
4230 mActive = true;
4231 mRetryCount = 127;
4232 return status;
4233}
4234
4235void AudioFlinger::PlaybackThread::OutputTrack::stop()
4236{
4237 Track::stop();
4238 clearBufferQueue();
4239 mOutBuffer.frameCount = 0;
4240 mActive = false;
4241}
4242
4243bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4244{
4245 Buffer *pInBuffer;
4246 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004247 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004248 bool outputBufferFull = false;
4249 inBuffer.frameCount = frames;
4250 inBuffer.i16 = data;
4251
4252 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4253
4254 if (!mActive && frames != 0) {
4255 start();
4256 sp<ThreadBase> thread = mThread.promote();
4257 if (thread != 0) {
4258 MixerThread *mixerThread = (MixerThread *)thread.get();
4259 if (mCblk->frameCount > frames){
4260 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4261 uint32_t startFrames = (mCblk->frameCount - frames);
4262 pInBuffer = new Buffer;
4263 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4264 pInBuffer->frameCount = startFrames;
4265 pInBuffer->i16 = pInBuffer->mBuffer;
4266 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4267 mBufferQueue.add(pInBuffer);
4268 } else {
4269 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
4270 }
4271 }
4272 }
4273 }
4274
4275 while (waitTimeLeftMs) {
4276 // First write pending buffers, then new data
4277 if (mBufferQueue.size()) {
4278 pInBuffer = mBufferQueue.itemAt(0);
4279 } else {
4280 pInBuffer = &inBuffer;
4281 }
4282
4283 if (pInBuffer->frameCount == 0) {
4284 break;
4285 }
4286
4287 if (mOutBuffer.frameCount == 0) {
4288 mOutBuffer.frameCount = pInBuffer->frameCount;
4289 nsecs_t startTime = systemTime();
4290 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
4291 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
4292 outputBufferFull = true;
4293 break;
4294 }
4295 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4296 if (waitTimeLeftMs >= waitTimeMs) {
4297 waitTimeLeftMs -= waitTimeMs;
4298 } else {
4299 waitTimeLeftMs = 0;
4300 }
4301 }
4302
4303 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4304 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4305 mCblk->stepUser(outFrames);
4306 pInBuffer->frameCount -= outFrames;
4307 pInBuffer->i16 += outFrames * channelCount;
4308 mOutBuffer.frameCount -= outFrames;
4309 mOutBuffer.i16 += outFrames * channelCount;
4310
4311 if (pInBuffer->frameCount == 0) {
4312 if (mBufferQueue.size()) {
4313 mBufferQueue.removeAt(0);
4314 delete [] pInBuffer->mBuffer;
4315 delete pInBuffer;
4316 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4317 } else {
4318 break;
4319 }
4320 }
4321 }
4322
4323 // If we could not write all frames, allocate a buffer and queue it for next time.
4324 if (inBuffer.frameCount) {
4325 sp<ThreadBase> thread = mThread.promote();
4326 if (thread != 0 && !thread->standby()) {
4327 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4328 pInBuffer = new Buffer;
4329 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4330 pInBuffer->frameCount = inBuffer.frameCount;
4331 pInBuffer->i16 = pInBuffer->mBuffer;
4332 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4333 mBufferQueue.add(pInBuffer);
4334 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4335 } else {
4336 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
4337 }
4338 }
4339 }
4340
4341 // Calling write() with a 0 length buffer, means that no more data will be written:
4342 // If no more buffers are pending, fill output track buffer to make sure it is started
4343 // by output mixer.
4344 if (frames == 0 && mBufferQueue.size() == 0) {
4345 if (mCblk->user < mCblk->frameCount) {
4346 frames = mCblk->frameCount - mCblk->user;
4347 pInBuffer = new Buffer;
4348 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4349 pInBuffer->frameCount = frames;
4350 pInBuffer->i16 = pInBuffer->mBuffer;
4351 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4352 mBufferQueue.add(pInBuffer);
4353 } else if (mActive) {
4354 stop();
4355 }
4356 }
4357
4358 return outputBufferFull;
4359}
4360
4361status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4362{
4363 int active;
4364 status_t result;
4365 audio_track_cblk_t* cblk = mCblk;
4366 uint32_t framesReq = buffer->frameCount;
4367
4368// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
4369 buffer->frameCount = 0;
4370
4371 uint32_t framesAvail = cblk->framesAvailable();
4372
4373
4374 if (framesAvail == 0) {
4375 Mutex::Autolock _l(cblk->lock);
4376 goto start_loop_here;
4377 while (framesAvail == 0) {
4378 active = mActive;
4379 if (UNLIKELY(!active)) {
4380 LOGV("Not active and NO_MORE_BUFFERS");
4381 return AudioTrack::NO_MORE_BUFFERS;
4382 }
4383 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4384 if (result != NO_ERROR) {
4385 return AudioTrack::NO_MORE_BUFFERS;
4386 }
4387 // read the server count again
4388 start_loop_here:
4389 framesAvail = cblk->framesAvailable_l();
4390 }
4391 }
4392
4393// if (framesAvail < framesReq) {
4394// return AudioTrack::NO_MORE_BUFFERS;
4395// }
4396
4397 if (framesReq > framesAvail) {
4398 framesReq = framesAvail;
4399 }
4400
4401 uint32_t u = cblk->user;
4402 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4403
4404 if (u + framesReq > bufferEnd) {
4405 framesReq = bufferEnd - u;
4406 }
4407
4408 buffer->frameCount = framesReq;
4409 buffer->raw = (void *)cblk->buffer(u);
4410 return NO_ERROR;
4411}
4412
4413
4414void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4415{
4416 size_t size = mBufferQueue.size();
4417 Buffer *pBuffer;
4418
4419 for (size_t i = 0; i < size; i++) {
4420 pBuffer = mBufferQueue.itemAt(i);
4421 delete [] pBuffer->mBuffer;
4422 delete pBuffer;
4423 }
4424 mBufferQueue.clear();
4425}
4426
4427// ----------------------------------------------------------------------------
4428
4429AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4430 : RefBase(),
4431 mAudioFlinger(audioFlinger),
4432 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
Mike J. Chen535235c2011-08-15 13:28:26 -07004433 mPid(pid),
4434 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004435{
4436 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4437}
4438
4439// Client destructor must be called with AudioFlinger::mLock held
4440AudioFlinger::Client::~Client()
4441{
4442 mAudioFlinger->removeClient_l(mPid);
4443}
4444
4445const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4446{
4447 return mMemoryDealer;
4448}
4449
Mike J. Chen535235c2011-08-15 13:28:26 -07004450// Reserve one of the limited slots for a timed audio track associated
4451// with this client
4452bool AudioFlinger::Client::reserveTimedTrack()
4453{
4454 const int kMaxTimedTracksPerClient = 4;
4455
4456 Mutex::Autolock _l(mTimedTrackLock);
4457
4458 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4459 LOGW("can not create timed track - pid %d has exceeded the limit",
4460 mPid);
4461 return false;
4462 }
4463
4464 mTimedTrackCount++;
4465 return true;
4466}
4467
4468// Release a slot for a timed audio track
4469void AudioFlinger::Client::releaseTimedTrack()
4470{
4471 Mutex::Autolock _l(mTimedTrackLock);
4472 mTimedTrackCount--;
4473}
4474
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475// ----------------------------------------------------------------------------
4476
4477AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4478 const sp<IAudioFlingerClient>& client,
4479 pid_t pid)
4480 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4481{
4482}
4483
4484AudioFlinger::NotificationClient::~NotificationClient()
4485{
4486 mClient.clear();
4487}
4488
4489void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4490{
4491 sp<NotificationClient> keep(this);
4492 {
4493 mAudioFlinger->removeNotificationClient(mPid);
4494 }
4495}
4496
4497// ----------------------------------------------------------------------------
4498
4499AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4500 : BnAudioTrack(),
4501 mTrack(track)
4502{
4503}
4504
4505AudioFlinger::TrackHandle::~TrackHandle() {
4506 // just stop the track on deletion, associated resources
4507 // will be freed from the main thread once all pending buffers have
4508 // been played. Unless it's not in the active track list, in which
4509 // case we free everything now...
4510 mTrack->destroy();
4511}
4512
4513status_t AudioFlinger::TrackHandle::start() {
4514 return mTrack->start();
4515}
4516
4517void AudioFlinger::TrackHandle::stop() {
4518 mTrack->stop();
4519}
4520
4521void AudioFlinger::TrackHandle::flush() {
4522 mTrack->flush();
4523}
4524
4525void AudioFlinger::TrackHandle::mute(bool e) {
4526 mTrack->mute(e);
4527}
4528
4529void AudioFlinger::TrackHandle::pause() {
4530 mTrack->pause();
4531}
4532
4533void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4534 mTrack->setVolume(left, right);
4535}
4536
4537sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4538 return mTrack->getCblk();
4539}
4540
4541status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4542{
4543 return mTrack->attachAuxEffect(EffectId);
4544}
4545
Mike J. Chen535235c2011-08-15 13:28:26 -07004546status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4547 sp<IMemory>* buffer) {
4548 if (!mTrack->isTimedTrack())
4549 return INVALID_OPERATION;
4550
4551 PlaybackThread::TimedTrack* tt =
4552 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4553 return tt->allocateTimedBuffer(size, buffer);
4554}
4555
4556status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4557 int64_t pts) {
4558 if (!mTrack->isTimedTrack())
4559 return INVALID_OPERATION;
4560
4561 PlaybackThread::TimedTrack* tt =
4562 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4563 return tt->queueTimedBuffer(buffer, pts);
4564}
4565
4566status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4567 const LinearTransform& xform, int target) {
4568
4569 if (!mTrack->isTimedTrack())
4570 return INVALID_OPERATION;
4571
4572 PlaybackThread::TimedTrack* tt =
4573 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4574 return tt->setMediaTimeTransform(
4575 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4576}
4577
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578status_t AudioFlinger::TrackHandle::onTransact(
4579 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4580{
4581 return BnAudioTrack::onTransact(code, data, reply, flags);
4582}
4583
4584// ----------------------------------------------------------------------------
4585
4586sp<IAudioRecord> AudioFlinger::openRecord(
4587 pid_t pid,
4588 int input,
4589 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004590 uint32_t format,
4591 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004592 int frameCount,
4593 uint32_t flags,
4594 int *sessionId,
4595 status_t *status)
4596{
4597 sp<RecordThread::RecordTrack> recordTrack;
4598 sp<RecordHandle> recordHandle;
4599 sp<Client> client;
4600 wp<Client> wclient;
4601 status_t lStatus;
4602 RecordThread *thread;
4603 size_t inFrameCount;
4604 int lSessionId;
4605
4606 // check calling permissions
4607 if (!recordingAllowed()) {
4608 lStatus = PERMISSION_DENIED;
4609 goto Exit;
4610 }
4611
4612 // add client to list
4613 { // scope for mLock
4614 Mutex::Autolock _l(mLock);
4615 thread = checkRecordThread_l(input);
4616 if (thread == NULL) {
4617 lStatus = BAD_VALUE;
4618 goto Exit;
4619 }
4620
4621 wclient = mClients.valueFor(pid);
4622 if (wclient != NULL) {
4623 client = wclient.promote();
4624 } else {
4625 client = new Client(this, pid);
4626 mClients.add(pid, client);
4627 }
4628
4629 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004630 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004631 lSessionId = *sessionId;
4632 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004633 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004634 if (sessionId != NULL) {
4635 *sessionId = lSessionId;
4636 }
4637 }
4638 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004639 recordTrack = thread->createRecordTrack_l(client,
4640 sampleRate,
4641 format,
4642 channelMask,
4643 frameCount,
4644 flags,
4645 lSessionId,
4646 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004647 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004648 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004649 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4650 // destructor is called by the TrackBase destructor with mLock held
4651 client.clear();
4652 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004653 goto Exit;
4654 }
4655
4656 // return to handle to client
4657 recordHandle = new RecordHandle(recordTrack);
4658 lStatus = NO_ERROR;
4659
4660Exit:
4661 if (status) {
4662 *status = lStatus;
4663 }
4664 return recordHandle;
4665}
4666
4667// ----------------------------------------------------------------------------
4668
4669AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4670 : BnAudioRecord(),
4671 mRecordTrack(recordTrack)
4672{
4673}
4674
4675AudioFlinger::RecordHandle::~RecordHandle() {
4676 stop();
4677}
4678
4679status_t AudioFlinger::RecordHandle::start() {
4680 LOGV("RecordHandle::start()");
4681 return mRecordTrack->start();
4682}
4683
4684void AudioFlinger::RecordHandle::stop() {
4685 LOGV("RecordHandle::stop()");
4686 mRecordTrack->stop();
4687}
4688
4689sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4690 return mRecordTrack->getCblk();
4691}
4692
4693status_t AudioFlinger::RecordHandle::onTransact(
4694 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4695{
4696 return BnAudioRecord::onTransact(code, data, reply, flags);
4697}
4698
4699// ----------------------------------------------------------------------------
4700
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004701AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4702 AudioStreamIn *input,
4703 uint32_t sampleRate,
4704 uint32_t channels,
4705 int id,
4706 uint32_t device) :
4707 ThreadBase(audioFlinger, id, device),
4708 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004710 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004711
4712 snprintf(mName, kNameLength, "AudioIn_%d", id);
4713
Dima Zavinfce7a472011-04-19 22:30:36 -07004714 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004715 mReqSampleRate = sampleRate;
4716 readInputParameters();
4717}
4718
4719
4720AudioFlinger::RecordThread::~RecordThread()
4721{
4722 delete[] mRsmpInBuffer;
4723 if (mResampler != 0) {
4724 delete mResampler;
4725 delete[] mRsmpOutBuffer;
4726 }
4727}
4728
4729void AudioFlinger::RecordThread::onFirstRef()
4730{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004731 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004732}
4733
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004734status_t AudioFlinger::RecordThread::readyToRun()
4735{
4736 status_t status = initCheck();
4737 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4738 return status;
4739}
4740
Mathias Agopian65ab4712010-07-14 17:59:35 -07004741bool AudioFlinger::RecordThread::threadLoop()
4742{
4743 AudioBufferProvider::Buffer buffer;
4744 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004745 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004746
Eric Laurent44d98482010-09-30 16:12:31 -07004747 nsecs_t lastWarning = 0;
4748
Eric Laurentfeb0db62011-07-22 09:04:31 -07004749 acquireWakeLock();
4750
Mathias Agopian65ab4712010-07-14 17:59:35 -07004751 // start recording
4752 while (!exitPending()) {
4753
4754 processConfigEvents();
4755
4756 { // scope for mLock
4757 Mutex::Autolock _l(mLock);
4758 checkForNewParameters_l();
4759 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4760 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004761 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004762 mStandby = true;
4763 }
4764
4765 if (exitPending()) break;
4766
Eric Laurentfeb0db62011-07-22 09:04:31 -07004767 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004768 LOGV("RecordThread: loop stopping");
4769 // go to sleep
4770 mWaitWorkCV.wait(mLock);
4771 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004772 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004773 continue;
4774 }
4775 if (mActiveTrack != 0) {
4776 if (mActiveTrack->mState == TrackBase::PAUSING) {
4777 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004778 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779 mStandby = true;
4780 }
4781 mActiveTrack.clear();
4782 mStartStopCond.broadcast();
4783 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4784 if (mReqChannelCount != mActiveTrack->channelCount()) {
4785 mActiveTrack.clear();
4786 mStartStopCond.broadcast();
4787 } else if (mBytesRead != 0) {
4788 // record start succeeds only if first read from audio input
4789 // succeeds
4790 if (mBytesRead > 0) {
4791 mActiveTrack->mState = TrackBase::ACTIVE;
4792 } else {
4793 mActiveTrack.clear();
4794 }
4795 mStartStopCond.broadcast();
4796 }
4797 mStandby = false;
4798 }
4799 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004800 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004801 }
4802
4803 if (mActiveTrack != 0) {
4804 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4805 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004806 unlockEffectChains(effectChains);
4807 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808 continue;
4809 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004810 for (size_t i = 0; i < effectChains.size(); i ++) {
4811 effectChains[i]->process_l();
4812 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004813
Mathias Agopian65ab4712010-07-14 17:59:35 -07004814 buffer.frameCount = mFrameCount;
Mike J. Chen535235c2011-08-15 13:28:26 -07004815 if (LIKELY(mActiveTrack->getNextBuffer(
4816 &buffer, AudioBufferProvider::kInvalidPTS) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004817 size_t framesOut = buffer.frameCount;
4818 if (mResampler == 0) {
4819 // no resampling
4820 while (framesOut) {
4821 size_t framesIn = mFrameCount - mRsmpInIndex;
4822 if (framesIn) {
4823 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4824 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4825 if (framesIn > framesOut)
4826 framesIn = framesOut;
4827 mRsmpInIndex += framesIn;
4828 framesOut -= framesIn;
4829 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004830 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004831 memcpy(dst, src, framesIn * mFrameSize);
4832 } else {
4833 int16_t *src16 = (int16_t *)src;
4834 int16_t *dst16 = (int16_t *)dst;
4835 if (mChannelCount == 1) {
4836 while (framesIn--) {
4837 *dst16++ = *src16;
4838 *dst16++ = *src16++;
4839 }
4840 } else {
4841 while (framesIn--) {
4842 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4843 src16 += 2;
4844 }
4845 }
4846 }
4847 }
4848 if (framesOut && mFrameCount == mRsmpInIndex) {
4849 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004850 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004851 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004852 framesOut = 0;
4853 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004854 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855 mRsmpInIndex = 0;
4856 }
4857 if (mBytesRead < 0) {
4858 LOGE("Error reading audio input");
4859 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4860 // Force input into standby so that it tries to
4861 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004862 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004863 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004864 }
4865 mRsmpInIndex = mFrameCount;
4866 framesOut = 0;
4867 buffer.frameCount = 0;
4868 }
4869 }
4870 }
4871 } else {
4872 // resampling
4873
4874 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4875 // alter output frame count as if we were expecting stereo samples
4876 if (mChannelCount == 1 && mReqChannelCount == 1) {
4877 framesOut >>= 1;
4878 }
4879 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4880 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4881 // are 32 bit aligned which should be always true.
4882 if (mChannelCount == 2 && mReqChannelCount == 1) {
4883 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4884 // the resampler always outputs stereo samples: do post stereo to mono conversion
4885 int16_t *src = (int16_t *)mRsmpOutBuffer;
4886 int16_t *dst = buffer.i16;
4887 while (framesOut--) {
4888 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4889 src += 2;
4890 }
4891 } else {
4892 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4893 }
4894
4895 }
4896 mActiveTrack->releaseBuffer(&buffer);
4897 mActiveTrack->overflow();
4898 }
4899 // client isn't retrieving buffers fast enough
4900 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004901 if (!mActiveTrack->setOverflow()) {
4902 nsecs_t now = systemTime();
4903 if ((now - lastWarning) > kWarningThrottle) {
4904 LOGW("RecordThread: buffer overflow");
4905 lastWarning = now;
4906 }
4907 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004908 // Release the processor for a while before asking for a new buffer.
4909 // This will give the application more chance to read from the buffer and
4910 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004911 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004912 }
4913 }
Eric Laurentec437d82011-07-26 20:54:46 -07004914 // enable changes in effect chain
4915 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004916 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917 }
4918
4919 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004920 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004921 }
4922 mActiveTrack.clear();
4923
4924 mStartStopCond.broadcast();
4925
Eric Laurentfeb0db62011-07-22 09:04:31 -07004926 releaseWakeLock();
4927
Mathias Agopian65ab4712010-07-14 17:59:35 -07004928 LOGV("RecordThread %p exiting", this);
4929 return false;
4930}
4931
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004932
4933sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4934 const sp<AudioFlinger::Client>& client,
4935 uint32_t sampleRate,
4936 int format,
4937 int channelMask,
4938 int frameCount,
4939 uint32_t flags,
4940 int sessionId,
4941 status_t *status)
4942{
4943 sp<RecordTrack> track;
4944 status_t lStatus;
4945
4946 lStatus = initCheck();
4947 if (lStatus != NO_ERROR) {
4948 LOGE("Audio driver not initialized.");
4949 goto Exit;
4950 }
4951
4952 { // scope for mLock
4953 Mutex::Autolock _l(mLock);
4954
4955 track = new RecordTrack(this, client, sampleRate,
4956 format, channelMask, frameCount, flags, sessionId);
4957
4958 if (track->getCblk() == NULL) {
4959 lStatus = NO_MEMORY;
4960 goto Exit;
4961 }
4962
4963 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004964 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4965 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004966 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004967 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4968 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004969 }
4970 lStatus = NO_ERROR;
4971
4972Exit:
4973 if (status) {
4974 *status = lStatus;
4975 }
4976 return track;
4977}
4978
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4980{
4981 LOGV("RecordThread::start");
4982 sp <ThreadBase> strongMe = this;
4983 status_t status = NO_ERROR;
4984 {
4985 AutoMutex lock(&mLock);
4986 if (mActiveTrack != 0) {
4987 if (recordTrack != mActiveTrack.get()) {
4988 status = -EBUSY;
4989 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4990 mActiveTrack->mState = TrackBase::ACTIVE;
4991 }
4992 return status;
4993 }
4994
4995 recordTrack->mState = TrackBase::IDLE;
4996 mActiveTrack = recordTrack;
4997 mLock.unlock();
4998 status_t status = AudioSystem::startInput(mId);
4999 mLock.lock();
5000 if (status != NO_ERROR) {
5001 mActiveTrack.clear();
5002 return status;
5003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005004 mRsmpInIndex = mFrameCount;
5005 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08005006 if (mResampler != NULL) {
5007 mResampler->reset();
5008 }
5009 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005010 // signal thread to start
5011 LOGV("Signal record thread");
5012 mWaitWorkCV.signal();
5013 // do not wait for mStartStopCond if exiting
5014 if (mExiting) {
5015 mActiveTrack.clear();
5016 status = INVALID_OPERATION;
5017 goto startError;
5018 }
5019 mStartStopCond.wait(mLock);
5020 if (mActiveTrack == 0) {
5021 LOGV("Record failed to start");
5022 status = BAD_VALUE;
5023 goto startError;
5024 }
5025 LOGV("Record started OK");
5026 return status;
5027 }
5028startError:
5029 AudioSystem::stopInput(mId);
5030 return status;
5031}
5032
5033void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
5034 LOGV("RecordThread::stop");
5035 sp <ThreadBase> strongMe = this;
5036 {
5037 AutoMutex lock(&mLock);
5038 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5039 mActiveTrack->mState = TrackBase::PAUSING;
5040 // do not wait for mStartStopCond if exiting
5041 if (mExiting) {
5042 return;
5043 }
5044 mStartStopCond.wait(mLock);
5045 // if we have been restarted, recordTrack == mActiveTrack.get() here
5046 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5047 mLock.unlock();
5048 AudioSystem::stopInput(mId);
5049 mLock.lock();
5050 LOGV("Record stopped OK");
5051 }
5052 }
5053 }
5054}
5055
5056status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5057{
5058 const size_t SIZE = 256;
5059 char buffer[SIZE];
5060 String8 result;
5061 pid_t pid = 0;
5062
5063 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5064 result.append(buffer);
5065
5066 if (mActiveTrack != 0) {
5067 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005068 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005069 mActiveTrack->dump(buffer, SIZE);
5070 result.append(buffer);
5071
5072 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5073 result.append(buffer);
5074 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5075 result.append(buffer);
5076 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
5077 result.append(buffer);
5078 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5079 result.append(buffer);
5080 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5081 result.append(buffer);
5082
5083
5084 } else {
5085 result.append("No record client\n");
5086 }
5087 write(fd, result.string(), result.size());
5088
5089 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005090 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005091
5092 return NO_ERROR;
5093}
5094
Mike J. Chen535235c2011-08-15 13:28:26 -07005095status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005096{
5097 size_t framesReq = buffer->frameCount;
5098 size_t framesReady = mFrameCount - mRsmpInIndex;
5099 int channelCount;
5100
5101 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005102 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 if (mBytesRead < 0) {
5104 LOGE("RecordThread::getNextBuffer() Error reading audio input");
5105 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5106 // Force input into standby so that it tries to
5107 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005108 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005109 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005110 }
5111 buffer->raw = 0;
5112 buffer->frameCount = 0;
5113 return NOT_ENOUGH_DATA;
5114 }
5115 mRsmpInIndex = 0;
5116 framesReady = mFrameCount;
5117 }
5118
5119 if (framesReq > framesReady) {
5120 framesReq = framesReady;
5121 }
5122
5123 if (mChannelCount == 1 && mReqChannelCount == 2) {
5124 channelCount = 1;
5125 } else {
5126 channelCount = 2;
5127 }
5128 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5129 buffer->frameCount = framesReq;
5130 return NO_ERROR;
5131}
5132
5133void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5134{
5135 mRsmpInIndex += buffer->frameCount;
5136 buffer->frameCount = 0;
5137}
5138
5139bool AudioFlinger::RecordThread::checkForNewParameters_l()
5140{
5141 bool reconfig = false;
5142
5143 while (!mNewParameters.isEmpty()) {
5144 status_t status = NO_ERROR;
5145 String8 keyValuePair = mNewParameters[0];
5146 AudioParameter param = AudioParameter(keyValuePair);
5147 int value;
5148 int reqFormat = mFormat;
5149 int reqSamplingRate = mReqSampleRate;
5150 int reqChannelCount = mReqChannelCount;
5151
5152 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5153 reqSamplingRate = value;
5154 reconfig = true;
5155 }
5156 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5157 reqFormat = value;
5158 reconfig = true;
5159 }
5160 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005161 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 reconfig = true;
5163 }
5164 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5165 // do not accept frame count changes if tracks are open as the track buffer
5166 // size depends on frame count and correct behavior would not be garantied
5167 // if frame count is changed after track creation
5168 if (mActiveTrack != 0) {
5169 status = INVALID_OPERATION;
5170 } else {
5171 reconfig = true;
5172 }
5173 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005174 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5175 // forward device change to effects that have requested to be
5176 // aware of attached audio device.
5177 for (size_t i = 0; i < mEffectChains.size(); i++) {
5178 mEffectChains[i]->setDevice_l(value);
5179 }
5180 // store input device and output device but do not forward output device to audio HAL.
5181 // Note that status is ignored by the caller for output device
5182 // (see AudioFlinger::setParameters()
5183 if (value & AUDIO_DEVICE_OUT_ALL) {
5184 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5185 status = BAD_VALUE;
5186 } else {
5187 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005188 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5189 if (mTrack != NULL) {
5190 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005191 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005192 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5193 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5194 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005195 }
5196 mDevice |= (uint32_t)value;
5197 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005198 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005199 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005201 mInput->stream->common.standby(&mInput->stream->common);
5202 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005203 }
5204 if (reconfig) {
5205 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005206 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005207 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005208 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5209 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005210 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005211 status = NO_ERROR;
5212 }
5213 if (status == NO_ERROR) {
5214 readInputParameters();
5215 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5216 }
5217 }
5218 }
5219
5220 mNewParameters.removeAt(0);
5221
5222 mParamStatus = status;
5223 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07005224 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
5225 // already timed out waiting for the status and will never signal the condition.
5226 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeout);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005227 }
5228 return reconfig;
5229}
5230
5231String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5232{
Dima Zavinfce7a472011-04-19 22:30:36 -07005233 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005234 String8 out_s8 = String8();
5235
5236 Mutex::Autolock _l(mLock);
5237 if (initCheck() != NO_ERROR) {
5238 return out_s8;
5239 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005240
Dima Zavin799a70e2011-04-18 16:57:27 -07005241 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005242 out_s8 = String8(s);
5243 free(s);
5244 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005245}
5246
5247void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5248 AudioSystem::OutputDescriptor desc;
5249 void *param2 = 0;
5250
5251 switch (event) {
5252 case AudioSystem::INPUT_OPENED:
5253 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005254 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005255 desc.samplingRate = mSampleRate;
5256 desc.format = mFormat;
5257 desc.frameCount = mFrameCount;
5258 desc.latency = 0;
5259 param2 = &desc;
5260 break;
5261
5262 case AudioSystem::INPUT_CLOSED:
5263 default:
5264 break;
5265 }
5266 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5267}
5268
5269void AudioFlinger::RecordThread::readInputParameters()
5270{
5271 if (mRsmpInBuffer) delete mRsmpInBuffer;
5272 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
5273 if (mResampler) delete mResampler;
5274 mResampler = 0;
5275
Dima Zavin799a70e2011-04-18 16:57:27 -07005276 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005277 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5278 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005279 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5280 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
5281 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282 mFrameCount = mInputBytes / mFrameSize;
5283 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5284
5285 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5286 {
5287 int channelCount;
5288 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5289 // stereo to mono post process as the resampler always outputs stereo.
5290 if (mChannelCount == 1 && mReqChannelCount == 2) {
5291 channelCount = 1;
5292 } else {
5293 channelCount = 2;
5294 }
5295 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5296 mResampler->setSampleRate(mSampleRate);
5297 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5298 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5299
5300 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5301 if (mChannelCount == 1 && mReqChannelCount == 1) {
5302 mFrameCount >>= 1;
5303 }
5304
5305 }
5306 mRsmpInIndex = mFrameCount;
5307}
5308
5309unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5310{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005311 Mutex::Autolock _l(mLock);
5312 if (initCheck() != NO_ERROR) {
5313 return 0;
5314 }
5315
Dima Zavin799a70e2011-04-18 16:57:27 -07005316 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005317}
5318
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005319uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5320{
5321 Mutex::Autolock _l(mLock);
5322 uint32_t result = 0;
5323 if (getEffectChain_l(sessionId) != 0) {
5324 result = EFFECT_SESSION;
5325 }
5326
5327 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5328 result |= TRACK_SESSION;
5329 }
5330
5331 return result;
5332}
5333
Eric Laurent59bd0da2011-08-01 09:52:20 -07005334AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5335{
5336 Mutex::Autolock _l(mLock);
5337 return mTrack;
5338}
5339
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005340AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
5341{
5342 Mutex::Autolock _l(mLock);
5343 return mInput;
5344}
5345
5346AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5347{
5348 Mutex::Autolock _l(mLock);
5349 AudioStreamIn *input = mInput;
5350 mInput = NULL;
5351 return input;
5352}
5353
5354// this method must always be called either with ThreadBase mLock held or inside the thread loop
5355audio_stream_t* AudioFlinger::RecordThread::stream()
5356{
5357 if (mInput == NULL) {
5358 return NULL;
5359 }
5360 return &mInput->stream->common;
5361}
5362
5363
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364// ----------------------------------------------------------------------------
5365
5366int AudioFlinger::openOutput(uint32_t *pDevices,
5367 uint32_t *pSamplingRate,
5368 uint32_t *pFormat,
5369 uint32_t *pChannels,
5370 uint32_t *pLatencyMs,
5371 uint32_t flags)
5372{
5373 status_t status;
5374 PlaybackThread *thread = NULL;
5375 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5376 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5377 uint32_t format = pFormat ? *pFormat : 0;
5378 uint32_t channels = pChannels ? *pChannels : 0;
5379 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005380 audio_stream_out_t *outStream;
5381 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005382
5383 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5384 pDevices ? *pDevices : 0,
5385 samplingRate,
5386 format,
5387 channels,
5388 flags);
5389
5390 if (pDevices == NULL || *pDevices == 0) {
5391 return 0;
5392 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005393
Mathias Agopian65ab4712010-07-14 17:59:35 -07005394 Mutex::Autolock _l(mLock);
5395
Dima Zavin799a70e2011-04-18 16:57:27 -07005396 outHwDev = findSuitableHwDev_l(*pDevices);
5397 if (outHwDev == NULL)
5398 return 0;
5399
5400 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
5401 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005402 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005403 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005404 samplingRate,
5405 format,
5406 channels,
5407 status);
5408
5409 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07005410 if (outStream != NULL) {
5411 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005412 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005413
Dima Zavinfce7a472011-04-19 22:30:36 -07005414 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5415 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5416 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005417 thread = new DirectOutputThread(this, output, id, *pDevices);
5418 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
5419 } else {
5420 thread = new MixerThread(this, output, id, *pDevices);
5421 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005422 }
5423 mPlaybackThreads.add(id, thread);
5424
5425 if (pSamplingRate) *pSamplingRate = samplingRate;
5426 if (pFormat) *pFormat = format;
5427 if (pChannels) *pChannels = channels;
5428 if (pLatencyMs) *pLatencyMs = thread->latency();
5429
5430 // notify client processes of the new output creation
5431 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5432 return id;
5433 }
5434
5435 return 0;
5436}
5437
5438int AudioFlinger::openDuplicateOutput(int output1, int output2)
5439{
5440 Mutex::Autolock _l(mLock);
5441 MixerThread *thread1 = checkMixerThread_l(output1);
5442 MixerThread *thread2 = checkMixerThread_l(output2);
5443
5444 if (thread1 == NULL || thread2 == NULL) {
5445 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
5446 return 0;
5447 }
5448
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005449 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5451 thread->addOutputTrack(thread2);
5452 mPlaybackThreads.add(id, thread);
5453 // notify client processes of the new output creation
5454 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5455 return id;
5456}
5457
5458status_t AudioFlinger::closeOutput(int output)
5459{
5460 // keep strong reference on the playback thread so that
5461 // it is not destroyed while exit() is executed
5462 sp <PlaybackThread> thread;
5463 {
5464 Mutex::Autolock _l(mLock);
5465 thread = checkPlaybackThread_l(output);
5466 if (thread == NULL) {
5467 return BAD_VALUE;
5468 }
5469
5470 LOGV("closeOutput() %d", output);
5471
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005472 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005474 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005475 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5476 dupThread->removeOutputTrack((MixerThread *)thread.get());
5477 }
5478 }
5479 }
5480 void *param2 = 0;
5481 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5482 mPlaybackThreads.removeItem(output);
5483 }
5484 thread->exit();
5485
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005486 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005487 AudioStreamOut *out = thread->clearOutput();
5488 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005489 out->hwDev->close_output_stream(out->hwDev, out->stream);
5490 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 }
5492 return NO_ERROR;
5493}
5494
5495status_t AudioFlinger::suspendOutput(int output)
5496{
5497 Mutex::Autolock _l(mLock);
5498 PlaybackThread *thread = checkPlaybackThread_l(output);
5499
5500 if (thread == NULL) {
5501 return BAD_VALUE;
5502 }
5503
5504 LOGV("suspendOutput() %d", output);
5505 thread->suspend();
5506
5507 return NO_ERROR;
5508}
5509
5510status_t AudioFlinger::restoreOutput(int output)
5511{
5512 Mutex::Autolock _l(mLock);
5513 PlaybackThread *thread = checkPlaybackThread_l(output);
5514
5515 if (thread == NULL) {
5516 return BAD_VALUE;
5517 }
5518
5519 LOGV("restoreOutput() %d", output);
5520
5521 thread->restore();
5522
5523 return NO_ERROR;
5524}
5525
5526int AudioFlinger::openInput(uint32_t *pDevices,
5527 uint32_t *pSamplingRate,
5528 uint32_t *pFormat,
5529 uint32_t *pChannels,
5530 uint32_t acoustics)
5531{
5532 status_t status;
5533 RecordThread *thread = NULL;
5534 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5535 uint32_t format = pFormat ? *pFormat : 0;
5536 uint32_t channels = pChannels ? *pChannels : 0;
5537 uint32_t reqSamplingRate = samplingRate;
5538 uint32_t reqFormat = format;
5539 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005540 audio_stream_in_t *inStream;
5541 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542
5543 if (pDevices == NULL || *pDevices == 0) {
5544 return 0;
5545 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005546
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 Mutex::Autolock _l(mLock);
5548
Dima Zavin799a70e2011-04-18 16:57:27 -07005549 inHwDev = findSuitableHwDev_l(*pDevices);
5550 if (inHwDev == NULL)
5551 return 0;
5552
5553 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5554 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005555 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005556 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005558 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005559 samplingRate,
5560 format,
5561 channels,
5562 acoustics,
5563 status);
5564
5565 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5566 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5567 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005568 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005569 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005570 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005571 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005573 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5574 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005575 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005576 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 }
5578
Dima Zavin799a70e2011-04-18 16:57:27 -07005579 if (inStream != NULL) {
5580 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5581
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005582 int id = nextUniqueId();
5583 // Start record thread
5584 // RecorThread require both input and output device indication to forward to audio
5585 // pre processing modules
5586 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5587 thread = new RecordThread(this,
5588 input,
5589 reqSamplingRate,
5590 reqChannels,
5591 id,
5592 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 mRecordThreads.add(id, thread);
5594 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
5595 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5596 if (pFormat) *pFormat = format;
5597 if (pChannels) *pChannels = reqChannels;
5598
Dima Zavin799a70e2011-04-18 16:57:27 -07005599 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005600
5601 // notify client processes of the new input creation
5602 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5603 return id;
5604 }
5605
5606 return 0;
5607}
5608
5609status_t AudioFlinger::closeInput(int input)
5610{
5611 // keep strong reference on the record thread so that
5612 // it is not destroyed while exit() is executed
5613 sp <RecordThread> thread;
5614 {
5615 Mutex::Autolock _l(mLock);
5616 thread = checkRecordThread_l(input);
5617 if (thread == NULL) {
5618 return BAD_VALUE;
5619 }
5620
5621 LOGV("closeInput() %d", input);
5622 void *param2 = 0;
5623 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5624 mRecordThreads.removeItem(input);
5625 }
5626 thread->exit();
5627
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005628 AudioStreamIn *in = thread->clearInput();
5629 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005630 in->hwDev->close_input_stream(in->hwDev, in->stream);
5631 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005632
5633 return NO_ERROR;
5634}
5635
5636status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5637{
5638 Mutex::Autolock _l(mLock);
5639 MixerThread *dstThread = checkMixerThread_l(output);
5640 if (dstThread == NULL) {
5641 LOGW("setStreamOutput() bad output id %d", output);
5642 return BAD_VALUE;
5643 }
5644
5645 LOGV("setStreamOutput() stream %d to output %d", stream, output);
5646 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5647
Eric Laurent9f6530f2011-08-30 10:18:54 -07005648 dstThread->setStreamValid(stream, true);
5649
Mathias Agopian65ab4712010-07-14 17:59:35 -07005650 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5651 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5652 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005653 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005654 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005655 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005656 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005657 }
Eric Laurentde070132010-07-13 04:45:46 -07005658 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005659
5660 return NO_ERROR;
5661}
5662
5663
5664int AudioFlinger::newAudioSessionId()
5665{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005666 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667}
5668
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005669void AudioFlinger::acquireAudioSessionId(int audioSession)
5670{
5671 Mutex::Autolock _l(mLock);
5672 int caller = IPCThreadState::self()->getCallingPid();
5673 LOGV("acquiring %d from %d", audioSession, caller);
5674 int num = mAudioSessionRefs.size();
5675 for (int i = 0; i< num; i++) {
5676 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5677 if (ref->sessionid == audioSession && ref->pid == caller) {
5678 ref->cnt++;
5679 LOGV(" incremented refcount to %d", ref->cnt);
5680 return;
5681 }
5682 }
5683 AudioSessionRef *ref = new AudioSessionRef();
5684 ref->sessionid = audioSession;
5685 ref->pid = caller;
5686 ref->cnt = 1;
5687 mAudioSessionRefs.push(ref);
5688 LOGV(" added new entry for %d", ref->sessionid);
5689}
5690
5691void AudioFlinger::releaseAudioSessionId(int audioSession)
5692{
5693 Mutex::Autolock _l(mLock);
5694 int caller = IPCThreadState::self()->getCallingPid();
5695 LOGV("releasing %d from %d", audioSession, caller);
5696 int num = mAudioSessionRefs.size();
5697 for (int i = 0; i< num; i++) {
5698 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5699 if (ref->sessionid == audioSession && ref->pid == caller) {
5700 ref->cnt--;
5701 LOGV(" decremented refcount to %d", ref->cnt);
5702 if (ref->cnt == 0) {
5703 mAudioSessionRefs.removeAt(i);
5704 delete ref;
5705 purgeStaleEffects_l();
5706 }
5707 return;
5708 }
5709 }
5710 LOGW("session id %d not found for pid %d", audioSession, caller);
5711}
5712
5713void AudioFlinger::purgeStaleEffects_l() {
5714
5715 LOGV("purging stale effects");
5716
5717 Vector< sp<EffectChain> > chains;
5718
5719 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5720 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5721 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5722 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005723 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5724 chains.push(ec);
5725 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005726 }
5727 }
5728 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5729 sp<RecordThread> t = mRecordThreads.valueAt(i);
5730 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5731 sp<EffectChain> ec = t->mEffectChains[j];
5732 chains.push(ec);
5733 }
5734 }
5735
5736 for (size_t i = 0; i < chains.size(); i++) {
5737 sp<EffectChain> ec = chains[i];
5738 int sessionid = ec->sessionId();
5739 sp<ThreadBase> t = ec->mThread.promote();
5740 if (t == 0) {
5741 continue;
5742 }
5743 size_t numsessionrefs = mAudioSessionRefs.size();
5744 bool found = false;
5745 for (size_t k = 0; k < numsessionrefs; k++) {
5746 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5747 if (ref->sessionid == sessionid) {
5748 LOGV(" session %d still exists for %d with %d refs",
5749 sessionid, ref->pid, ref->cnt);
5750 found = true;
5751 break;
5752 }
5753 }
5754 if (!found) {
5755 // remove all effects from the chain
5756 while (ec->mEffects.size()) {
5757 sp<EffectModule> effect = ec->mEffects[0];
5758 effect->unPin();
5759 Mutex::Autolock _l (t->mLock);
5760 t->removeEffect_l(effect);
5761 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5762 sp<EffectHandle> handle = effect->mHandles[j].promote();
5763 if (handle != 0) {
5764 handle->mEffect.clear();
5765 }
5766 }
5767 AudioSystem::unregisterEffect(effect->id());
5768 }
5769 }
5770 }
5771 return;
5772}
5773
Mathias Agopian65ab4712010-07-14 17:59:35 -07005774// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5775AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5776{
5777 PlaybackThread *thread = NULL;
5778 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5779 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5780 }
5781 return thread;
5782}
5783
5784// checkMixerThread_l() must be called with AudioFlinger::mLock held
5785AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5786{
5787 PlaybackThread *thread = checkPlaybackThread_l(output);
5788 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005789 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005790 thread = NULL;
5791 }
5792 }
5793 return (MixerThread *)thread;
5794}
5795
5796// checkRecordThread_l() must be called with AudioFlinger::mLock held
5797AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5798{
5799 RecordThread *thread = NULL;
5800 if (mRecordThreads.indexOfKey(input) >= 0) {
5801 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5802 }
5803 return thread;
5804}
5805
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005806uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005808 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005809}
5810
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005811AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5812{
5813 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5814 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005815 AudioStreamOut *output = thread->getOutput();
5816 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005817 return thread;
5818 }
5819 }
5820 return NULL;
5821}
5822
5823uint32_t AudioFlinger::primaryOutputDevice_l()
5824{
5825 PlaybackThread *thread = primaryPlaybackThread_l();
5826
5827 if (thread == NULL) {
5828 return 0;
5829 }
5830
5831 return thread->device();
5832}
5833
5834
Mathias Agopian65ab4712010-07-14 17:59:35 -07005835// ----------------------------------------------------------------------------
5836// Effect management
5837// ----------------------------------------------------------------------------
5838
5839
Mathias Agopian65ab4712010-07-14 17:59:35 -07005840status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5841{
5842 Mutex::Autolock _l(mLock);
5843 return EffectQueryNumberEffects(numEffects);
5844}
5845
5846status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5847{
5848 Mutex::Autolock _l(mLock);
5849 return EffectQueryEffect(index, descriptor);
5850}
5851
5852status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5853{
5854 Mutex::Autolock _l(mLock);
5855 return EffectGetDescriptor(pUuid, descriptor);
5856}
5857
5858
Mathias Agopian65ab4712010-07-14 17:59:35 -07005859sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5860 effect_descriptor_t *pDesc,
5861 const sp<IEffectClient>& effectClient,
5862 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005863 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005864 int sessionId,
5865 status_t *status,
5866 int *id,
5867 int *enabled)
5868{
5869 status_t lStatus = NO_ERROR;
5870 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005871 effect_descriptor_t desc;
5872 sp<Client> client;
5873 wp<Client> wclient;
5874
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005875 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5876 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005877
5878 if (pDesc == NULL) {
5879 lStatus = BAD_VALUE;
5880 goto Exit;
5881 }
5882
Eric Laurent84e9a102010-09-23 16:10:16 -07005883 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005884 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005885 lStatus = PERMISSION_DENIED;
5886 goto Exit;
5887 }
5888
Dima Zavinfce7a472011-04-19 22:30:36 -07005889 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005890 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005891 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005892 lStatus = PERMISSION_DENIED;
5893 goto Exit;
5894 }
5895
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005896 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005897 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005898 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005899 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005900 lStatus = BAD_VALUE;
5901 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005902 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005903 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005904 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005905 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005906 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005907 }
5908 }
5909
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 {
5911 Mutex::Autolock _l(mLock);
5912
Mathias Agopian65ab4712010-07-14 17:59:35 -07005913
5914 if (!EffectIsNullUuid(&pDesc->uuid)) {
5915 // if uuid is specified, request effect descriptor
5916 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5917 if (lStatus < 0) {
5918 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5919 goto Exit;
5920 }
5921 } else {
5922 // if uuid is not specified, look for an available implementation
5923 // of the required type in effect factory
5924 if (EffectIsNullUuid(&pDesc->type)) {
5925 LOGW("createEffect() no effect type");
5926 lStatus = BAD_VALUE;
5927 goto Exit;
5928 }
5929 uint32_t numEffects = 0;
5930 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005931 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 bool found = false;
5933
5934 lStatus = EffectQueryNumberEffects(&numEffects);
5935 if (lStatus < 0) {
5936 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5937 goto Exit;
5938 }
5939 for (uint32_t i = 0; i < numEffects; i++) {
5940 lStatus = EffectQueryEffect(i, &desc);
5941 if (lStatus < 0) {
5942 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5943 continue;
5944 }
5945 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5946 // If matching type found save effect descriptor. If the session is
5947 // 0 and the effect is not auxiliary, continue enumeration in case
5948 // an auxiliary version of this effect type is available
5949 found = true;
5950 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005951 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005952 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5953 break;
5954 }
5955 }
5956 }
5957 if (!found) {
5958 lStatus = BAD_VALUE;
5959 LOGW("createEffect() effect not found");
5960 goto Exit;
5961 }
5962 // For same effect type, chose auxiliary version over insert version if
5963 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005964 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005965 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5966 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5967 }
5968 }
5969
5970 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005971 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5973 lStatus = INVALID_OPERATION;
5974 goto Exit;
5975 }
5976
Eric Laurent59255e42011-07-27 19:49:51 -07005977 // check recording permission for visualizer
5978 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5979 !recordingAllowed()) {
5980 lStatus = PERMISSION_DENIED;
5981 goto Exit;
5982 }
5983
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 // return effect descriptor
5985 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5986
5987 // If output is not specified try to find a matching audio session ID in one of the
5988 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005989 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5990 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005991 // Note: io is never 0 when creating an effect on an input
5992 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005993 // look for the thread where the specified audio session is present
5994 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5995 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005996 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005997 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005998 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005999 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006000 if (io == 0) {
6001 for (size_t i = 0; i < mRecordThreads.size(); i++) {
6002 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
6003 io = mRecordThreads.keyAt(i);
6004 break;
6005 }
6006 }
6007 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006008 // If no output thread contains the requested session ID, default to
6009 // first output. The effect chain will be moved to the correct output
6010 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006011 if (io == 0 && mPlaybackThreads.size()) {
6012 io = mPlaybackThreads.keyAt(0);
6013 }
6014 LOGV("createEffect() got io %d for effect %s", io, desc.name);
6015 }
6016 ThreadBase *thread = checkRecordThread_l(io);
6017 if (thread == NULL) {
6018 thread = checkPlaybackThread_l(io);
6019 if (thread == NULL) {
6020 LOGE("createEffect() unknown output thread");
6021 lStatus = BAD_VALUE;
6022 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07006023 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006024 }
Eric Laurent84e9a102010-09-23 16:10:16 -07006025
Mathias Agopian65ab4712010-07-14 17:59:35 -07006026 wclient = mClients.valueFor(pid);
6027
6028 if (wclient != NULL) {
6029 client = wclient.promote();
6030 } else {
6031 client = new Client(this, pid);
6032 mClients.add(pid, client);
6033 }
6034
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006035 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006036 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6037 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006038 if (handle != 0 && id != NULL) {
6039 *id = handle->id();
6040 }
6041 }
6042
6043Exit:
6044 if(status) {
6045 *status = lStatus;
6046 }
6047 return handle;
6048}
6049
Eric Laurent59255e42011-07-27 19:49:51 -07006050status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006051{
6052 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006053 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006054 Mutex::Autolock _l(mLock);
6055 if (srcOutput == dstOutput) {
6056 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
6057 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006058 }
Eric Laurentde070132010-07-13 04:45:46 -07006059 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6060 if (srcThread == NULL) {
6061 LOGW("moveEffects() bad srcOutput %d", srcOutput);
6062 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006063 }
Eric Laurentde070132010-07-13 04:45:46 -07006064 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6065 if (dstThread == NULL) {
6066 LOGW("moveEffects() bad dstOutput %d", dstOutput);
6067 return BAD_VALUE;
6068 }
6069
6070 Mutex::Autolock _dl(dstThread->mLock);
6071 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006072 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074 return NO_ERROR;
6075}
6076
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006077// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006078status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006079 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006080 AudioFlinger::PlaybackThread *dstThread,
6081 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006082{
6083 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006084 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006085
Eric Laurent59255e42011-07-27 19:49:51 -07006086 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006087 if (chain == 0) {
6088 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006089 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006090 return INVALID_OPERATION;
6091 }
6092
Eric Laurent39e94f82010-07-28 01:32:47 -07006093 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006094 // so that a new chain is created with correct parameters when first effect is added. This is
6095 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
6096 // removed.
6097 srcThread->removeEffectChain_l(chain);
6098
6099 // transfer all effects one by one so that new effect chain is created on new thread with
6100 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07006101 int dstOutput = dstThread->id();
6102 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006103 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006104 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6105 while (effect != 0) {
6106 srcThread->removeEffect_l(effect);
6107 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07006108 // if the move request is not received from audio policy manager, the effect must be
6109 // re-registered with the new strategy and output
6110 if (dstChain == 0) {
6111 dstChain = effect->chain().promote();
6112 if (dstChain == 0) {
6113 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
6114 srcThread->addEffect_l(effect);
6115 return NO_INIT;
6116 }
6117 strategy = dstChain->strategy();
6118 }
6119 if (reRegister) {
6120 AudioSystem::unregisterEffect(effect->id());
6121 AudioSystem::registerEffect(&effect->desc(),
6122 dstOutput,
6123 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006124 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006125 effect->id());
6126 }
Eric Laurentde070132010-07-13 04:45:46 -07006127 effect = chain->getEffectFromId_l(0);
6128 }
6129
6130 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006131}
6132
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006133
Mathias Agopian65ab4712010-07-14 17:59:35 -07006134// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006135sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 const sp<AudioFlinger::Client>& client,
6137 const sp<IEffectClient>& effectClient,
6138 int32_t priority,
6139 int sessionId,
6140 effect_descriptor_t *desc,
6141 int *enabled,
6142 status_t *status
6143 )
6144{
6145 sp<EffectModule> effect;
6146 sp<EffectHandle> handle;
6147 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006148 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006149 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006150 bool effectCreated = false;
6151 bool effectRegistered = false;
6152
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006153 lStatus = initCheck();
6154 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006155 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 goto Exit;
6157 }
6158
6159 // Do not allow effects with session ID 0 on direct output or duplicating threads
6160 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006161 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07006162 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
6163 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 lStatus = BAD_VALUE;
6165 goto Exit;
6166 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006167 // Only Pre processor effects are allowed on input threads and only on input threads
6168 if ((mType == RECORD &&
6169 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
6170 (mType != RECORD &&
6171 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
6172 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
6173 desc->name, desc->flags, mType);
6174 lStatus = BAD_VALUE;
6175 goto Exit;
6176 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006177
6178 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
6179
6180 { // scope for mLock
6181 Mutex::Autolock _l(mLock);
6182
6183 // check for existing effect chain with the requested audio session
6184 chain = getEffectChain_l(sessionId);
6185 if (chain == 0) {
6186 // create a new chain for this session
6187 LOGV("createEffect_l() new effect chain for session %d", sessionId);
6188 chain = new EffectChain(this, sessionId);
6189 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006190 chain->setStrategy(getStrategyForSession_l(sessionId));
6191 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006192 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006193 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006194 }
6195
6196 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
6197
6198 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006199 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006200 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006201 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006202 if (lStatus != NO_ERROR) {
6203 goto Exit;
6204 }
6205 effectRegistered = true;
6206 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006207 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006208 lStatus = effect->status();
6209 if (lStatus != NO_ERROR) {
6210 goto Exit;
6211 }
Eric Laurentcab11242010-07-15 12:50:15 -07006212 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006213 if (lStatus != NO_ERROR) {
6214 goto Exit;
6215 }
6216 effectCreated = true;
6217
6218 effect->setDevice(mDevice);
6219 effect->setMode(mAudioFlinger->getMode());
6220 }
6221 // create effect handle and connect it to effect module
6222 handle = new EffectHandle(effect, client, effectClient, priority);
6223 lStatus = effect->addHandle(handle);
6224 if (enabled) {
6225 *enabled = (int)effect->isEnabled();
6226 }
6227 }
6228
6229Exit:
6230 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006231 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006232 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006233 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006234 }
6235 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006236 AudioSystem::unregisterEffect(effect->id());
6237 }
6238 if (chainCreated) {
6239 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006240 }
6241 handle.clear();
6242 }
6243
6244 if(status) {
6245 *status = lStatus;
6246 }
6247 return handle;
6248}
6249
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006250sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6251{
6252 sp<EffectModule> effect;
6253
6254 sp<EffectChain> chain = getEffectChain_l(sessionId);
6255 if (chain != 0) {
6256 effect = chain->getEffectFromId_l(effectId);
6257 }
6258 return effect;
6259}
6260
Eric Laurentde070132010-07-13 04:45:46 -07006261// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6262// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006263status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006264{
6265 // check for existing effect chain with the requested audio session
6266 int sessionId = effect->sessionId();
6267 sp<EffectChain> chain = getEffectChain_l(sessionId);
6268 bool chainCreated = false;
6269
6270 if (chain == 0) {
6271 // create a new chain for this session
6272 LOGV("addEffect_l() new effect chain for session %d", sessionId);
6273 chain = new EffectChain(this, sessionId);
6274 addEffectChain_l(chain);
6275 chain->setStrategy(getStrategyForSession_l(sessionId));
6276 chainCreated = true;
6277 }
6278 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
6279
6280 if (chain->getEffectFromId_l(effect->id()) != 0) {
6281 LOGW("addEffect_l() %p effect %s already present in chain %p",
6282 this, effect->desc().name, chain.get());
6283 return BAD_VALUE;
6284 }
6285
6286 status_t status = chain->addEffect_l(effect);
6287 if (status != NO_ERROR) {
6288 if (chainCreated) {
6289 removeEffectChain_l(chain);
6290 }
6291 return status;
6292 }
6293
6294 effect->setDevice(mDevice);
6295 effect->setMode(mAudioFlinger->getMode());
6296 return NO_ERROR;
6297}
6298
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006299void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006300
6301 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006302 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006303 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6304 detachAuxEffect_l(effect->id());
6305 }
6306
6307 sp<EffectChain> chain = effect->chain().promote();
6308 if (chain != 0) {
6309 // remove effect chain if removing last effect
6310 if (chain->removeEffect_l(effect) == 0) {
6311 removeEffectChain_l(chain);
6312 }
6313 } else {
6314 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
6315 }
6316}
6317
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006318void AudioFlinger::ThreadBase::lockEffectChains_l(
6319 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6320{
6321 effectChains = mEffectChains;
6322 for (size_t i = 0; i < mEffectChains.size(); i++) {
6323 mEffectChains[i]->lock();
6324 }
6325}
6326
6327void AudioFlinger::ThreadBase::unlockEffectChains(
6328 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6329{
6330 for (size_t i = 0; i < effectChains.size(); i++) {
6331 effectChains[i]->unlock();
6332 }
6333}
6334
6335sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6336{
6337 Mutex::Autolock _l(mLock);
6338 return getEffectChain_l(sessionId);
6339}
6340
6341sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6342{
6343 sp<EffectChain> chain;
6344
6345 size_t size = mEffectChains.size();
6346 for (size_t i = 0; i < size; i++) {
6347 if (mEffectChains[i]->sessionId() == sessionId) {
6348 chain = mEffectChains[i];
6349 break;
6350 }
6351 }
6352 return chain;
6353}
6354
6355void AudioFlinger::ThreadBase::setMode(uint32_t mode)
6356{
6357 Mutex::Autolock _l(mLock);
6358 size_t size = mEffectChains.size();
6359 for (size_t i = 0; i < size; i++) {
6360 mEffectChains[i]->setMode_l(mode);
6361 }
6362}
6363
6364void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006365 const wp<EffectHandle>& handle,
6366 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006367
Mathias Agopian65ab4712010-07-14 17:59:35 -07006368 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006369 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006370 // delete the effect module if removing last handle on it
6371 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006372 if (!effect->isPinned() || unpiniflast) {
6373 removeEffect_l(effect);
6374 AudioSystem::unregisterEffect(effect->id());
6375 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 }
6377}
6378
6379status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6380{
6381 int session = chain->sessionId();
6382 int16_t *buffer = mMixBuffer;
6383 bool ownsBuffer = false;
6384
6385 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
6386 if (session > 0) {
6387 // Only one effect chain can be present in direct output thread and it uses
6388 // the mix buffer as input
6389 if (mType != DIRECT) {
6390 size_t numSamples = mFrameCount * mChannelCount;
6391 buffer = new int16_t[numSamples];
6392 memset(buffer, 0, numSamples * sizeof(int16_t));
6393 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
6394 ownsBuffer = true;
6395 }
6396
6397 // Attach all tracks with same session ID to this chain.
6398 for (size_t i = 0; i < mTracks.size(); ++i) {
6399 sp<Track> track = mTracks[i];
6400 if (session == track->sessionId()) {
6401 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
6402 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006403 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006404 }
6405 }
6406
6407 // indicate all active tracks in the chain
6408 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6409 sp<Track> track = mActiveTracks[i].promote();
6410 if (track == 0) continue;
6411 if (session == track->sessionId()) {
6412 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006413 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006414 }
6415 }
6416 }
6417
6418 chain->setInBuffer(buffer, ownsBuffer);
6419 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006420 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006421 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006422 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6423 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006424 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006425 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6426 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006427 // Effect chain for other sessions are inserted at beginning of effect
6428 // chains list to be processed before output mix effects. Relative order between other
6429 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006430 size_t size = mEffectChains.size();
6431 size_t i = 0;
6432 for (i = 0; i < size; i++) {
6433 if (mEffectChains[i]->sessionId() < session) break;
6434 }
6435 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006436 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006437
6438 return NO_ERROR;
6439}
6440
6441size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6442{
6443 int session = chain->sessionId();
6444
6445 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
6446
6447 for (size_t i = 0; i < mEffectChains.size(); i++) {
6448 if (chain == mEffectChains[i]) {
6449 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006450 // detach all active tracks from the chain
6451 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6452 sp<Track> track = mActiveTracks[i].promote();
6453 if (track == 0) continue;
6454 if (session == track->sessionId()) {
6455 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6456 chain.get(), session);
6457 chain->decActiveTrackCnt();
6458 }
6459 }
6460
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461 // detach all tracks with same session ID from this chain
6462 for (size_t i = 0; i < mTracks.size(); ++i) {
6463 sp<Track> track = mTracks[i];
6464 if (session == track->sessionId()) {
6465 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006466 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006467 }
6468 }
Eric Laurentde070132010-07-13 04:45:46 -07006469 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006470 }
6471 }
6472 return mEffectChains.size();
6473}
6474
Eric Laurentde070132010-07-13 04:45:46 -07006475status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6476 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477{
6478 Mutex::Autolock _l(mLock);
6479 return attachAuxEffect_l(track, EffectId);
6480}
6481
Eric Laurentde070132010-07-13 04:45:46 -07006482status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6483 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006484{
6485 status_t status = NO_ERROR;
6486
6487 if (EffectId == 0) {
6488 track->setAuxBuffer(0, NULL);
6489 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006490 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6491 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 if (effect != 0) {
6493 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6494 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6495 } else {
6496 status = INVALID_OPERATION;
6497 }
6498 } else {
6499 status = BAD_VALUE;
6500 }
6501 }
6502 return status;
6503}
6504
6505void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6506{
6507 for (size_t i = 0; i < mTracks.size(); ++i) {
6508 sp<Track> track = mTracks[i];
6509 if (track->auxEffectId() == effectId) {
6510 attachAuxEffect_l(track, 0);
6511 }
6512 }
6513}
6514
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006515status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6516{
6517 // only one chain per input thread
6518 if (mEffectChains.size() != 0) {
6519 return INVALID_OPERATION;
6520 }
6521 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6522
6523 chain->setInBuffer(NULL);
6524 chain->setOutBuffer(NULL);
6525
Eric Laurent59255e42011-07-27 19:49:51 -07006526 checkSuspendOnAddEffectChain_l(chain);
6527
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006528 mEffectChains.add(chain);
6529
6530 return NO_ERROR;
6531}
6532
6533size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6534{
6535 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6536 LOGW_IF(mEffectChains.size() != 1,
6537 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6538 chain.get(), mEffectChains.size(), this);
6539 if (mEffectChains.size() == 1) {
6540 mEffectChains.removeAt(0);
6541 }
6542 return 0;
6543}
6544
Mathias Agopian65ab4712010-07-14 17:59:35 -07006545// ----------------------------------------------------------------------------
6546// EffectModule implementation
6547// ----------------------------------------------------------------------------
6548
6549#undef LOG_TAG
6550#define LOG_TAG "AudioFlinger::EffectModule"
6551
6552AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6553 const wp<AudioFlinger::EffectChain>& chain,
6554 effect_descriptor_t *desc,
6555 int id,
6556 int sessionId)
6557 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006558 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006559{
6560 LOGV("Constructor %p", this);
6561 int lStatus;
6562 sp<ThreadBase> thread = mThread.promote();
6563 if (thread == 0) {
6564 return;
6565 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006566
6567 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6568
6569 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006570 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006571
6572 if (mStatus != NO_ERROR) {
6573 return;
6574 }
6575 lStatus = init();
6576 if (lStatus < 0) {
6577 mStatus = lStatus;
6578 goto Error;
6579 }
6580
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006581 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6582 mPinned = true;
6583 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6585 return;
6586Error:
6587 EffectRelease(mEffectInterface);
6588 mEffectInterface = NULL;
6589 LOGV("Constructor Error %d", mStatus);
6590}
6591
6592AudioFlinger::EffectModule::~EffectModule()
6593{
6594 LOGV("Destructor %p", this);
6595 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006596 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6597 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6598 sp<ThreadBase> thread = mThread.promote();
6599 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006600 audio_stream_t *stream = thread->stream();
6601 if (stream != NULL) {
6602 stream->remove_audio_effect(stream, mEffectInterface);
6603 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006604 }
6605 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 // release effect engine
6607 EffectRelease(mEffectInterface);
6608 }
6609}
6610
6611status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6612{
6613 status_t status;
6614
6615 Mutex::Autolock _l(mLock);
6616 // First handle in mHandles has highest priority and controls the effect module
6617 int priority = handle->priority();
6618 size_t size = mHandles.size();
6619 sp<EffectHandle> h;
6620 size_t i;
6621 for (i = 0; i < size; i++) {
6622 h = mHandles[i].promote();
6623 if (h == 0) continue;
6624 if (h->priority() <= priority) break;
6625 }
6626 // if inserted in first place, move effect control from previous owner to this handle
6627 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006628 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006629 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006630 enabled = h->enabled();
6631 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006632 }
Eric Laurent59255e42011-07-27 19:49:51 -07006633 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634 status = NO_ERROR;
6635 } else {
6636 status = ALREADY_EXISTS;
6637 }
Eric Laurent59255e42011-07-27 19:49:51 -07006638 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006639 mHandles.insertAt(handle, i);
6640 return status;
6641}
6642
6643size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6644{
6645 Mutex::Autolock _l(mLock);
6646 size_t size = mHandles.size();
6647 size_t i;
6648 for (i = 0; i < size; i++) {
6649 if (mHandles[i] == handle) break;
6650 }
6651 if (i == size) {
6652 return size;
6653 }
Eric Laurent59255e42011-07-27 19:49:51 -07006654 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6655
6656 bool enabled = false;
6657 EffectHandle *hdl = handle.unsafe_get();
6658 if (hdl) {
6659 LOGV("removeHandle() unsafe_get OK");
6660 enabled = hdl->enabled();
6661 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006662 mHandles.removeAt(i);
6663 size = mHandles.size();
6664 // if removed from first place, move effect control from this handle to next in line
6665 if (i == 0 && size != 0) {
6666 sp<EffectHandle> h = mHandles[0].promote();
6667 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006668 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006669 }
6670 }
6671
Eric Laurentec437d82011-07-26 20:54:46 -07006672 // Prevent calls to process() and other functions on effect interface from now on.
6673 // The effect engine will be released by the destructor when the last strong reference on
6674 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006675 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006676 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006677 }
6678
Mathias Agopian65ab4712010-07-14 17:59:35 -07006679 return size;
6680}
6681
Eric Laurent59255e42011-07-27 19:49:51 -07006682sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6683{
6684 Mutex::Autolock _l(mLock);
6685 sp<EffectHandle> handle;
6686 if (mHandles.size() != 0) {
6687 handle = mHandles[0].promote();
6688 }
6689 return handle;
6690}
6691
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006692void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006693{
Eric Laurent59255e42011-07-27 19:49:51 -07006694 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006695 // keep a strong reference on this EffectModule to avoid calling the
6696 // destructor before we exit
6697 sp<EffectModule> keep(this);
6698 {
6699 sp<ThreadBase> thread = mThread.promote();
6700 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006701 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006702 }
6703 }
6704}
6705
6706void AudioFlinger::EffectModule::updateState() {
6707 Mutex::Autolock _l(mLock);
6708
6709 switch (mState) {
6710 case RESTART:
6711 reset_l();
6712 // FALL THROUGH
6713
6714 case STARTING:
6715 // clear auxiliary effect input buffer for next accumulation
6716 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6717 memset(mConfig.inputCfg.buffer.raw,
6718 0,
6719 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6720 }
6721 start_l();
6722 mState = ACTIVE;
6723 break;
6724 case STOPPING:
6725 stop_l();
6726 mDisableWaitCnt = mMaxDisableWaitCnt;
6727 mState = STOPPED;
6728 break;
6729 case STOPPED:
6730 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6731 // turn off sequence.
6732 if (--mDisableWaitCnt == 0) {
6733 reset_l();
6734 mState = IDLE;
6735 }
6736 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006737 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006738 break;
6739 }
6740}
6741
6742void AudioFlinger::EffectModule::process()
6743{
6744 Mutex::Autolock _l(mLock);
6745
Eric Laurentec437d82011-07-26 20:54:46 -07006746 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006747 mConfig.inputCfg.buffer.raw == NULL ||
6748 mConfig.outputCfg.buffer.raw == NULL) {
6749 return;
6750 }
6751
Eric Laurent8f45bd72010-08-31 13:50:07 -07006752 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006753 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6754 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6755 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6756 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006757 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 }
6759
6760 // do the actual processing in the effect engine
6761 int ret = (*mEffectInterface)->process(mEffectInterface,
6762 &mConfig.inputCfg.buffer,
6763 &mConfig.outputCfg.buffer);
6764
6765 // force transition to IDLE state when engine is ready
6766 if (mState == STOPPED && ret == -ENODATA) {
6767 mDisableWaitCnt = 1;
6768 }
6769
6770 // clear auxiliary effect input buffer for next accumulation
6771 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006772 memset(mConfig.inputCfg.buffer.raw, 0,
6773 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006774 }
6775 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006776 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6777 // If an insert effect is idle and input buffer is different from output buffer,
6778 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006779 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006780 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006781 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6782 int16_t *in = mConfig.inputCfg.buffer.s16;
6783 int16_t *out = mConfig.outputCfg.buffer.s16;
6784 for (size_t i = 0; i < frameCnt; i++) {
6785 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006786 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006787 }
6788 }
6789}
6790
6791void AudioFlinger::EffectModule::reset_l()
6792{
6793 if (mEffectInterface == NULL) {
6794 return;
6795 }
6796 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6797}
6798
6799status_t AudioFlinger::EffectModule::configure()
6800{
6801 uint32_t channels;
6802 if (mEffectInterface == NULL) {
6803 return NO_INIT;
6804 }
6805
6806 sp<ThreadBase> thread = mThread.promote();
6807 if (thread == 0) {
6808 return DEAD_OBJECT;
6809 }
6810
6811 // TODO: handle configuration of effects replacing track process
6812 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006813 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006814 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006815 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006816 }
6817
6818 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006819 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006820 } else {
6821 mConfig.inputCfg.channels = channels;
6822 }
6823 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006824 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6825 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006826 mConfig.inputCfg.samplingRate = thread->sampleRate();
6827 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6828 mConfig.inputCfg.bufferProvider.cookie = NULL;
6829 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6830 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6831 mConfig.outputCfg.bufferProvider.cookie = NULL;
6832 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6833 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6834 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6835 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006836 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006837 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006838 // - in other sessions:
6839 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6840 // other effect: overwrites output buffer: input buffer == output buffer
6841 // Auxiliary effect:
6842 // accumulates in output buffer: input buffer != output buffer
6843 // Therefore: accumulate <=> input buffer != output buffer
6844 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6845 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6846 } else {
6847 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6848 }
6849 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6850 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6851 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6852 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6853
Eric Laurentde070132010-07-13 04:45:46 -07006854 LOGV("configure() %p thread %p buffer %p framecount %d",
6855 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6856
Mathias Agopian65ab4712010-07-14 17:59:35 -07006857 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006858 uint32_t size = sizeof(int);
6859 status_t status = (*mEffectInterface)->command(mEffectInterface,
6860 EFFECT_CMD_CONFIGURE,
6861 sizeof(effect_config_t),
6862 &mConfig,
6863 &size,
6864 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006865 if (status == 0) {
6866 status = cmdStatus;
6867 }
6868
6869 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6870 (1000 * mConfig.outputCfg.buffer.frameCount);
6871
6872 return status;
6873}
6874
6875status_t AudioFlinger::EffectModule::init()
6876{
6877 Mutex::Autolock _l(mLock);
6878 if (mEffectInterface == NULL) {
6879 return NO_INIT;
6880 }
6881 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006882 uint32_t size = sizeof(status_t);
6883 status_t status = (*mEffectInterface)->command(mEffectInterface,
6884 EFFECT_CMD_INIT,
6885 0,
6886 NULL,
6887 &size,
6888 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889 if (status == 0) {
6890 status = cmdStatus;
6891 }
6892 return status;
6893}
6894
6895status_t AudioFlinger::EffectModule::start_l()
6896{
6897 if (mEffectInterface == NULL) {
6898 return NO_INIT;
6899 }
6900 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006901 uint32_t size = sizeof(status_t);
6902 status_t status = (*mEffectInterface)->command(mEffectInterface,
6903 EFFECT_CMD_ENABLE,
6904 0,
6905 NULL,
6906 &size,
6907 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006908 if (status == 0) {
6909 status = cmdStatus;
6910 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006911 if (status == 0 &&
6912 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6913 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6914 sp<ThreadBase> thread = mThread.promote();
6915 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006916 audio_stream_t *stream = thread->stream();
6917 if (stream != NULL) {
6918 stream->add_audio_effect(stream, mEffectInterface);
6919 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006920 }
6921 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006922 return status;
6923}
6924
Eric Laurentec437d82011-07-26 20:54:46 -07006925status_t AudioFlinger::EffectModule::stop()
6926{
6927 Mutex::Autolock _l(mLock);
6928 return stop_l();
6929}
6930
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931status_t AudioFlinger::EffectModule::stop_l()
6932{
6933 if (mEffectInterface == NULL) {
6934 return NO_INIT;
6935 }
6936 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006937 uint32_t size = sizeof(status_t);
6938 status_t status = (*mEffectInterface)->command(mEffectInterface,
6939 EFFECT_CMD_DISABLE,
6940 0,
6941 NULL,
6942 &size,
6943 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006944 if (status == 0) {
6945 status = cmdStatus;
6946 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006947 if (status == 0 &&
6948 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6949 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6950 sp<ThreadBase> thread = mThread.promote();
6951 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006952 audio_stream_t *stream = thread->stream();
6953 if (stream != NULL) {
6954 stream->remove_audio_effect(stream, mEffectInterface);
6955 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006956 }
6957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006958 return status;
6959}
6960
Eric Laurent25f43952010-07-28 05:40:18 -07006961status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6962 uint32_t cmdSize,
6963 void *pCmdData,
6964 uint32_t *replySize,
6965 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966{
6967 Mutex::Autolock _l(mLock);
6968// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6969
Eric Laurentec437d82011-07-26 20:54:46 -07006970 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006971 return NO_INIT;
6972 }
Eric Laurent25f43952010-07-28 05:40:18 -07006973 status_t status = (*mEffectInterface)->command(mEffectInterface,
6974 cmdCode,
6975 cmdSize,
6976 pCmdData,
6977 replySize,
6978 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006979 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006980 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006981 for (size_t i = 1; i < mHandles.size(); i++) {
6982 sp<EffectHandle> h = mHandles[i].promote();
6983 if (h != 0) {
6984 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6985 }
6986 }
6987 }
6988 return status;
6989}
6990
6991status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6992{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006993
Mathias Agopian65ab4712010-07-14 17:59:35 -07006994 Mutex::Autolock _l(mLock);
6995 LOGV("setEnabled %p enabled %d", this, enabled);
6996
6997 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006998 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6999 if (enabled && status != NO_ERROR) {
7000 return status;
7001 }
7002
Mathias Agopian65ab4712010-07-14 17:59:35 -07007003 switch (mState) {
7004 // going from disabled to enabled
7005 case IDLE:
7006 mState = STARTING;
7007 break;
7008 case STOPPED:
7009 mState = RESTART;
7010 break;
7011 case STOPPING:
7012 mState = ACTIVE;
7013 break;
7014
7015 // going from enabled to disabled
7016 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007017 mState = STOPPED;
7018 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007019 case STARTING:
7020 mState = IDLE;
7021 break;
7022 case ACTIVE:
7023 mState = STOPPING;
7024 break;
Eric Laurentec437d82011-07-26 20:54:46 -07007025 case DESTROYED:
7026 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07007027 }
7028 for (size_t i = 1; i < mHandles.size(); i++) {
7029 sp<EffectHandle> h = mHandles[i].promote();
7030 if (h != 0) {
7031 h->setEnabled(enabled);
7032 }
7033 }
7034 }
7035 return NO_ERROR;
7036}
7037
7038bool AudioFlinger::EffectModule::isEnabled()
7039{
7040 switch (mState) {
7041 case RESTART:
7042 case STARTING:
7043 case ACTIVE:
7044 return true;
7045 case IDLE:
7046 case STOPPING:
7047 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007048 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007049 default:
7050 return false;
7051 }
7052}
7053
Eric Laurent8f45bd72010-08-31 13:50:07 -07007054bool AudioFlinger::EffectModule::isProcessEnabled()
7055{
7056 switch (mState) {
7057 case RESTART:
7058 case ACTIVE:
7059 case STOPPING:
7060 case STOPPED:
7061 return true;
7062 case IDLE:
7063 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007064 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007065 default:
7066 return false;
7067 }
7068}
7069
Mathias Agopian65ab4712010-07-14 17:59:35 -07007070status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7071{
7072 Mutex::Autolock _l(mLock);
7073 status_t status = NO_ERROR;
7074
7075 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7076 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007077 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007078 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7079 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007080 status_t cmdStatus;
7081 uint32_t volume[2];
7082 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007083 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007084 volume[0] = *left;
7085 volume[1] = *right;
7086 if (controller) {
7087 pVolume = volume;
7088 }
Eric Laurent25f43952010-07-28 05:40:18 -07007089 status = (*mEffectInterface)->command(mEffectInterface,
7090 EFFECT_CMD_SET_VOLUME,
7091 size,
7092 volume,
7093 &size,
7094 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007095 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7096 *left = volume[0];
7097 *right = volume[1];
7098 }
7099 }
7100 return status;
7101}
7102
7103status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7104{
7105 Mutex::Autolock _l(mLock);
7106 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007107 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7108 // audio pre processing modules on RecordThread can receive both output and
7109 // input device indication in the same call
7110 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7111 if (dev) {
7112 status_t cmdStatus;
7113 uint32_t size = sizeof(status_t);
7114
7115 status = (*mEffectInterface)->command(mEffectInterface,
7116 EFFECT_CMD_SET_DEVICE,
7117 sizeof(uint32_t),
7118 &dev,
7119 &size,
7120 &cmdStatus);
7121 if (status == NO_ERROR) {
7122 status = cmdStatus;
7123 }
7124 }
7125 dev = device & AUDIO_DEVICE_IN_ALL;
7126 if (dev) {
7127 status_t cmdStatus;
7128 uint32_t size = sizeof(status_t);
7129
7130 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7131 EFFECT_CMD_SET_INPUT_DEVICE,
7132 sizeof(uint32_t),
7133 &dev,
7134 &size,
7135 &cmdStatus);
7136 if (status2 == NO_ERROR) {
7137 status2 = cmdStatus;
7138 }
7139 if (status == NO_ERROR) {
7140 status = status2;
7141 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007142 }
7143 }
7144 return status;
7145}
7146
7147status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
7148{
7149 Mutex::Autolock _l(mLock);
7150 status_t status = NO_ERROR;
7151 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007152 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007153 uint32_t size = sizeof(status_t);
7154 status = (*mEffectInterface)->command(mEffectInterface,
7155 EFFECT_CMD_SET_AUDIO_MODE,
7156 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07007157 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007158 &size,
7159 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007160 if (status == NO_ERROR) {
7161 status = cmdStatus;
7162 }
7163 }
7164 return status;
7165}
7166
Eric Laurent59255e42011-07-27 19:49:51 -07007167void AudioFlinger::EffectModule::setSuspended(bool suspended)
7168{
7169 Mutex::Autolock _l(mLock);
7170 mSuspended = suspended;
7171}
7172bool AudioFlinger::EffectModule::suspended()
7173{
7174 Mutex::Autolock _l(mLock);
7175 return mSuspended;
7176}
7177
Mathias Agopian65ab4712010-07-14 17:59:35 -07007178status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7179{
7180 const size_t SIZE = 256;
7181 char buffer[SIZE];
7182 String8 result;
7183
7184 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7185 result.append(buffer);
7186
7187 bool locked = tryLock(mLock);
7188 // failed to lock - AudioFlinger is probably deadlocked
7189 if (!locked) {
7190 result.append("\t\tCould not lock Fx mutex:\n");
7191 }
7192
7193 result.append("\t\tSession Status State Engine:\n");
7194 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7195 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7196 result.append(buffer);
7197
7198 result.append("\t\tDescriptor:\n");
7199 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7200 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7201 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7202 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7203 result.append(buffer);
7204 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7205 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7206 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7207 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7208 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007209 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007210 mDescriptor.apiVersion,
7211 mDescriptor.flags);
7212 result.append(buffer);
7213 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7214 mDescriptor.name);
7215 result.append(buffer);
7216 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7217 mDescriptor.implementor);
7218 result.append(buffer);
7219
7220 result.append("\t\t- Input configuration:\n");
7221 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7222 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7223 (uint32_t)mConfig.inputCfg.buffer.raw,
7224 mConfig.inputCfg.buffer.frameCount,
7225 mConfig.inputCfg.samplingRate,
7226 mConfig.inputCfg.channels,
7227 mConfig.inputCfg.format);
7228 result.append(buffer);
7229
7230 result.append("\t\t- Output configuration:\n");
7231 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7232 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7233 (uint32_t)mConfig.outputCfg.buffer.raw,
7234 mConfig.outputCfg.buffer.frameCount,
7235 mConfig.outputCfg.samplingRate,
7236 mConfig.outputCfg.channels,
7237 mConfig.outputCfg.format);
7238 result.append(buffer);
7239
7240 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7241 result.append(buffer);
7242 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7243 for (size_t i = 0; i < mHandles.size(); ++i) {
7244 sp<EffectHandle> handle = mHandles[i].promote();
7245 if (handle != 0) {
7246 handle->dump(buffer, SIZE);
7247 result.append(buffer);
7248 }
7249 }
7250
7251 result.append("\n");
7252
7253 write(fd, result.string(), result.length());
7254
7255 if (locked) {
7256 mLock.unlock();
7257 }
7258
7259 return NO_ERROR;
7260}
7261
7262// ----------------------------------------------------------------------------
7263// EffectHandle implementation
7264// ----------------------------------------------------------------------------
7265
7266#undef LOG_TAG
7267#define LOG_TAG "AudioFlinger::EffectHandle"
7268
7269AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7270 const sp<AudioFlinger::Client>& client,
7271 const sp<IEffectClient>& effectClient,
7272 int32_t priority)
7273 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007274 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007275 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007276{
7277 LOGV("constructor %p", this);
7278
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007279 if (client == 0) {
7280 return;
7281 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007282 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7283 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7284 if (mCblkMemory != 0) {
7285 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7286
7287 if (mCblk) {
7288 new(mCblk) effect_param_cblk_t();
7289 mBuffer = (uint8_t *)mCblk + bufOffset;
7290 }
7291 } else {
7292 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
7293 return;
7294 }
7295}
7296
7297AudioFlinger::EffectHandle::~EffectHandle()
7298{
7299 LOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007300 disconnect(false);
Eric Laurent59255e42011-07-27 19:49:51 -07007301 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007302}
7303
7304status_t AudioFlinger::EffectHandle::enable()
7305{
Eric Laurent59255e42011-07-27 19:49:51 -07007306 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007307 if (!mHasControl) return INVALID_OPERATION;
7308 if (mEffect == 0) return DEAD_OBJECT;
7309
Eric Laurentdb7c0792011-08-10 10:37:50 -07007310 if (mEnabled) {
7311 return NO_ERROR;
7312 }
7313
Eric Laurent59255e42011-07-27 19:49:51 -07007314 mEnabled = true;
7315
7316 sp<ThreadBase> thread = mEffect->thread().promote();
7317 if (thread != 0) {
7318 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7319 }
7320
7321 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7322 if (mEffect->suspended()) {
7323 return NO_ERROR;
7324 }
7325
Eric Laurentdb7c0792011-08-10 10:37:50 -07007326 status_t status = mEffect->setEnabled(true);
7327 if (status != NO_ERROR) {
7328 if (thread != 0) {
7329 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7330 }
7331 mEnabled = false;
7332 }
7333 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007334}
7335
7336status_t AudioFlinger::EffectHandle::disable()
7337{
Eric Laurent59255e42011-07-27 19:49:51 -07007338 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007339 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007340 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341
Eric Laurentdb7c0792011-08-10 10:37:50 -07007342 if (!mEnabled) {
7343 return NO_ERROR;
7344 }
Eric Laurent59255e42011-07-27 19:49:51 -07007345 mEnabled = false;
7346
7347 if (mEffect->suspended()) {
7348 return NO_ERROR;
7349 }
7350
7351 status_t status = mEffect->setEnabled(false);
7352
7353 sp<ThreadBase> thread = mEffect->thread().promote();
7354 if (thread != 0) {
7355 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7356 }
7357
7358 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007359}
7360
7361void AudioFlinger::EffectHandle::disconnect()
7362{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007363 disconnect(true);
7364}
7365
7366void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
7367{
7368 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007369 if (mEffect == 0) {
7370 return;
7371 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007372 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07007373
Eric Laurentdb7c0792011-08-10 10:37:50 -07007374 if (mEnabled) {
7375 sp<ThreadBase> thread = mEffect->thread().promote();
7376 if (thread != 0) {
7377 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7378 }
Eric Laurent59255e42011-07-27 19:49:51 -07007379 }
7380
Mathias Agopian65ab4712010-07-14 17:59:35 -07007381 // release sp on module => module destructor can be called now
7382 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007383 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007384 if (mCblk) {
7385 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7386 }
7387 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07007388 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7389 mClient.clear();
7390 }
7391}
7392
Eric Laurent25f43952010-07-28 05:40:18 -07007393status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7394 uint32_t cmdSize,
7395 void *pCmdData,
7396 uint32_t *replySize,
7397 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007398{
Eric Laurent25f43952010-07-28 05:40:18 -07007399// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
7400// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401
7402 // only get parameter command is permitted for applications not controlling the effect
7403 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7404 return INVALID_OPERATION;
7405 }
7406 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007407 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007408
7409 // handle commands that are not forwarded transparently to effect engine
7410 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7411 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7412 // no risk to block the whole media server process or mixer threads is we are stuck here
7413 Mutex::Autolock _l(mCblk->lock);
7414 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7415 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7416 mCblk->serverIndex = 0;
7417 mCblk->clientIndex = 0;
7418 return BAD_VALUE;
7419 }
7420 status_t status = NO_ERROR;
7421 while (mCblk->serverIndex < mCblk->clientIndex) {
7422 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007423 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 int *p = (int *)(mBuffer + mCblk->serverIndex);
7425 int size = *p++;
7426 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
7427 LOGW("command(): invalid parameter block size");
7428 break;
7429 }
7430 effect_param_t *param = (effect_param_t *)p;
7431 if (param->psize == 0 || param->vsize == 0) {
7432 LOGW("command(): null parameter or value size");
7433 mCblk->serverIndex += size;
7434 continue;
7435 }
Eric Laurent25f43952010-07-28 05:40:18 -07007436 uint32_t psize = sizeof(effect_param_t) +
7437 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7438 param->vsize;
7439 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7440 psize,
7441 p,
7442 &rsize,
7443 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007444 // stop at first error encountered
7445 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007447 *(int *)pReplyData = reply;
7448 break;
7449 } else if (reply != NO_ERROR) {
7450 *(int *)pReplyData = reply;
7451 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 }
7453 mCblk->serverIndex += size;
7454 }
7455 mCblk->serverIndex = 0;
7456 mCblk->clientIndex = 0;
7457 return status;
7458 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007459 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007460 return enable();
7461 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007462 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007463 return disable();
7464 }
7465
7466 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7467}
7468
7469sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7470 return mCblkMemory;
7471}
7472
Eric Laurent59255e42011-07-27 19:49:51 -07007473void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007474{
7475 LOGV("setControl %p control %d", this, hasControl);
7476
7477 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007478 mEnabled = enabled;
7479
Mathias Agopian65ab4712010-07-14 17:59:35 -07007480 if (signal && mEffectClient != 0) {
7481 mEffectClient->controlStatusChanged(hasControl);
7482 }
7483}
7484
Eric Laurent25f43952010-07-28 05:40:18 -07007485void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7486 uint32_t cmdSize,
7487 void *pCmdData,
7488 uint32_t replySize,
7489 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007490{
7491 if (mEffectClient != 0) {
7492 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7493 }
7494}
7495
7496
7497
7498void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7499{
7500 if (mEffectClient != 0) {
7501 mEffectClient->enableStatusChanged(enabled);
7502 }
7503}
7504
7505status_t AudioFlinger::EffectHandle::onTransact(
7506 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7507{
7508 return BnEffect::onTransact(code, data, reply, flags);
7509}
7510
7511
7512void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7513{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007514 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007515
7516 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7517 (mClient == NULL) ? getpid() : mClient->pid(),
7518 mPriority,
7519 mHasControl,
7520 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007521 mCblk ? mCblk->clientIndex : 0,
7522 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007523 );
7524
7525 if (locked) {
7526 mCblk->lock.unlock();
7527 }
7528}
7529
7530#undef LOG_TAG
7531#define LOG_TAG "AudioFlinger::EffectChain"
7532
7533AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7534 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07007535 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
7536 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7537 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007538{
Dima Zavinfce7a472011-04-19 22:30:36 -07007539 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007540}
7541
7542AudioFlinger::EffectChain::~EffectChain()
7543{
7544 if (mOwnInBuffer) {
7545 delete mInBuffer;
7546 }
7547
7548}
7549
Eric Laurent59255e42011-07-27 19:49:51 -07007550// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007551sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007552{
7553 sp<EffectModule> effect;
7554 size_t size = mEffects.size();
7555
7556 for (size_t i = 0; i < size; i++) {
7557 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7558 effect = mEffects[i];
7559 break;
7560 }
7561 }
7562 return effect;
7563}
7564
Eric Laurent59255e42011-07-27 19:49:51 -07007565// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007566sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007567{
7568 sp<EffectModule> effect;
7569 size_t size = mEffects.size();
7570
7571 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007572 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7573 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007574 effect = mEffects[i];
7575 break;
7576 }
7577 }
7578 return effect;
7579}
7580
Eric Laurent59255e42011-07-27 19:49:51 -07007581// getEffectFromType_l() must be called with ThreadBase::mLock held
7582sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7583 const effect_uuid_t *type)
7584{
7585 sp<EffectModule> effect;
7586 size_t size = mEffects.size();
7587
7588 for (size_t i = 0; i < size; i++) {
7589 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7590 effect = mEffects[i];
7591 break;
7592 }
7593 }
7594 return effect;
7595}
7596
Mathias Agopian65ab4712010-07-14 17:59:35 -07007597// Must be called with EffectChain::mLock locked
7598void AudioFlinger::EffectChain::process_l()
7599{
Eric Laurentdac69112010-09-28 14:09:57 -07007600 sp<ThreadBase> thread = mThread.promote();
7601 if (thread == 0) {
7602 LOGW("process_l(): cannot promote mixer thread");
7603 return;
7604 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007605 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7606 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07007607 bool tracksOnSession = false;
7608 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07007609 tracksOnSession = (trackCnt() != 0);
7610 }
7611
7612 // if no track is active, input buffer must be cleared here as the mixer process
7613 // will not do it
7614 if (tracksOnSession &&
7615 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007616 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07007617 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07007618 }
7619
Mathias Agopian65ab4712010-07-14 17:59:35 -07007620 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07007621 // do not process effect if no track is present in same audio session
7622 if (isGlobalSession || tracksOnSession) {
7623 for (size_t i = 0; i < size; i++) {
7624 mEffects[i]->process();
7625 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007626 }
7627 for (size_t i = 0; i < size; i++) {
7628 mEffects[i]->updateState();
7629 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007630}
7631
Eric Laurentcab11242010-07-15 12:50:15 -07007632// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007633status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007634{
7635 effect_descriptor_t desc = effect->desc();
7636 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7637
7638 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007639 effect->setChain(this);
7640 sp<ThreadBase> thread = mThread.promote();
7641 if (thread == 0) {
7642 return NO_INIT;
7643 }
7644 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007645
7646 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7647 // Auxiliary effects are inserted at the beginning of mEffects vector as
7648 // they are processed first and accumulated in chain input buffer
7649 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007650
Mathias Agopian65ab4712010-07-14 17:59:35 -07007651 // the input buffer for auxiliary effect contains mono samples in
7652 // 32 bit format. This is to avoid saturation in AudoMixer
7653 // accumulation stage. Saturation is done in EffectModule::process() before
7654 // calling the process in effect engine
7655 size_t numSamples = thread->frameCount();
7656 int32_t *buffer = new int32_t[numSamples];
7657 memset(buffer, 0, numSamples * sizeof(int32_t));
7658 effect->setInBuffer((int16_t *)buffer);
7659 // auxiliary effects output samples to chain input buffer for further processing
7660 // by insert effects
7661 effect->setOutBuffer(mInBuffer);
7662 } else {
7663 // Insert effects are inserted at the end of mEffects vector as they are processed
7664 // after track and auxiliary effects.
7665 // Insert effect order as a function of indicated preference:
7666 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7667 // another effect is present
7668 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7669 // last effect claiming first position
7670 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7671 // first effect claiming last position
7672 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7673 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7674 // already present
7675
7676 int size = (int)mEffects.size();
7677 int idx_insert = size;
7678 int idx_insert_first = -1;
7679 int idx_insert_last = -1;
7680
7681 for (int i = 0; i < size; i++) {
7682 effect_descriptor_t d = mEffects[i]->desc();
7683 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7684 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7685 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7686 // check invalid effect chaining combinations
7687 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7688 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007689 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007690 return INVALID_OPERATION;
7691 }
7692 // remember position of first insert effect and by default
7693 // select this as insert position for new effect
7694 if (idx_insert == size) {
7695 idx_insert = i;
7696 }
7697 // remember position of last insert effect claiming
7698 // first position
7699 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7700 idx_insert_first = i;
7701 }
7702 // remember position of first insert effect claiming
7703 // last position
7704 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7705 idx_insert_last == -1) {
7706 idx_insert_last = i;
7707 }
7708 }
7709 }
7710
7711 // modify idx_insert from first position if needed
7712 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7713 if (idx_insert_last != -1) {
7714 idx_insert = idx_insert_last;
7715 } else {
7716 idx_insert = size;
7717 }
7718 } else {
7719 if (idx_insert_first != -1) {
7720 idx_insert = idx_insert_first + 1;
7721 }
7722 }
7723
7724 // always read samples from chain input buffer
7725 effect->setInBuffer(mInBuffer);
7726
7727 // if last effect in the chain, output samples to chain
7728 // output buffer, otherwise to chain input buffer
7729 if (idx_insert == size) {
7730 if (idx_insert != 0) {
7731 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7732 mEffects[idx_insert-1]->configure();
7733 }
7734 effect->setOutBuffer(mOutBuffer);
7735 } else {
7736 effect->setOutBuffer(mInBuffer);
7737 }
7738 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007739
Eric Laurentcab11242010-07-15 12:50:15 -07007740 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007741 }
7742 effect->configure();
7743 return NO_ERROR;
7744}
7745
Eric Laurentcab11242010-07-15 12:50:15 -07007746// removeEffect_l() must be called with PlaybackThread::mLock held
7747size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007748{
7749 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007750 int size = (int)mEffects.size();
7751 int i;
7752 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7753
7754 for (i = 0; i < size; i++) {
7755 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007756 // calling stop here will remove pre-processing effect from the audio HAL.
7757 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7758 // the middle of a read from audio HAL
7759 mEffects[i]->stop();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7761 delete[] effect->inBuffer();
7762 } else {
7763 if (i == size - 1 && i != 0) {
7764 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7765 mEffects[i - 1]->configure();
7766 }
7767 }
7768 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07007769 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007770 break;
7771 }
7772 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007773
7774 return mEffects.size();
7775}
7776
Eric Laurentcab11242010-07-15 12:50:15 -07007777// setDevice_l() must be called with PlaybackThread::mLock held
7778void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007779{
7780 size_t size = mEffects.size();
7781 for (size_t i = 0; i < size; i++) {
7782 mEffects[i]->setDevice(device);
7783 }
7784}
7785
Eric Laurentcab11242010-07-15 12:50:15 -07007786// setMode_l() must be called with PlaybackThread::mLock held
7787void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007788{
7789 size_t size = mEffects.size();
7790 for (size_t i = 0; i < size; i++) {
7791 mEffects[i]->setMode(mode);
7792 }
7793}
7794
Eric Laurentcab11242010-07-15 12:50:15 -07007795// setVolume_l() must be called with PlaybackThread::mLock held
7796bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007797{
7798 uint32_t newLeft = *left;
7799 uint32_t newRight = *right;
7800 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007801 int ctrlIdx = -1;
7802 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803
Eric Laurentcab11242010-07-15 12:50:15 -07007804 // first update volume controller
7805 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007806 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007807 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7808 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007809 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007810 break;
7811 }
7812 }
7813
7814 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007815 if (hasControl) {
7816 *left = mNewLeftVolume;
7817 *right = mNewRightVolume;
7818 }
7819 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007820 }
7821
7822 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007823 mLeftVolume = newLeft;
7824 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007825
7826 // second get volume update from volume controller
7827 if (ctrlIdx >= 0) {
7828 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007829 mNewLeftVolume = newLeft;
7830 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007831 }
7832 // then indicate volume to all other effects in chain.
7833 // Pass altered volume to effects before volume controller
7834 // and requested volume to effects after controller
7835 uint32_t lVol = newLeft;
7836 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007837
Mathias Agopian65ab4712010-07-14 17:59:35 -07007838 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007839 if ((int)i == ctrlIdx) continue;
7840 // this also works for ctrlIdx == -1 when there is no volume controller
7841 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842 lVol = *left;
7843 rVol = *right;
7844 }
7845 mEffects[i]->setVolume(&lVol, &rVol, false);
7846 }
7847 *left = newLeft;
7848 *right = newRight;
7849
7850 return hasControl;
7851}
7852
Mathias Agopian65ab4712010-07-14 17:59:35 -07007853status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7854{
7855 const size_t SIZE = 256;
7856 char buffer[SIZE];
7857 String8 result;
7858
7859 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7860 result.append(buffer);
7861
7862 bool locked = tryLock(mLock);
7863 // failed to lock - AudioFlinger is probably deadlocked
7864 if (!locked) {
7865 result.append("\tCould not lock mutex:\n");
7866 }
7867
Eric Laurentcab11242010-07-15 12:50:15 -07007868 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7869 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007870 mEffects.size(),
7871 (uint32_t)mInBuffer,
7872 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007873 mActiveTrackCnt);
7874 result.append(buffer);
7875 write(fd, result.string(), result.size());
7876
7877 for (size_t i = 0; i < mEffects.size(); ++i) {
7878 sp<EffectModule> effect = mEffects[i];
7879 if (effect != 0) {
7880 effect->dump(fd, args);
7881 }
7882 }
7883
7884 if (locked) {
7885 mLock.unlock();
7886 }
7887
7888 return NO_ERROR;
7889}
7890
Eric Laurent59255e42011-07-27 19:49:51 -07007891// must be called with ThreadBase::mLock held
7892void AudioFlinger::EffectChain::setEffectSuspended_l(
7893 const effect_uuid_t *type, bool suspend)
7894{
7895 sp<SuspendedEffectDesc> desc;
7896 // use effect type UUID timelow as key as there is no real risk of identical
7897 // timeLow fields among effect type UUIDs.
7898 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7899 if (suspend) {
7900 if (index >= 0) {
7901 desc = mSuspendedEffects.valueAt(index);
7902 } else {
7903 desc = new SuspendedEffectDesc();
7904 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7905 mSuspendedEffects.add(type->timeLow, desc);
7906 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7907 }
7908 if (desc->mRefCount++ == 0) {
7909 sp<EffectModule> effect = getEffectIfEnabled(type);
7910 if (effect != 0) {
7911 desc->mEffect = effect;
7912 effect->setSuspended(true);
7913 effect->setEnabled(false);
7914 }
7915 }
7916 } else {
7917 if (index < 0) {
7918 return;
7919 }
7920 desc = mSuspendedEffects.valueAt(index);
7921 if (desc->mRefCount <= 0) {
7922 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7923 desc->mRefCount = 1;
7924 }
7925 if (--desc->mRefCount == 0) {
7926 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7927 if (desc->mEffect != 0) {
7928 sp<EffectModule> effect = desc->mEffect.promote();
7929 if (effect != 0) {
7930 effect->setSuspended(false);
7931 sp<EffectHandle> handle = effect->controlHandle();
7932 if (handle != 0) {
7933 effect->setEnabled(handle->enabled());
7934 }
7935 }
7936 desc->mEffect.clear();
7937 }
7938 mSuspendedEffects.removeItemsAt(index);
7939 }
7940 }
7941}
7942
7943// must be called with ThreadBase::mLock held
7944void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7945{
7946 sp<SuspendedEffectDesc> desc;
7947
7948 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7949 if (suspend) {
7950 if (index >= 0) {
7951 desc = mSuspendedEffects.valueAt(index);
7952 } else {
7953 desc = new SuspendedEffectDesc();
7954 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7955 LOGV("setEffectSuspendedAll_l() add entry for 0");
7956 }
7957 if (desc->mRefCount++ == 0) {
7958 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7959 for (size_t i = 0; i < effects.size(); i++) {
7960 setEffectSuspended_l(&effects[i]->desc().type, true);
7961 }
7962 }
7963 } else {
7964 if (index < 0) {
7965 return;
7966 }
7967 desc = mSuspendedEffects.valueAt(index);
7968 if (desc->mRefCount <= 0) {
7969 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7970 desc->mRefCount = 1;
7971 }
7972 if (--desc->mRefCount == 0) {
7973 Vector<const effect_uuid_t *> types;
7974 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7975 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7976 continue;
7977 }
7978 types.add(&mSuspendedEffects.valueAt(i)->mType);
7979 }
7980 for (size_t i = 0; i < types.size(); i++) {
7981 setEffectSuspended_l(types[i], false);
7982 }
7983 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7984 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7985 }
7986 }
7987}
7988
Eric Laurent6bffdb82011-09-23 08:40:41 -07007989
7990// The volume effect is used for automated tests only
7991#ifndef OPENSL_ES_H_
7992static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7993 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7994const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7995#endif //OPENSL_ES_H_
7996
Eric Laurentdb7c0792011-08-10 10:37:50 -07007997bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7998{
7999 // auxiliary effects and visualizer are never suspended on output mix
8000 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
8001 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07008002 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
8003 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008004 return false;
8005 }
8006 return true;
8007}
8008
Eric Laurent59255e42011-07-27 19:49:51 -07008009Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
8010{
8011 Vector< sp<EffectModule> > effects;
8012 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07008013 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07008014 continue;
8015 }
8016 effects.add(mEffects[i]);
8017 }
8018 return effects;
8019}
8020
8021sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
8022 const effect_uuid_t *type)
8023{
8024 sp<EffectModule> effect;
8025 effect = getEffectFromType_l(type);
8026 if (effect != 0 && !effect->isEnabled()) {
8027 effect.clear();
8028 }
8029 return effect;
8030}
8031
8032void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
8033 bool enabled)
8034{
8035 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
8036 if (enabled) {
8037 if (index < 0) {
8038 // if the effect is not suspend check if all effects are suspended
8039 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8040 if (index < 0) {
8041 return;
8042 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008043 if (!isEffectEligibleForSuspend(effect->desc())) {
8044 return;
8045 }
Eric Laurent59255e42011-07-27 19:49:51 -07008046 setEffectSuspended_l(&effect->desc().type, enabled);
8047 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008048 if (index < 0) {
8049 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
8050 return;
8051 }
Eric Laurent59255e42011-07-27 19:49:51 -07008052 }
8053 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
8054 effect->desc().type.timeLow);
8055 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8056 // if effect is requested to suspended but was not yet enabled, supend it now.
8057 if (desc->mEffect == 0) {
8058 desc->mEffect = effect;
8059 effect->setEnabled(false);
8060 effect->setSuspended(true);
8061 }
8062 } else {
8063 if (index < 0) {
8064 return;
8065 }
8066 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
8067 effect->desc().type.timeLow);
8068 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8069 desc->mEffect.clear();
8070 effect->setSuspended(false);
8071 }
8072}
8073
Mathias Agopian65ab4712010-07-14 17:59:35 -07008074#undef LOG_TAG
8075#define LOG_TAG "AudioFlinger"
8076
8077// ----------------------------------------------------------------------------
8078
8079status_t AudioFlinger::onTransact(
8080 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8081{
8082 return BnAudioFlinger::onTransact(code, data, reply, flags);
8083}
8084
Mathias Agopian65ab4712010-07-14 17:59:35 -07008085}; // namespace android