blob: 75ddc4680eb1e99530a4410501be4a4e10a88918 [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
Mathias Agopian65ab4712010-07-14 17:59:35 -070093// ----------------------------------------------------------------------------
94
95static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070096 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
97 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
98 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
99 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700100}
101
102static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
105 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
106 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107}
108
Gloria Wang9ee159b2011-02-24 14:51:45 -0800109// To collect the amplifier usage
110static void addBatteryData(uint32_t params) {
111 sp<IBinder> binder =
112 defaultServiceManager()->getService(String16("media.player"));
113 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
114 if (service.get() == NULL) {
115 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
116 return;
117 }
118
119 service->addBatteryData(params);
120}
121
Dima Zavin799a70e2011-04-18 16:57:27 -0700122static int load_audio_interface(const char *if_name, const hw_module_t **mod,
123 audio_hw_device_t **dev)
124{
125 int rc;
126
127 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
128 if (rc)
129 goto out;
130
131 rc = audio_hw_device_open(*mod, dev);
132 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
133 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
134 if (rc)
135 goto out;
136
137 return 0;
138
139out:
140 *mod = NULL;
141 *dev = NULL;
142 return rc;
143}
144
145static const char *audio_interfaces[] = {
146 "primary",
147 "a2dp",
148 "usb",
149};
150#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
151
Mathias Agopian65ab4712010-07-14 17:59:35 -0700152// ----------------------------------------------------------------------------
153
154AudioFlinger::AudioFlinger()
155 : BnAudioFlinger(),
Mike J. Chen535235c2011-08-15 13:28:26 -0700156 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterVolumeSW(1.0f),
157 mMasterVolumeSupportLvl(MVS_NONE), mMasterMute(false), mNextUniqueId(1),
Jason Simmonsca426b42011-08-29 16:16:49 -0700158 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700159{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700160}
161
162void AudioFlinger::onFirstRef()
163{
Dima Zavin799a70e2011-04-18 16:57:27 -0700164 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700165
Eric Laurent93575202011-01-18 18:39:02 -0800166 Mutex::Autolock _l(mLock);
167
Dima Zavin799a70e2011-04-18 16:57:27 -0700168 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700169 mHardwareStatus = AUDIO_HW_IDLE;
170
Dima Zavin799a70e2011-04-18 16:57:27 -0700171 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
172 const hw_module_t *mod;
173 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700174
Dima Zavin799a70e2011-04-18 16:57:27 -0700175 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
176 if (rc)
177 continue;
178
179 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
180 mod->name, mod->id);
181 mAudioHwDevs.push(dev);
182
183 if (!mPrimaryHardwareDev) {
184 mPrimaryHardwareDev = dev;
185 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700186 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700187 }
188 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700189
190 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700191
Dima Zavin799a70e2011-04-18 16:57:27 -0700192 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
193 LOGE("Primary audio interface not found");
194 return;
195 }
196
Mike J. Chen535235c2011-08-15 13:28:26 -0700197 // Determine the level of master volume support the primary audio HAL has,
198 // and set the initial master volume at the same time.
199 float initialVolume = 1.0;
200 mMasterVolumeSupportLvl = MVS_NONE;
201 if (0 == mPrimaryHardwareDev->init_check(mPrimaryHardwareDev)) {
202 AutoMutex lock(mHardwareLock);
203 audio_hw_device_t *dev = mPrimaryHardwareDev;
204
205 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
206 if ((NULL != dev->get_master_volume) &&
207 (NO_ERROR == dev->get_master_volume(dev, &initialVolume))) {
208 mMasterVolumeSupportLvl = MVS_FULL;
209 } else {
210 mMasterVolumeSupportLvl = MVS_SETONLY;
211 initialVolume = 1.0;
212 }
213
214 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
215 if ((NULL == dev->set_master_volume) ||
216 (NO_ERROR != dev->set_master_volume(dev, initialVolume))) {
217 mMasterVolumeSupportLvl = MVS_NONE;
218 }
219 mHardwareStatus = AUDIO_HW_INIT;
220 }
221
222 // Set the mode for each audio HAL, and try to set the initial volume (if
223 // supported) for all of the non-primary audio HALs.
Dima Zavin799a70e2011-04-18 16:57:27 -0700224 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
225 audio_hw_device_t *dev = mAudioHwDevs[i];
226
227 mHardwareStatus = AUDIO_HW_INIT;
228 rc = dev->init_check(dev);
229 if (rc == 0) {
230 AutoMutex lock(mHardwareLock);
231
232 mMode = AUDIO_MODE_NORMAL;
233 mHardwareStatus = AUDIO_HW_SET_MODE;
234 dev->set_mode(dev, mMode);
Mike J. Chen535235c2011-08-15 13:28:26 -0700235
236 if ((dev != mPrimaryHardwareDev) &&
237 (NULL != dev->set_master_volume)) {
238 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
239 dev->set_master_volume(dev, initialVolume);
240 }
241
242 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavin799a70e2011-04-18 16:57:27 -0700243 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700244 }
Mike J. Chen535235c2011-08-15 13:28:26 -0700245
246 mMasterVolumeSW = (MVS_NONE == mMasterVolumeSupportLvl)
247 ? initialVolume
248 : 1.0;
249 mMasterVolume = initialVolume;
250 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700251}
252
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700253status_t AudioFlinger::initCheck() const
254{
255 Mutex::Autolock _l(mLock);
256 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
257 return NO_INIT;
258 return NO_ERROR;
259}
260
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261AudioFlinger::~AudioFlinger()
262{
Dima Zavin799a70e2011-04-18 16:57:27 -0700263 int num_devs = mAudioHwDevs.size();
264
Mathias Agopian65ab4712010-07-14 17:59:35 -0700265 while (!mRecordThreads.isEmpty()) {
266 // closeInput() will remove first entry from mRecordThreads
267 closeInput(mRecordThreads.keyAt(0));
268 }
269 while (!mPlaybackThreads.isEmpty()) {
270 // closeOutput() will remove first entry from mPlaybackThreads
271 closeOutput(mPlaybackThreads.keyAt(0));
272 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700273
274 for (int i = 0; i < num_devs; i++) {
275 audio_hw_device_t *dev = mAudioHwDevs[i];
276 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700277 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700278 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700279}
280
Dima Zavin799a70e2011-04-18 16:57:27 -0700281audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
282{
283 /* first matching HW device is returned */
284 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
285 audio_hw_device_t *dev = mAudioHwDevs[i];
286 if ((dev->get_supported_devices(dev) & devices) == devices)
287 return dev;
288 }
289 return NULL;
290}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700291
292status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
297
298 result.append("Clients:\n");
299 for (size_t i = 0; i < mClients.size(); ++i) {
300 wp<Client> wClient = mClients.valueAt(i);
301 if (wClient != 0) {
302 sp<Client> client = wClient.promote();
303 if (client != 0) {
304 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
305 result.append(buffer);
306 }
307 }
308 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700309
310 result.append("Global session refs:\n");
311 result.append(" session pid cnt\n");
312 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
313 AudioSessionRef *r = mAudioSessionRefs[i];
314 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
315 result.append(buffer);
316 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700317 write(fd, result.string(), result.size());
318 return NO_ERROR;
319}
320
321
322status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
323{
324 const size_t SIZE = 256;
325 char buffer[SIZE];
326 String8 result;
327 int hardwareStatus = mHardwareStatus;
328
329 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
330 result.append(buffer);
331 write(fd, result.string(), result.size());
332 return NO_ERROR;
333}
334
335status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
336{
337 const size_t SIZE = 256;
338 char buffer[SIZE];
339 String8 result;
340 snprintf(buffer, SIZE, "Permission Denial: "
341 "can't dump AudioFlinger from pid=%d, uid=%d\n",
342 IPCThreadState::self()->getCallingPid(),
343 IPCThreadState::self()->getCallingUid());
344 result.append(buffer);
345 write(fd, result.string(), result.size());
346 return NO_ERROR;
347}
348
349static bool tryLock(Mutex& mutex)
350{
351 bool locked = false;
352 for (int i = 0; i < kDumpLockRetries; ++i) {
353 if (mutex.tryLock() == NO_ERROR) {
354 locked = true;
355 break;
356 }
357 usleep(kDumpLockSleep);
358 }
359 return locked;
360}
361
362status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
363{
364 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
365 dumpPermissionDenial(fd, args);
366 } else {
367 // get state of hardware lock
368 bool hardwareLocked = tryLock(mHardwareLock);
369 if (!hardwareLocked) {
370 String8 result(kHardwareLockedString);
371 write(fd, result.string(), result.size());
372 } else {
373 mHardwareLock.unlock();
374 }
375
376 bool locked = tryLock(mLock);
377
378 // failed to lock - AudioFlinger is probably deadlocked
379 if (!locked) {
380 String8 result(kDeadlockedString);
381 write(fd, result.string(), result.size());
382 }
383
384 dumpClients(fd, args);
385 dumpInternals(fd, args);
386
387 // dump playback threads
388 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
389 mPlaybackThreads.valueAt(i)->dump(fd, args);
390 }
391
392 // dump record threads
393 for (size_t i = 0; i < mRecordThreads.size(); i++) {
394 mRecordThreads.valueAt(i)->dump(fd, args);
395 }
396
Dima Zavin799a70e2011-04-18 16:57:27 -0700397 // dump all hardware devs
398 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
399 audio_hw_device_t *dev = mAudioHwDevs[i];
400 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700401 }
402 if (locked) mLock.unlock();
403 }
404 return NO_ERROR;
405}
406
407
408// IAudioFlinger interface
409
410
411sp<IAudioTrack> AudioFlinger::createTrack(
412 pid_t pid,
413 int streamType,
414 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700415 uint32_t format,
416 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700417 int frameCount,
418 uint32_t flags,
419 const sp<IMemory>& sharedBuffer,
420 int output,
Mike J. Chen535235c2011-08-15 13:28:26 -0700421 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700422 int *sessionId,
423 status_t *status)
424{
425 sp<PlaybackThread::Track> track;
426 sp<TrackHandle> trackHandle;
427 sp<Client> client;
428 wp<Client> wclient;
429 status_t lStatus;
430 int lSessionId;
431
Dima Zavinfce7a472011-04-19 22:30:36 -0700432 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700433 LOGE("invalid stream type");
434 lStatus = BAD_VALUE;
435 goto Exit;
436 }
437
438 {
439 Mutex::Autolock _l(mLock);
440 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700441 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700442 if (thread == NULL) {
443 LOGE("unknown output thread");
444 lStatus = BAD_VALUE;
445 goto Exit;
446 }
447
448 wclient = mClients.valueFor(pid);
449
450 if (wclient != NULL) {
451 client = wclient.promote();
452 } else {
453 client = new Client(this, pid);
454 mClients.add(pid, client);
455 }
456
Mathias Agopian65ab4712010-07-14 17:59:35 -0700457 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700458 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700459 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700460 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
461 if (mPlaybackThreads.keyAt(i) != output) {
462 // prevent same audio session on different output threads
463 uint32_t sessions = t->hasAudioSession(*sessionId);
464 if (sessions & PlaybackThread::TRACK_SESSION) {
465 lStatus = BAD_VALUE;
466 goto Exit;
467 }
468 // check if an effect with same session ID is waiting for a track to be created
469 if (sessions & PlaybackThread::EFFECT_SESSION) {
470 effectThread = t.get();
471 }
Eric Laurentde070132010-07-13 04:45:46 -0700472 }
473 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 lSessionId = *sessionId;
475 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700476 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700477 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700478 if (sessionId != NULL) {
479 *sessionId = lSessionId;
480 }
481 }
482 LOGV("createTrack() lSessionId: %d", lSessionId);
483
484 track = thread->createTrack_l(client, streamType, sampleRate, format,
Mike J. Chen535235c2011-08-15 13:28:26 -0700485 channelMask, frameCount, sharedBuffer, lSessionId, isTimed, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700486
487 // move effect chain to this output thread if an effect on same session was waiting
488 // for a track to be created
489 if (lStatus == NO_ERROR && effectThread != NULL) {
490 Mutex::Autolock _dl(thread->mLock);
491 Mutex::Autolock _sl(effectThread->mLock);
492 moveEffectChain_l(lSessionId, effectThread, thread, true);
493 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700494 }
495 if (lStatus == NO_ERROR) {
496 trackHandle = new TrackHandle(track);
497 } else {
498 // remove local strong reference to Client before deleting the Track so that the Client
499 // destructor is called by the TrackBase destructor with mLock held
500 client.clear();
501 track.clear();
502 }
503
504Exit:
505 if(status) {
506 *status = lStatus;
507 }
508 return trackHandle;
509}
510
511uint32_t AudioFlinger::sampleRate(int output) const
512{
513 Mutex::Autolock _l(mLock);
514 PlaybackThread *thread = checkPlaybackThread_l(output);
515 if (thread == NULL) {
516 LOGW("sampleRate() unknown thread %d", output);
517 return 0;
518 }
519 return thread->sampleRate();
520}
521
522int AudioFlinger::channelCount(int output) const
523{
524 Mutex::Autolock _l(mLock);
525 PlaybackThread *thread = checkPlaybackThread_l(output);
526 if (thread == NULL) {
527 LOGW("channelCount() unknown thread %d", output);
528 return 0;
529 }
530 return thread->channelCount();
531}
532
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700533uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700534{
535 Mutex::Autolock _l(mLock);
536 PlaybackThread *thread = checkPlaybackThread_l(output);
537 if (thread == NULL) {
538 LOGW("format() unknown thread %d", output);
539 return 0;
540 }
541 return thread->format();
542}
543
544size_t AudioFlinger::frameCount(int output) const
545{
546 Mutex::Autolock _l(mLock);
547 PlaybackThread *thread = checkPlaybackThread_l(output);
548 if (thread == NULL) {
549 LOGW("frameCount() unknown thread %d", output);
550 return 0;
551 }
552 return thread->frameCount();
553}
554
555uint32_t AudioFlinger::latency(int output) const
556{
557 Mutex::Autolock _l(mLock);
558 PlaybackThread *thread = checkPlaybackThread_l(output);
559 if (thread == NULL) {
560 LOGW("latency() unknown thread %d", output);
561 return 0;
562 }
563 return thread->latency();
564}
565
566status_t AudioFlinger::setMasterVolume(float value)
567{
Eric Laurenta1884f92011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
572
Mathias Agopian65ab4712010-07-14 17:59:35 -0700573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
577
Mike J. Chen535235c2011-08-15 13:28:26 -0700578 float swmv = value;
579
Mathias Agopian65ab4712010-07-14 17:59:35 -0700580 // when hw supports master volume, don't scale in sw mixer
Mike J. Chen535235c2011-08-15 13:28:26 -0700581 if (MVS_NONE != mMasterVolumeSupportLvl) {
582 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
583 AutoMutex lock(mHardwareLock);
584 audio_hw_device_t *dev = mAudioHwDevs[i];
585
586 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
587 if (NULL != dev->set_master_volume) {
588 dev->set_master_volume(dev, value);
589 }
590 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent93575202011-01-18 18:39:02 -0800591 }
Mike J. Chen535235c2011-08-15 13:28:26 -0700592
593 swmv = 1.0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700595
Eric Laurent93575202011-01-18 18:39:02 -0800596 Mutex::Autolock _l(mLock);
Mike J. Chen535235c2011-08-15 13:28:26 -0700597 mMasterVolume = value;
598 mMasterVolumeSW = swmv;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Mike J. Chen535235c2011-08-15 13:28:26 -0700600 mPlaybackThreads.valueAt(i)->setMasterVolume(swmv);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601
602 return NO_ERROR;
603}
604
605status_t AudioFlinger::setMode(int mode)
606{
Eric Laurenta1884f92011-08-23 08:25:03 -0700607 status_t ret = initCheck();
608 if (ret != NO_ERROR) {
609 return ret;
610 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700611
612 // check calling permissions
613 if (!settingsAllowed()) {
614 return PERMISSION_DENIED;
615 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700616 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700617 LOGW("Illegal value: setMode(%d)", mode);
618 return BAD_VALUE;
619 }
620
621 { // scope for the lock
622 AutoMutex lock(mHardwareLock);
623 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700624 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700625 mHardwareStatus = AUDIO_HW_IDLE;
626 }
627
628 if (NO_ERROR == ret) {
629 Mutex::Autolock _l(mLock);
630 mMode = mode;
631 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
632 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700633 }
634
635 return ret;
636}
637
638status_t AudioFlinger::setMicMute(bool state)
639{
Eric Laurenta1884f92011-08-23 08:25:03 -0700640 status_t ret = initCheck();
641 if (ret != NO_ERROR) {
642 return ret;
643 }
644
Mathias Agopian65ab4712010-07-14 17:59:35 -0700645 // check calling permissions
646 if (!settingsAllowed()) {
647 return PERMISSION_DENIED;
648 }
649
650 AutoMutex lock(mHardwareLock);
651 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700652 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700653 mHardwareStatus = AUDIO_HW_IDLE;
654 return ret;
655}
656
657bool AudioFlinger::getMicMute() const
658{
Eric Laurenta1884f92011-08-23 08:25:03 -0700659 status_t ret = initCheck();
660 if (ret != NO_ERROR) {
661 return false;
662 }
663
Dima Zavinfce7a472011-04-19 22:30:36 -0700664 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700665 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700666 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700667 mHardwareStatus = AUDIO_HW_IDLE;
668 return state;
669}
670
671status_t AudioFlinger::setMasterMute(bool muted)
672{
673 // check calling permissions
674 if (!settingsAllowed()) {
675 return PERMISSION_DENIED;
676 }
677
Eric Laurent93575202011-01-18 18:39:02 -0800678 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700679 mMasterMute = muted;
680 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
681 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
682
683 return NO_ERROR;
684}
685
686float AudioFlinger::masterVolume() const
687{
Mike J. Chen535235c2011-08-15 13:28:26 -0700688 if (MVS_FULL == mMasterVolumeSupportLvl) {
689 float ret_val;
690 AutoMutex lock(mHardwareLock);
691
692 mHardwareStatus = AUDIO_HW_GET_MASTER_VOLUME;
693 assert(NULL != mPrimaryHardwareDev);
694 assert(NULL != mPrimaryHardwareDev->get_master_volume);
695
696 mPrimaryHardwareDev->get_master_volume(mPrimaryHardwareDev, &ret_val);
697 mHardwareStatus = AUDIO_HW_IDLE;
698 return ret_val;
699 }
700
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 return mMasterVolume;
702}
703
Mike J. Chen535235c2011-08-15 13:28:26 -0700704float AudioFlinger::masterVolumeSW() const
705{
706 return mMasterVolumeSW;
707}
708
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709bool AudioFlinger::masterMute() const
710{
711 return mMasterMute;
712}
713
714status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
715{
716 // check calling permissions
717 if (!settingsAllowed()) {
718 return PERMISSION_DENIED;
719 }
720
Dima Zavinfce7a472011-04-19 22:30:36 -0700721 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722 return BAD_VALUE;
723 }
724
725 AutoMutex lock(mLock);
726 PlaybackThread *thread = NULL;
727 if (output) {
728 thread = checkPlaybackThread_l(output);
729 if (thread == NULL) {
730 return BAD_VALUE;
731 }
732 }
733
734 mStreamTypes[stream].volume = value;
735
736 if (thread == NULL) {
737 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
738 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
739 }
740 } else {
741 thread->setStreamVolume(stream, value);
742 }
743
744 return NO_ERROR;
745}
746
747status_t AudioFlinger::setStreamMute(int stream, bool muted)
748{
749 // check calling permissions
750 if (!settingsAllowed()) {
751 return PERMISSION_DENIED;
752 }
753
Dima Zavinfce7a472011-04-19 22:30:36 -0700754 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
755 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756 return BAD_VALUE;
757 }
758
Eric Laurent93575202011-01-18 18:39:02 -0800759 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700760 mStreamTypes[stream].mute = muted;
761 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
762 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
763
764 return NO_ERROR;
765}
766
767float AudioFlinger::streamVolume(int stream, int output) const
768{
Dima Zavinfce7a472011-04-19 22:30:36 -0700769 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700770 return 0.0f;
771 }
772
773 AutoMutex lock(mLock);
774 float volume;
775 if (output) {
776 PlaybackThread *thread = checkPlaybackThread_l(output);
777 if (thread == NULL) {
778 return 0.0f;
779 }
780 volume = thread->streamVolume(stream);
781 } else {
782 volume = mStreamTypes[stream].volume;
783 }
784
785 return volume;
786}
787
788bool AudioFlinger::streamMute(int stream) const
789{
Dima Zavinfce7a472011-04-19 22:30:36 -0700790 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700791 return true;
792 }
793
794 return mStreamTypes[stream].mute;
795}
796
Mathias Agopian65ab4712010-07-14 17:59:35 -0700797status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
798{
799 status_t result;
800
801 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
802 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
803 // check calling permissions
804 if (!settingsAllowed()) {
805 return PERMISSION_DENIED;
806 }
807
Mathias Agopian65ab4712010-07-14 17:59:35 -0700808 // ioHandle == 0 means the parameters are global to the audio hardware interface
809 if (ioHandle == 0) {
810 AutoMutex lock(mHardwareLock);
811 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700812 status_t final_result = NO_ERROR;
813 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
814 audio_hw_device_t *dev = mAudioHwDevs[i];
815 result = dev->set_parameters(dev, keyValuePairs.string());
816 final_result = result ?: final_result;
817 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700818 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700819 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
820 AudioParameter param = AudioParameter(keyValuePairs);
821 String8 value;
822 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
823 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700824 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
825 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700826 for (size_t i = 0; i < mRecordThreads.size(); i++) {
827 sp<RecordThread> thread = mRecordThreads.valueAt(i);
828 RecordThread::RecordTrack *track = thread->track();
829 if (track != NULL) {
830 audio_devices_t device = (audio_devices_t)(
831 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700832 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700833 thread->setEffectSuspended(FX_IID_AEC,
834 suspend,
835 track->sessionId());
836 thread->setEffectSuspended(FX_IID_NS,
837 suspend,
838 track->sessionId());
839 }
840 }
Eric Laurentbee53372011-08-29 12:42:48 -0700841 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700842 }
843 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700844 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700845 }
846
847 // hold a strong ref on thread in case closeOutput() or closeInput() is called
848 // and the thread is exited once the lock is released
849 sp<ThreadBase> thread;
850 {
851 Mutex::Autolock _l(mLock);
852 thread = checkPlaybackThread_l(ioHandle);
853 if (thread == NULL) {
854 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700855 } else if (thread.get() == primaryPlaybackThread_l()) {
856 // indicate output device change to all input threads for pre processing
857 AudioParameter param = AudioParameter(keyValuePairs);
858 int value;
859 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
860 for (size_t i = 0; i < mRecordThreads.size(); i++) {
861 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
862 }
863 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700864 }
865 }
866 if (thread != NULL) {
867 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700868 return result;
869 }
870 return BAD_VALUE;
871}
872
873String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
874{
875// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
876// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
877
878 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700879 String8 out_s8;
880
Dima Zavin799a70e2011-04-18 16:57:27 -0700881 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
882 audio_hw_device_t *dev = mAudioHwDevs[i];
883 char *s = dev->get_parameters(dev, keys.string());
884 out_s8 += String8(s);
885 free(s);
886 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700887 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 }
889
890 Mutex::Autolock _l(mLock);
891
892 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
893 if (playbackThread != NULL) {
894 return playbackThread->getParameters(keys);
895 }
896 RecordThread *recordThread = checkRecordThread_l(ioHandle);
897 if (recordThread != NULL) {
898 return recordThread->getParameters(keys);
899 }
900 return String8("");
901}
902
903size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
904{
Eric Laurenta1884f92011-08-23 08:25:03 -0700905 status_t ret = initCheck();
906 if (ret != NO_ERROR) {
907 return 0;
908 }
909
Dima Zavin799a70e2011-04-18 16:57:27 -0700910 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700911}
912
913unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
914{
915 if (ioHandle == 0) {
916 return 0;
917 }
918
919 Mutex::Autolock _l(mLock);
920
921 RecordThread *recordThread = checkRecordThread_l(ioHandle);
922 if (recordThread != NULL) {
923 return recordThread->getInputFramesLost();
924 }
925 return 0;
926}
927
928status_t AudioFlinger::setVoiceVolume(float value)
929{
Eric Laurenta1884f92011-08-23 08:25:03 -0700930 status_t ret = initCheck();
931 if (ret != NO_ERROR) {
932 return ret;
933 }
934
Mathias Agopian65ab4712010-07-14 17:59:35 -0700935 // check calling permissions
936 if (!settingsAllowed()) {
937 return PERMISSION_DENIED;
938 }
939
940 AutoMutex lock(mHardwareLock);
941 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700942 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700943 mHardwareStatus = AUDIO_HW_IDLE;
944
945 return ret;
946}
947
948status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
949{
950 status_t status;
951
952 Mutex::Autolock _l(mLock);
953
954 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
955 if (playbackThread != NULL) {
956 return playbackThread->getRenderPosition(halFrames, dspFrames);
957 }
958
959 return BAD_VALUE;
960}
961
962void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
963{
964
965 Mutex::Autolock _l(mLock);
966
967 int pid = IPCThreadState::self()->getCallingPid();
968 if (mNotificationClients.indexOfKey(pid) < 0) {
969 sp<NotificationClient> notificationClient = new NotificationClient(this,
970 client,
971 pid);
972 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
973
974 mNotificationClients.add(pid, notificationClient);
975
976 sp<IBinder> binder = client->asBinder();
977 binder->linkToDeath(notificationClient);
978
979 // the config change is always sent from playback or record threads to avoid deadlock
980 // with AudioSystem::gLock
981 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
982 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
983 }
984
985 for (size_t i = 0; i < mRecordThreads.size(); i++) {
986 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
987 }
988 }
989}
990
991void AudioFlinger::removeNotificationClient(pid_t pid)
992{
993 Mutex::Autolock _l(mLock);
994
995 int index = mNotificationClients.indexOfKey(pid);
996 if (index >= 0) {
997 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
998 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700999 mNotificationClients.removeItem(pid);
1000 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07001001
1002 LOGV("%d died, releasing its sessions", pid);
1003 int num = mAudioSessionRefs.size();
1004 bool removed = false;
1005 for (int i = 0; i< num; i++) {
1006 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
1007 LOGV(" pid %d @ %d", ref->pid, i);
1008 if (ref->pid == pid) {
1009 LOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
1010 mAudioSessionRefs.removeAt(i);
1011 delete ref;
1012 removed = true;
1013 i--;
1014 num--;
1015 }
1016 }
1017 if (removed) {
1018 purgeStaleEffects_l();
1019 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001020}
1021
1022// audioConfigChanged_l() must be called with AudioFlinger::mLock held
1023void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
1024{
1025 size_t size = mNotificationClients.size();
1026 for (size_t i = 0; i < size; i++) {
1027 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
1028 }
1029}
1030
1031// removeClient_l() must be called with AudioFlinger::mLock held
1032void AudioFlinger::removeClient_l(pid_t pid)
1033{
1034 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
1035 mClients.removeItem(pid);
1036}
1037
1038
1039// ----------------------------------------------------------------------------
1040
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001041AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001042 : Thread(false),
1043 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -07001044 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
1045 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001046{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001047 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001048}
1049
1050AudioFlinger::ThreadBase::~ThreadBase()
1051{
1052 mParamCond.broadcast();
1053 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001054 // do not lock the mutex in destructor
1055 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001056}
1057
1058void AudioFlinger::ThreadBase::exit()
1059{
1060 // keep a strong ref on ourself so that we wont get
1061 // destroyed in the middle of requestExitAndWait()
1062 sp <ThreadBase> strongMe = this;
1063
1064 LOGV("ThreadBase::exit");
1065 {
1066 AutoMutex lock(&mLock);
1067 mExiting = true;
1068 requestExit();
1069 mWaitWorkCV.signal();
1070 }
1071 requestExitAndWait();
1072}
1073
1074uint32_t AudioFlinger::ThreadBase::sampleRate() const
1075{
1076 return mSampleRate;
1077}
1078
1079int AudioFlinger::ThreadBase::channelCount() const
1080{
1081 return (int)mChannelCount;
1082}
1083
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001084uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085{
1086 return mFormat;
1087}
1088
1089size_t AudioFlinger::ThreadBase::frameCount() const
1090{
1091 return mFrameCount;
1092}
1093
1094status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1095{
1096 status_t status;
1097
1098 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
1099 Mutex::Autolock _l(mLock);
1100
1101 mNewParameters.add(keyValuePairs);
1102 mWaitWorkCV.signal();
1103 // wait condition with timeout in case the thread loop has exited
1104 // before the request could be processed
1105 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
1106 status = mParamStatus;
1107 mWaitWorkCV.signal();
1108 } else {
1109 status = TIMED_OUT;
1110 }
1111 return status;
1112}
1113
1114void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1115{
1116 Mutex::Autolock _l(mLock);
1117 sendConfigEvent_l(event, param);
1118}
1119
1120// sendConfigEvent_l() must be called with ThreadBase::mLock held
1121void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1122{
1123 ConfigEvent *configEvent = new ConfigEvent();
1124 configEvent->mEvent = event;
1125 configEvent->mParam = param;
1126 mConfigEvents.add(configEvent);
1127 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
1128 mWaitWorkCV.signal();
1129}
1130
1131void AudioFlinger::ThreadBase::processConfigEvents()
1132{
1133 mLock.lock();
1134 while(!mConfigEvents.isEmpty()) {
1135 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
1136 ConfigEvent *configEvent = mConfigEvents[0];
1137 mConfigEvents.removeAt(0);
1138 // release mLock before locking AudioFlinger mLock: lock order is always
1139 // AudioFlinger then ThreadBase to avoid cross deadlock
1140 mLock.unlock();
1141 mAudioFlinger->mLock.lock();
1142 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
1143 mAudioFlinger->mLock.unlock();
1144 delete configEvent;
1145 mLock.lock();
1146 }
1147 mLock.unlock();
1148}
1149
1150status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1151{
1152 const size_t SIZE = 256;
1153 char buffer[SIZE];
1154 String8 result;
1155
1156 bool locked = tryLock(mLock);
1157 if (!locked) {
1158 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1159 write(fd, buffer, strlen(buffer));
1160 }
1161
1162 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1163 result.append(buffer);
1164 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1165 result.append(buffer);
1166 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1167 result.append(buffer);
1168 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1169 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001170 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1171 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001172 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1173 result.append(buffer);
1174 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1175 result.append(buffer);
1176
1177 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1178 result.append(buffer);
1179 result.append(" Index Command");
1180 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1181 snprintf(buffer, SIZE, "\n %02d ", i);
1182 result.append(buffer);
1183 result.append(mNewParameters[i]);
1184 }
1185
1186 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1187 result.append(buffer);
1188 snprintf(buffer, SIZE, " Index event param\n");
1189 result.append(buffer);
1190 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1191 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1192 result.append(buffer);
1193 }
1194 result.append("\n");
1195
1196 write(fd, result.string(), result.size());
1197
1198 if (locked) {
1199 mLock.unlock();
1200 }
1201 return NO_ERROR;
1202}
1203
Eric Laurent1d2bff02011-07-24 17:49:51 -07001204status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1205{
1206 const size_t SIZE = 256;
1207 char buffer[SIZE];
1208 String8 result;
1209
1210 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1211 write(fd, buffer, strlen(buffer));
1212
1213 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1214 sp<EffectChain> chain = mEffectChains[i];
1215 if (chain != 0) {
1216 chain->dump(fd, args);
1217 }
1218 }
1219 return NO_ERROR;
1220}
1221
Eric Laurentfeb0db62011-07-22 09:04:31 -07001222void AudioFlinger::ThreadBase::acquireWakeLock()
1223{
1224 Mutex::Autolock _l(mLock);
1225 acquireWakeLock_l();
1226}
1227
1228void AudioFlinger::ThreadBase::acquireWakeLock_l()
1229{
1230 if (mPowerManager == 0) {
1231 // use checkService() to avoid blocking if power service is not up yet
1232 sp<IBinder> binder =
1233 defaultServiceManager()->checkService(String16("power"));
1234 if (binder == 0) {
1235 LOGW("Thread %s cannot connect to the power manager service", mName);
1236 } else {
1237 mPowerManager = interface_cast<IPowerManager>(binder);
1238 binder->linkToDeath(mDeathRecipient);
1239 }
1240 }
1241 if (mPowerManager != 0) {
1242 sp<IBinder> binder = new BBinder();
1243 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1244 binder,
1245 String16(mName));
1246 if (status == NO_ERROR) {
1247 mWakeLockToken = binder;
1248 }
1249 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1250 }
1251}
1252
1253void AudioFlinger::ThreadBase::releaseWakeLock()
1254{
1255 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001256 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001257}
1258
1259void AudioFlinger::ThreadBase::releaseWakeLock_l()
1260{
1261 if (mWakeLockToken != 0) {
1262 LOGV("releaseWakeLock_l() %s", mName);
1263 if (mPowerManager != 0) {
1264 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1265 }
1266 mWakeLockToken.clear();
1267 }
1268}
1269
1270void AudioFlinger::ThreadBase::clearPowerManager()
1271{
1272 Mutex::Autolock _l(mLock);
1273 releaseWakeLock_l();
1274 mPowerManager.clear();
1275}
1276
1277void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1278{
1279 sp<ThreadBase> thread = mThread.promote();
1280 if (thread != 0) {
1281 thread->clearPowerManager();
1282 }
1283 LOGW("power manager service died !!!");
1284}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001285
Eric Laurent59255e42011-07-27 19:49:51 -07001286void AudioFlinger::ThreadBase::setEffectSuspended(
1287 const effect_uuid_t *type, bool suspend, int sessionId)
1288{
1289 Mutex::Autolock _l(mLock);
1290 setEffectSuspended_l(type, suspend, sessionId);
1291}
1292
1293void AudioFlinger::ThreadBase::setEffectSuspended_l(
1294 const effect_uuid_t *type, bool suspend, int sessionId)
1295{
1296 sp<EffectChain> chain;
1297 chain = getEffectChain_l(sessionId);
1298 if (chain != 0) {
1299 if (type != NULL) {
1300 chain->setEffectSuspended_l(type, suspend);
1301 } else {
1302 chain->setEffectSuspendedAll_l(suspend);
1303 }
1304 }
1305
1306 updateSuspendedSessions_l(type, suspend, sessionId);
1307}
1308
1309void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1310{
1311 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1312 if (index < 0) {
1313 return;
1314 }
1315
1316 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1317 mSuspendedSessions.editValueAt(index);
1318
1319 for (size_t i = 0; i < sessionEffects.size(); i++) {
1320 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1321 for (int j = 0; j < desc->mRefCount; j++) {
1322 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1323 chain->setEffectSuspendedAll_l(true);
1324 } else {
1325 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1326 desc->mType.timeLow);
1327 chain->setEffectSuspended_l(&desc->mType, true);
1328 }
1329 }
1330 }
1331}
1332
Eric Laurent59255e42011-07-27 19:49:51 -07001333void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1334 bool suspend,
1335 int sessionId)
1336{
1337 int index = mSuspendedSessions.indexOfKey(sessionId);
1338
1339 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1340
1341 if (suspend) {
1342 if (index >= 0) {
1343 sessionEffects = mSuspendedSessions.editValueAt(index);
1344 } else {
1345 mSuspendedSessions.add(sessionId, sessionEffects);
1346 }
1347 } else {
1348 if (index < 0) {
1349 return;
1350 }
1351 sessionEffects = mSuspendedSessions.editValueAt(index);
1352 }
1353
1354
1355 int key = EffectChain::kKeyForSuspendAll;
1356 if (type != NULL) {
1357 key = type->timeLow;
1358 }
1359 index = sessionEffects.indexOfKey(key);
1360
1361 sp <SuspendedSessionDesc> desc;
1362 if (suspend) {
1363 if (index >= 0) {
1364 desc = sessionEffects.valueAt(index);
1365 } else {
1366 desc = new SuspendedSessionDesc();
1367 if (type != NULL) {
1368 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1369 }
1370 sessionEffects.add(key, desc);
1371 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1372 }
1373 desc->mRefCount++;
1374 } else {
1375 if (index < 0) {
1376 return;
1377 }
1378 desc = sessionEffects.valueAt(index);
1379 if (--desc->mRefCount == 0) {
1380 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1381 sessionEffects.removeItemsAt(index);
1382 if (sessionEffects.isEmpty()) {
1383 LOGV("updateSuspendedSessions_l() restore removing session %d",
1384 sessionId);
1385 mSuspendedSessions.removeItem(sessionId);
1386 }
1387 }
1388 }
1389 if (!sessionEffects.isEmpty()) {
1390 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1391 }
1392}
1393
1394void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1395 bool enabled,
1396 int sessionId)
1397{
1398 Mutex::Autolock _l(mLock);
1399
Eric Laurentdb7c0792011-08-10 10:37:50 -07001400 if (mType != RECORD) {
1401 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1402 // another session. This gives the priority to well behaved effect control panels
1403 // and applications not using global effects.
1404 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1405 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1406 }
1407 }
Eric Laurent59255e42011-07-27 19:49:51 -07001408
1409 sp<EffectChain> chain = getEffectChain_l(sessionId);
1410 if (chain != 0) {
1411 chain->checkSuspendOnEffectEnabled(effect, enabled);
1412 }
1413}
1414
Mathias Agopian65ab4712010-07-14 17:59:35 -07001415// ----------------------------------------------------------------------------
1416
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001417AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1418 AudioStreamOut* output,
1419 int id,
1420 uint32_t device)
1421 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001423 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001424{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001425 snprintf(mName, kNameLength, "AudioOut_%d", id);
1426
Mathias Agopian65ab4712010-07-14 17:59:35 -07001427 readOutputParameters();
1428
Mike J. Chen535235c2011-08-15 13:28:26 -07001429 mMasterVolume = mAudioFlinger->masterVolumeSW();
1430
Mathias Agopian65ab4712010-07-14 17:59:35 -07001431 mMasterMute = mAudioFlinger->masterMute();
1432
Dima Zavinfce7a472011-04-19 22:30:36 -07001433 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1435 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1436 }
1437}
1438
1439AudioFlinger::PlaybackThread::~PlaybackThread()
1440{
1441 delete [] mMixBuffer;
1442}
1443
1444status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1445{
1446 dumpInternals(fd, args);
1447 dumpTracks(fd, args);
1448 dumpEffectChains(fd, args);
1449 return NO_ERROR;
1450}
1451
1452status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1453{
1454 const size_t SIZE = 256;
1455 char buffer[SIZE];
1456 String8 result;
1457
1458 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1459 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001460 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 -07001461 for (size_t i = 0; i < mTracks.size(); ++i) {
1462 sp<Track> track = mTracks[i];
1463 if (track != 0) {
1464 track->dump(buffer, SIZE);
1465 result.append(buffer);
1466 }
1467 }
1468
1469 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1470 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001471 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 -07001472 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1473 wp<Track> wTrack = mActiveTracks[i];
1474 if (wTrack != 0) {
1475 sp<Track> track = wTrack.promote();
1476 if (track != 0) {
1477 track->dump(buffer, SIZE);
1478 result.append(buffer);
1479 }
1480 }
1481 }
1482 write(fd, result.string(), result.size());
1483 return NO_ERROR;
1484}
1485
Mathias Agopian65ab4712010-07-14 17:59:35 -07001486status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1487{
1488 const size_t SIZE = 256;
1489 char buffer[SIZE];
1490 String8 result;
1491
1492 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1493 result.append(buffer);
1494 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1495 result.append(buffer);
1496 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1497 result.append(buffer);
1498 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1499 result.append(buffer);
1500 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1501 result.append(buffer);
1502 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1503 result.append(buffer);
1504 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1505 result.append(buffer);
1506 write(fd, result.string(), result.size());
1507
1508 dumpBase(fd, args);
1509
1510 return NO_ERROR;
1511}
1512
1513// Thread virtuals
1514status_t AudioFlinger::PlaybackThread::readyToRun()
1515{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001516 status_t status = initCheck();
1517 if (status == NO_ERROR) {
1518 LOGI("AudioFlinger's thread %p ready to run", this);
1519 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001521 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001522 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001523}
1524
1525void AudioFlinger::PlaybackThread::onFirstRef()
1526{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001527 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001528}
1529
1530// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1531sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1532 const sp<AudioFlinger::Client>& client,
1533 int streamType,
1534 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001535 uint32_t format,
1536 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537 int frameCount,
1538 const sp<IMemory>& sharedBuffer,
1539 int sessionId,
Mike J. Chen535235c2011-08-15 13:28:26 -07001540 bool isTimed,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001541 status_t *status)
1542{
1543 sp<Track> track;
1544 status_t lStatus;
1545
1546 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001547 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1548 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1549 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1550 "for output %p with format %d",
1551 sampleRate, format, channelMask, mOutput, mFormat);
1552 lStatus = BAD_VALUE;
1553 goto Exit;
1554 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 }
1556 } else {
1557 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1558 if (sampleRate > mSampleRate*2) {
1559 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1560 lStatus = BAD_VALUE;
1561 goto Exit;
1562 }
1563 }
1564
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001565 lStatus = initCheck();
1566 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001568 goto Exit;
1569 }
1570
1571 { // scope for mLock
1572 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001573
1574 // all tracks in same audio session must share the same routing strategy otherwise
1575 // conflicts will happen when tracks are moved from one output to another by audio policy
1576 // manager
1577 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001578 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001579 for (size_t i = 0; i < mTracks.size(); ++i) {
1580 sp<Track> t = mTracks[i];
1581 if (t != 0) {
1582 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001583 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001584 lStatus = BAD_VALUE;
1585 goto Exit;
1586 }
1587 }
1588 }
1589
Mike J. Chen535235c2011-08-15 13:28:26 -07001590 if (!isTimed) {
1591 track = new Track(this, client, streamType, sampleRate, format,
1592 channelMask, frameCount, sharedBuffer, sessionId);
1593 } else {
1594 track = TimedTrack::create(this, client, streamType, sampleRate, format,
1595 channelMask, frameCount, sharedBuffer, sessionId);
1596 }
1597 if (track == NULL || track->getCblk() == NULL || track->name() < 0) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001598 lStatus = NO_MEMORY;
1599 goto Exit;
1600 }
1601 mTracks.add(track);
1602
1603 sp<EffectChain> chain = getEffectChain_l(sessionId);
1604 if (chain != 0) {
1605 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1606 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001607 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001608 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001609 }
1610 }
1611 lStatus = NO_ERROR;
1612
1613Exit:
1614 if(status) {
1615 *status = lStatus;
1616 }
1617 return track;
1618}
1619
1620uint32_t AudioFlinger::PlaybackThread::latency() const
1621{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001622 Mutex::Autolock _l(mLock);
1623 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001624 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001625 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001626 return 0;
1627 }
1628}
1629
1630status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1631{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001632 mMasterVolume = value;
1633 return NO_ERROR;
1634}
1635
1636status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1637{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 mMasterMute = muted;
1639 return NO_ERROR;
1640}
1641
1642float AudioFlinger::PlaybackThread::masterVolume() const
1643{
1644 return mMasterVolume;
1645}
1646
1647bool AudioFlinger::PlaybackThread::masterMute() const
1648{
1649 return mMasterMute;
1650}
1651
1652status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1653{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001654 mStreamTypes[stream].volume = value;
1655 return NO_ERROR;
1656}
1657
1658status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1659{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 mStreamTypes[stream].mute = muted;
1661 return NO_ERROR;
1662}
1663
1664float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1665{
1666 return mStreamTypes[stream].volume;
1667}
1668
1669bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1670{
1671 return mStreamTypes[stream].mute;
1672}
1673
Mathias Agopian65ab4712010-07-14 17:59:35 -07001674// addTrack_l() must be called with ThreadBase::mLock held
1675status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1676{
1677 status_t status = ALREADY_EXISTS;
1678
1679 // set retry count for buffer fill
1680 track->mRetryCount = kMaxTrackStartupRetries;
1681 if (mActiveTracks.indexOf(track) < 0) {
1682 // the track is newly added, make sure it fills up all its
1683 // buffers before playing. This is to ensure the client will
1684 // effectively get the latency it requested.
1685 track->mFillingUpStatus = Track::FS_FILLING;
1686 track->mResetDone = false;
1687 mActiveTracks.add(track);
1688 if (track->mainBuffer() != mMixBuffer) {
1689 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1690 if (chain != 0) {
1691 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001692 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 }
1694 }
1695
1696 status = NO_ERROR;
1697 }
1698
1699 LOGV("mWaitWorkCV.broadcast");
1700 mWaitWorkCV.broadcast();
1701
1702 return status;
1703}
1704
1705// destroyTrack_l() must be called with ThreadBase::mLock held
1706void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1707{
1708 track->mState = TrackBase::TERMINATED;
1709 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001710 removeTrack_l(track);
1711 }
1712}
1713
1714void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1715{
1716 mTracks.remove(track);
1717 deleteTrackName_l(track->name());
1718 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1719 if (chain != 0) {
1720 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 }
1722}
1723
1724String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1725{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001726 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001727 char *s;
1728
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001729 Mutex::Autolock _l(mLock);
1730 if (initCheck() != NO_ERROR) {
1731 return out_s8;
1732 }
1733
Dima Zavin799a70e2011-04-18 16:57:27 -07001734 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001735 out_s8 = String8(s);
1736 free(s);
1737 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738}
1739
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001740// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1742 AudioSystem::OutputDescriptor desc;
1743 void *param2 = 0;
1744
1745 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1746
1747 switch (event) {
1748 case AudioSystem::OUTPUT_OPENED:
1749 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001750 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751 desc.samplingRate = mSampleRate;
1752 desc.format = mFormat;
1753 desc.frameCount = mFrameCount;
1754 desc.latency = latency();
1755 param2 = &desc;
1756 break;
1757
1758 case AudioSystem::STREAM_CONFIG_CHANGED:
1759 param2 = &param;
1760 case AudioSystem::OUTPUT_CLOSED:
1761 default:
1762 break;
1763 }
1764 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1765}
1766
1767void AudioFlinger::PlaybackThread::readOutputParameters()
1768{
Dima Zavin799a70e2011-04-18 16:57:27 -07001769 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001770 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1771 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001772 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1773 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1774 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001775
1776 // FIXME - Current mixer implementation only supports stereo output: Always
1777 // Allocate a stereo buffer even if HW output is mono.
1778 if (mMixBuffer != NULL) delete[] mMixBuffer;
1779 mMixBuffer = new int16_t[mFrameCount * 2];
1780 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1781
Eric Laurentde070132010-07-13 04:45:46 -07001782 // force reconfiguration of effect chains and engines to take new buffer size and audio
1783 // parameters into account
1784 // Note that mLock is not held when readOutputParameters() is called from the constructor
1785 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1786 // matter.
1787 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1788 Vector< sp<EffectChain> > effectChains = mEffectChains;
1789 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001790 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001791 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001792}
1793
1794status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1795{
1796 if (halFrames == 0 || dspFrames == 0) {
1797 return BAD_VALUE;
1798 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001799 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001800 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001801 return INVALID_OPERATION;
1802 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001803 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001804
Dima Zavin799a70e2011-04-18 16:57:27 -07001805 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001806}
1807
Eric Laurent39e94f82010-07-28 01:32:47 -07001808uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001809{
1810 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001811 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001812 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001813 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001814 }
1815
1816 for (size_t i = 0; i < mTracks.size(); ++i) {
1817 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001818 if (sessionId == track->sessionId() &&
1819 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001820 result |= TRACK_SESSION;
1821 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001822 }
1823 }
1824
Eric Laurent39e94f82010-07-28 01:32:47 -07001825 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001826}
1827
Eric Laurentde070132010-07-13 04:45:46 -07001828uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1829{
Dima Zavinfce7a472011-04-19 22:30:36 -07001830 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001831 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001832 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1833 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001834 }
1835 for (size_t i = 0; i < mTracks.size(); i++) {
1836 sp<Track> track = mTracks[i];
1837 if (sessionId == track->sessionId() &&
1838 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001839 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001840 }
1841 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001842 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001843}
1844
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001846AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1847{
1848 Mutex::Autolock _l(mLock);
1849 return mOutput;
1850}
1851
1852AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1853{
1854 Mutex::Autolock _l(mLock);
1855 AudioStreamOut *output = mOutput;
1856 mOutput = NULL;
1857 return output;
1858}
1859
1860// this method must always be called either with ThreadBase mLock held or inside the thread loop
1861audio_stream_t* AudioFlinger::PlaybackThread::stream()
1862{
1863 if (mOutput == NULL) {
1864 return NULL;
1865 }
1866 return &mOutput->stream->common;
1867}
1868
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869// ----------------------------------------------------------------------------
1870
Dima Zavin799a70e2011-04-18 16:57:27 -07001871AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001872 : PlaybackThread(audioFlinger, output, id, device),
1873 mAudioMixer(0)
1874{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001875 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001876 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1877
1878 // FIXME - Current mixer implementation only supports stereo output
1879 if (mChannelCount == 1) {
1880 LOGE("Invalid audio hardware channel count");
1881 }
1882}
1883
1884AudioFlinger::MixerThread::~MixerThread()
1885{
1886 delete mAudioMixer;
1887}
1888
1889bool AudioFlinger::MixerThread::threadLoop()
1890{
1891 Vector< sp<Track> > tracksToRemove;
1892 uint32_t mixerStatus = MIXER_IDLE;
1893 nsecs_t standbyTime = systemTime();
1894 size_t mixBufferSize = mFrameCount * mFrameSize;
1895 // FIXME: Relaxed timing because of a certain device that can't meet latency
1896 // Should be reduced to 2x after the vendor fixes the driver issue
1897 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1898 nsecs_t lastWarning = 0;
1899 bool longStandbyExit = false;
1900 uint32_t activeSleepTime = activeSleepTimeUs();
1901 uint32_t idleSleepTime = idleSleepTimeUs();
1902 uint32_t sleepTime = idleSleepTime;
1903 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001904#ifdef DEBUG_CPU_USAGE
1905 ThreadCpuUsage cpu;
1906 const CentralTendencyStatistics& stats = cpu.statistics();
1907#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001908
Eric Laurentfeb0db62011-07-22 09:04:31 -07001909 acquireWakeLock();
1910
Mike J. Chen535235c2011-08-15 13:28:26 -07001911 LocalClock lc;
1912 uint64_t localTimeFreq;
1913 localTimeFreq = lc.getLocalFreq();
1914
Mathias Agopian65ab4712010-07-14 17:59:35 -07001915 while (!exitPending())
1916 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001917#ifdef DEBUG_CPU_USAGE
1918 cpu.sampleAndEnable();
1919 unsigned n = stats.n();
1920 // cpu.elapsed() is expensive, so don't call it every loop
1921 if ((n & 127) == 1) {
1922 long long elapsed = cpu.elapsed();
1923 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1924 double perLoop = elapsed / (double) n;
1925 double perLoop100 = perLoop * 0.01;
1926 double mean = stats.mean();
1927 double stddev = stats.stddev();
1928 double minimum = stats.minimum();
1929 double maximum = stats.maximum();
1930 cpu.resetStatistics();
1931 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",
1932 elapsed * .000000001, n, perLoop * .000001,
1933 mean * .001,
1934 stddev * .001,
1935 minimum * .001,
1936 maximum * .001,
1937 mean / perLoop100,
1938 stddev / perLoop100,
1939 minimum / perLoop100,
1940 maximum / perLoop100);
1941 }
1942 }
1943#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001944 processConfigEvents();
1945
1946 mixerStatus = MIXER_IDLE;
1947 { // scope for mLock
1948
1949 Mutex::Autolock _l(mLock);
1950
1951 if (checkForNewParameters_l()) {
1952 mixBufferSize = mFrameCount * mFrameSize;
1953 // FIXME: Relaxed timing because of a certain device that can't meet latency
1954 // Should be reduced to 2x after the vendor fixes the driver issue
1955 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1956 activeSleepTime = activeSleepTimeUs();
1957 idleSleepTime = idleSleepTimeUs();
1958 }
1959
1960 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1961
1962 // put audio hardware into standby after short delay
1963 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1964 mSuspended) {
1965 if (!mStandby) {
1966 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001967 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001968 mStandby = true;
1969 mBytesWritten = 0;
1970 }
1971
1972 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1973 // we're about to wait, flush the binder command buffer
1974 IPCThreadState::self()->flushCommands();
1975
1976 if (exitPending()) break;
1977
Eric Laurentfeb0db62011-07-22 09:04:31 -07001978 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001979 // wait until we have something to do...
1980 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1981 mWaitWorkCV.wait(mLock);
1982 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001983 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984
1985 if (mMasterMute == false) {
1986 char value[PROPERTY_VALUE_MAX];
1987 property_get("ro.audio.silent", value, "0");
1988 if (atoi(value)) {
1989 LOGD("Silence is golden");
1990 setMasterMute(true);
1991 }
1992 }
1993
1994 standbyTime = systemTime() + kStandbyTimeInNsecs;
1995 sleepTime = idleSleepTime;
1996 continue;
1997 }
1998 }
1999
2000 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2001
2002 // prevent any changes in effect chain list and in each effect chain
2003 // during mixing and effect process as the audio buffers could be deleted
2004 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002005 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002006 }
2007
2008 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Mike J. Chen535235c2011-08-15 13:28:26 -07002009 // obtain the presentation timestamp of the next output buffer
2010 int64_t pts;
John Grossmandcdbcc52011-08-29 10:26:47 -07002011 status_t status = INVALID_OPERATION;
2012
2013 if (NULL != mOutput->stream->get_next_write_timestamp) {
2014 status = mOutput->stream->get_next_write_timestamp(
2015 mOutput->stream, &pts);
2016 }
2017
Mike J. Chen535235c2011-08-15 13:28:26 -07002018 if (status != NO_ERROR) {
2019 pts = AudioBufferProvider::kInvalidPTS;
2020 }
2021
Mathias Agopian65ab4712010-07-14 17:59:35 -07002022 // mix buffers...
Mike J. Chen535235c2011-08-15 13:28:26 -07002023 mAudioMixer->process(pts);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002024 sleepTime = 0;
2025 standbyTime = systemTime() + kStandbyTimeInNsecs;
2026 //TODO: delay standby when effects have a tail
2027 } else {
2028 // If no tracks are ready, sleep once for the duration of an output
2029 // buffer size, then write 0s to the output
2030 if (sleepTime == 0) {
2031 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2032 sleepTime = activeSleepTime;
2033 } else {
2034 sleepTime = idleSleepTime;
2035 }
2036 } else if (mBytesWritten != 0 ||
2037 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2038 memset (mMixBuffer, 0, mixBufferSize);
2039 sleepTime = 0;
2040 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
2041 }
2042 // TODO add standby time extension fct of effect tail
2043 }
2044
2045 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002046 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002047 }
2048 // sleepTime == 0 means we must write to audio hardware
2049 if (sleepTime == 0) {
2050 for (size_t i = 0; i < effectChains.size(); i ++) {
2051 effectChains[i]->process_l();
2052 }
2053 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002054 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002055 mLastWriteTime = systemTime();
2056 mInWrite = true;
2057 mBytesWritten += mixBufferSize;
2058
Dima Zavin799a70e2011-04-18 16:57:27 -07002059 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002060 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2061 mNumWrites++;
2062 mInWrite = false;
2063 nsecs_t now = systemTime();
2064 nsecs_t delta = now - mLastWriteTime;
2065 if (delta > maxPeriod) {
2066 mNumDelayedWrites++;
2067 if ((now - lastWarning) > kWarningThrottle) {
2068 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2069 ns2ms(delta), mNumDelayedWrites, this);
2070 lastWarning = now;
2071 }
2072 if (mStandby) {
2073 longStandbyExit = true;
2074 }
2075 }
2076 mStandby = false;
2077 } else {
2078 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002079 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 usleep(sleepTime);
2081 }
2082
2083 // finally let go of all our tracks, without the lock held
2084 // since we can't guarantee the destructors won't acquire that
2085 // same lock.
2086 tracksToRemove.clear();
2087
2088 // Effect chains will be actually deleted here if they were removed from
2089 // mEffectChains list during mixing or effects processing
2090 effectChains.clear();
2091 }
2092
2093 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002094 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002095 }
2096
Eric Laurentfeb0db62011-07-22 09:04:31 -07002097 releaseWakeLock();
2098
Mathias Agopian65ab4712010-07-14 17:59:35 -07002099 LOGV("MixerThread %p exiting", this);
2100 return false;
2101}
2102
2103// prepareTracks_l() must be called with ThreadBase::mLock held
2104uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2105{
2106
2107 uint32_t mixerStatus = MIXER_IDLE;
2108 // find out which tracks need to be processed
2109 size_t count = activeTracks.size();
2110 size_t mixedTracks = 0;
2111 size_t tracksWithEffect = 0;
2112
2113 float masterVolume = mMasterVolume;
2114 bool masterMute = mMasterMute;
2115
Eric Laurent571d49c2010-08-11 05:20:11 -07002116 if (masterMute) {
2117 masterVolume = 0;
2118 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002119 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002120 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002121 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002122 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002123 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002124 masterVolume = (float)((v + (1 << 23)) >> 24);
2125 chain.clear();
2126 }
2127
2128 for (size_t i=0 ; i<count ; i++) {
2129 sp<Track> t = activeTracks[i].promote();
2130 if (t == 0) continue;
2131
2132 Track* const track = t.get();
2133 audio_track_cblk_t* cblk = track->cblk();
2134
2135 // The first time a track is added we wait
2136 // for all its buffers to be filled before processing it
2137 mAudioMixer->setActiveTrack(track->name());
Mike J. Chen535235c2011-08-15 13:28:26 -07002138 if (track->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002139 !track->isPaused() && !track->isTerminated())
2140 {
2141 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
2142
2143 mixedTracks++;
2144
2145 // track->mainBuffer() != mMixBuffer means there is an effect chain
2146 // connected to the track
2147 chain.clear();
2148 if (track->mainBuffer() != mMixBuffer) {
2149 chain = getEffectChain_l(track->sessionId());
2150 // Delegate volume control to effect in track effect chain if needed
2151 if (chain != 0) {
2152 tracksWithEffect++;
2153 } else {
2154 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
2155 track->name(), track->sessionId());
2156 }
2157 }
2158
2159
2160 int param = AudioMixer::VOLUME;
2161 if (track->mFillingUpStatus == Track::FS_FILLED) {
2162 // no ramp for the first volume setting
2163 track->mFillingUpStatus = Track::FS_ACTIVE;
2164 if (track->mState == TrackBase::RESUMING) {
2165 track->mState = TrackBase::ACTIVE;
2166 param = AudioMixer::RAMP_VOLUME;
2167 }
Eric Laurent243f5f92011-02-28 16:52:51 -08002168 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002169 } else if (cblk->server != 0) {
2170 // If the track is stopped before the first frame was mixed,
2171 // do not apply ramp
2172 param = AudioMixer::RAMP_VOLUME;
2173 }
2174
2175 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002176 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002177 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002178 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002179 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002180 if (track->isPausing()) {
2181 track->setPaused();
2182 }
2183 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002184
Mathias Agopian65ab4712010-07-14 17:59:35 -07002185 // read original volumes with volume control
2186 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002187 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002188 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2189 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002190
Eric Laurente0aed6d2010-09-10 17:44:44 -07002191 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002192 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002193 // Delegate volume control to effect in track effect chain if needed
2194 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2195 // Do not ramp volume if volume is controlled by effect
2196 param = AudioMixer::VOLUME;
2197 track->mHasVolumeController = true;
2198 } else {
2199 // force no volume ramp when volume controller was just disabled or removed
2200 // from effect chain to avoid volume spike
2201 if (track->mHasVolumeController) {
2202 param = AudioMixer::VOLUME;
2203 }
2204 track->mHasVolumeController = false;
2205 }
2206
2207 // Convert volumes from 8.24 to 4.12 format
2208 int16_t left, right, aux;
2209 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2210 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2211 left = int16_t(v_clamped);
2212 v_clamped = (vr + (1 << 11)) >> 12;
2213 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2214 right = int16_t(v_clamped);
2215
2216 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2217 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002218
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 // XXX: these things DON'T need to be done each time
2220 mAudioMixer->setBufferProvider(track);
2221 mAudioMixer->enable(AudioMixer::MIXING);
2222
2223 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2224 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2225 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2226 mAudioMixer->setParameter(
2227 AudioMixer::TRACK,
2228 AudioMixer::FORMAT, (void *)track->format());
2229 mAudioMixer->setParameter(
2230 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002231 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 mAudioMixer->setParameter(
2233 AudioMixer::RESAMPLE,
2234 AudioMixer::SAMPLE_RATE,
2235 (void *)(cblk->sampleRate));
2236 mAudioMixer->setParameter(
2237 AudioMixer::TRACK,
2238 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2239 mAudioMixer->setParameter(
2240 AudioMixer::TRACK,
2241 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2242
2243 // reset retry count
2244 track->mRetryCount = kMaxTrackRetries;
2245 mixerStatus = MIXER_TRACKS_READY;
2246 } else {
2247 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2248 if (track->isStopped()) {
2249 track->reset();
2250 }
2251 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2252 // We have consumed all the buffers of this track.
2253 // Remove it from the list of active tracks.
2254 tracksToRemove->add(track);
2255 } else {
2256 // No buffers for this track. Give it a few chances to
2257 // fill a buffer, then remove it from active list.
2258 if (--(track->mRetryCount) <= 0) {
2259 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2260 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002261 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002262 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 } else if (mixerStatus != MIXER_TRACKS_READY) {
2264 mixerStatus = MIXER_TRACKS_ENABLED;
2265 }
2266 }
2267 mAudioMixer->disable(AudioMixer::MIXING);
2268 }
2269 }
2270
2271 // remove all the tracks that need to be...
2272 count = tracksToRemove->size();
2273 if (UNLIKELY(count)) {
2274 for (size_t i=0 ; i<count ; i++) {
2275 const sp<Track>& track = tracksToRemove->itemAt(i);
2276 mActiveTracks.remove(track);
2277 if (track->mainBuffer() != mMixBuffer) {
2278 chain = getEffectChain_l(track->sessionId());
2279 if (chain != 0) {
2280 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002281 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002282 }
2283 }
2284 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002285 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002286 }
2287 }
2288 }
2289
2290 // mix buffer must be cleared if all tracks are connected to an
2291 // effect chain as in this case the mixer will not write to
2292 // mix buffer and track effects will accumulate into it
2293 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2294 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2295 }
2296
2297 return mixerStatus;
2298}
2299
2300void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2301{
Eric Laurentde070132010-07-13 04:45:46 -07002302 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2303 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002305
Mathias Agopian65ab4712010-07-14 17:59:35 -07002306 size_t size = mTracks.size();
2307 for (size_t i = 0; i < size; i++) {
2308 sp<Track> t = mTracks[i];
2309 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002310 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002311 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002312 }
2313 }
2314}
2315
2316
2317// getTrackName_l() must be called with ThreadBase::mLock held
2318int AudioFlinger::MixerThread::getTrackName_l()
2319{
2320 return mAudioMixer->getTrackName();
2321}
2322
2323// deleteTrackName_l() must be called with ThreadBase::mLock held
2324void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2325{
2326 LOGV("remove track (%d) and delete from mixer", name);
2327 mAudioMixer->deleteTrackName(name);
2328}
2329
2330// checkForNewParameters_l() must be called with ThreadBase::mLock held
2331bool AudioFlinger::MixerThread::checkForNewParameters_l()
2332{
2333 bool reconfig = false;
2334
2335 while (!mNewParameters.isEmpty()) {
2336 status_t status = NO_ERROR;
2337 String8 keyValuePair = mNewParameters[0];
2338 AudioParameter param = AudioParameter(keyValuePair);
2339 int value;
2340
2341 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2342 reconfig = true;
2343 }
2344 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002345 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002346 status = BAD_VALUE;
2347 } else {
2348 reconfig = true;
2349 }
2350 }
2351 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002352 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002353 status = BAD_VALUE;
2354 } else {
2355 reconfig = true;
2356 }
2357 }
2358 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2359 // do not accept frame count changes if tracks are open as the track buffer
2360 // size depends on frame count and correct behavior would not be garantied
2361 // if frame count is changed after track creation
2362 if (!mTracks.isEmpty()) {
2363 status = INVALID_OPERATION;
2364 } else {
2365 reconfig = true;
2366 }
2367 }
2368 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002369 // when changing the audio output device, call addBatteryData to notify
2370 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002371 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002372 uint32_t params = 0;
2373 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002374 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002375 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2376 }
2377
2378 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002379 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002380 // check if any other device (except speaker) is on
2381 if (value & deviceWithoutSpeaker ) {
2382 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2383 }
2384
2385 if (params != 0) {
2386 addBatteryData(params);
2387 }
2388 }
2389
Mathias Agopian65ab4712010-07-14 17:59:35 -07002390 // forward device change to effects that have requested to be
2391 // aware of attached audio device.
2392 mDevice = (uint32_t)value;
2393 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002394 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002395 }
2396 }
2397
2398 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002399 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002400 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002401 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002402 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403 mStandby = true;
2404 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002405 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002406 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002407 }
2408 if (status == NO_ERROR && reconfig) {
2409 delete mAudioMixer;
2410 readOutputParameters();
2411 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2412 for (size_t i = 0; i < mTracks.size() ; i++) {
2413 int name = getTrackName_l();
2414 if (name < 0) break;
2415 mTracks[i]->mName = name;
2416 // limit track sample rate to 2 x new output sample rate
2417 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2418 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2419 }
2420 }
2421 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2422 }
2423 }
2424
2425 mNewParameters.removeAt(0);
2426
2427 mParamStatus = status;
2428 mParamCond.signal();
2429 mWaitWorkCV.wait(mLock);
2430 }
2431 return reconfig;
2432}
2433
2434status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2435{
2436 const size_t SIZE = 256;
2437 char buffer[SIZE];
2438 String8 result;
2439
2440 PlaybackThread::dumpInternals(fd, args);
2441
2442 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2443 result.append(buffer);
2444 write(fd, result.string(), result.size());
2445 return NO_ERROR;
2446}
2447
2448uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2449{
Dima Zavin799a70e2011-04-18 16:57:27 -07002450 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002451}
2452
2453uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2454{
Eric Laurent60e18242010-07-29 06:50:24 -07002455 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002456}
2457
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002458uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2459{
2460 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2461}
2462
Mathias Agopian65ab4712010-07-14 17:59:35 -07002463// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002464AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465 : PlaybackThread(audioFlinger, output, id, device)
2466{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002467 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468}
2469
2470AudioFlinger::DirectOutputThread::~DirectOutputThread()
2471{
2472}
2473
2474
2475static inline int16_t clamp16(int32_t sample)
2476{
2477 if ((sample>>15) ^ (sample>>31))
2478 sample = 0x7FFF ^ (sample>>31);
2479 return sample;
2480}
2481
2482static inline
2483int32_t mul(int16_t in, int16_t v)
2484{
2485#if defined(__arm__) && !defined(__thumb__)
2486 int32_t out;
2487 asm( "smulbb %[out], %[in], %[v] \n"
2488 : [out]"=r"(out)
2489 : [in]"%r"(in), [v]"r"(v)
2490 : );
2491 return out;
2492#else
2493 return in * int32_t(v);
2494#endif
2495}
2496
2497void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2498{
2499 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002500 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002501 return;
2502 }
2503
2504 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002505 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002506 size_t count = mFrameCount * mChannelCount;
2507 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2508 int16_t *dst = mMixBuffer + count-1;
2509 while(count--) {
2510 *dst-- = (int16_t)(*src--^0x80) << 8;
2511 }
2512 }
2513
2514 size_t frameCount = mFrameCount;
2515 int16_t *out = mMixBuffer;
2516 if (ramp) {
2517 if (mChannelCount == 1) {
2518 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2519 int32_t vlInc = d / (int32_t)frameCount;
2520 int32_t vl = ((int32_t)mLeftVolShort << 16);
2521 do {
2522 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2523 out++;
2524 vl += vlInc;
2525 } while (--frameCount);
2526
2527 } else {
2528 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2529 int32_t vlInc = d / (int32_t)frameCount;
2530 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2531 int32_t vrInc = d / (int32_t)frameCount;
2532 int32_t vl = ((int32_t)mLeftVolShort << 16);
2533 int32_t vr = ((int32_t)mRightVolShort << 16);
2534 do {
2535 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2536 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2537 out += 2;
2538 vl += vlInc;
2539 vr += vrInc;
2540 } while (--frameCount);
2541 }
2542 } else {
2543 if (mChannelCount == 1) {
2544 do {
2545 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2546 out++;
2547 } while (--frameCount);
2548 } else {
2549 do {
2550 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2551 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2552 out += 2;
2553 } while (--frameCount);
2554 }
2555 }
2556
2557 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002558 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002559 size_t count = mFrameCount * mChannelCount;
2560 int16_t *src = mMixBuffer;
2561 uint8_t *dst = (uint8_t *)mMixBuffer;
2562 while(count--) {
2563 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2564 }
2565 }
2566
2567 mLeftVolShort = leftVol;
2568 mRightVolShort = rightVol;
2569}
2570
2571bool AudioFlinger::DirectOutputThread::threadLoop()
2572{
2573 uint32_t mixerStatus = MIXER_IDLE;
2574 sp<Track> trackToRemove;
2575 sp<Track> activeTrack;
2576 nsecs_t standbyTime = systemTime();
2577 int8_t *curBuf;
2578 size_t mixBufferSize = mFrameCount*mFrameSize;
2579 uint32_t activeSleepTime = activeSleepTimeUs();
2580 uint32_t idleSleepTime = idleSleepTimeUs();
2581 uint32_t sleepTime = idleSleepTime;
2582 // use shorter standby delay as on normal output to release
2583 // hardware resources as soon as possible
2584 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2585
Eric Laurentfeb0db62011-07-22 09:04:31 -07002586 acquireWakeLock();
2587
Mathias Agopian65ab4712010-07-14 17:59:35 -07002588 while (!exitPending())
2589 {
2590 bool rampVolume;
2591 uint16_t leftVol;
2592 uint16_t rightVol;
2593 Vector< sp<EffectChain> > effectChains;
2594
2595 processConfigEvents();
2596
2597 mixerStatus = MIXER_IDLE;
2598
2599 { // scope for the mLock
2600
2601 Mutex::Autolock _l(mLock);
2602
2603 if (checkForNewParameters_l()) {
2604 mixBufferSize = mFrameCount*mFrameSize;
2605 activeSleepTime = activeSleepTimeUs();
2606 idleSleepTime = idleSleepTimeUs();
2607 standbyDelay = microseconds(activeSleepTime*2);
2608 }
2609
2610 // put audio hardware into standby after short delay
2611 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2612 mSuspended) {
2613 // wait until we have something to do...
2614 if (!mStandby) {
2615 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002616 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002617 mStandby = true;
2618 mBytesWritten = 0;
2619 }
2620
2621 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2622 // we're about to wait, flush the binder command buffer
2623 IPCThreadState::self()->flushCommands();
2624
2625 if (exitPending()) break;
2626
Eric Laurentfeb0db62011-07-22 09:04:31 -07002627 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002628 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2629 mWaitWorkCV.wait(mLock);
2630 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002631 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002632
2633 if (mMasterMute == false) {
2634 char value[PROPERTY_VALUE_MAX];
2635 property_get("ro.audio.silent", value, "0");
2636 if (atoi(value)) {
2637 LOGD("Silence is golden");
2638 setMasterMute(true);
2639 }
2640 }
2641
2642 standbyTime = systemTime() + standbyDelay;
2643 sleepTime = idleSleepTime;
2644 continue;
2645 }
2646 }
2647
2648 effectChains = mEffectChains;
2649
2650 // find out which tracks need to be processed
2651 if (mActiveTracks.size() != 0) {
2652 sp<Track> t = mActiveTracks[0].promote();
2653 if (t == 0) continue;
2654
2655 Track* const track = t.get();
2656 audio_track_cblk_t* cblk = track->cblk();
2657
2658 // The first time a track is added we wait
2659 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002660 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002661 !track->isPaused() && !track->isTerminated())
2662 {
2663 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2664
2665 if (track->mFillingUpStatus == Track::FS_FILLED) {
2666 track->mFillingUpStatus = Track::FS_ACTIVE;
2667 mLeftVolFloat = mRightVolFloat = 0;
2668 mLeftVolShort = mRightVolShort = 0;
2669 if (track->mState == TrackBase::RESUMING) {
2670 track->mState = TrackBase::ACTIVE;
2671 rampVolume = true;
2672 }
2673 } else if (cblk->server != 0) {
2674 // If the track is stopped before the first frame was mixed,
2675 // do not apply ramp
2676 rampVolume = true;
2677 }
2678 // compute volume for this track
2679 float left, right;
2680 if (track->isMuted() || mMasterMute || track->isPausing() ||
2681 mStreamTypes[track->type()].mute) {
2682 left = right = 0;
2683 if (track->isPausing()) {
2684 track->setPaused();
2685 }
2686 } else {
2687 float typeVolume = mStreamTypes[track->type()].volume;
2688 float v = mMasterVolume * typeVolume;
2689 float v_clamped = v * cblk->volume[0];
2690 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2691 left = v_clamped/MAX_GAIN;
2692 v_clamped = v * cblk->volume[1];
2693 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2694 right = v_clamped/MAX_GAIN;
2695 }
2696
2697 if (left != mLeftVolFloat || right != mRightVolFloat) {
2698 mLeftVolFloat = left;
2699 mRightVolFloat = right;
2700
2701 // If audio HAL implements volume control,
2702 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002703 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002704 left = 1.0f;
2705 right = 1.0f;
2706 }
2707
2708 // Convert volumes from float to 8.24
2709 uint32_t vl = (uint32_t)(left * (1 << 24));
2710 uint32_t vr = (uint32_t)(right * (1 << 24));
2711
2712 // Delegate volume control to effect in track effect chain if needed
2713 // only one effect chain can be present on DirectOutputThread, so if
2714 // there is one, the track is connected to it
2715 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002716 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002717 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002718 rampVolume = false;
2719 }
2720 }
2721
2722 // Convert volumes from 8.24 to 4.12 format
2723 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2724 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2725 leftVol = (uint16_t)v_clamped;
2726 v_clamped = (vr + (1 << 11)) >> 12;
2727 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2728 rightVol = (uint16_t)v_clamped;
2729 } else {
2730 leftVol = mLeftVolShort;
2731 rightVol = mRightVolShort;
2732 rampVolume = false;
2733 }
2734
2735 // reset retry count
2736 track->mRetryCount = kMaxTrackRetriesDirect;
2737 activeTrack = t;
2738 mixerStatus = MIXER_TRACKS_READY;
2739 } else {
2740 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2741 if (track->isStopped()) {
2742 track->reset();
2743 }
2744 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2745 // We have consumed all the buffers of this track.
2746 // Remove it from the list of active tracks.
2747 trackToRemove = track;
2748 } else {
2749 // No buffers for this track. Give it a few chances to
2750 // fill a buffer, then remove it from active list.
2751 if (--(track->mRetryCount) <= 0) {
2752 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2753 trackToRemove = track;
2754 } else {
2755 mixerStatus = MIXER_TRACKS_ENABLED;
2756 }
2757 }
2758 }
2759 }
2760
2761 // remove all the tracks that need to be...
2762 if (UNLIKELY(trackToRemove != 0)) {
2763 mActiveTracks.remove(trackToRemove);
2764 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002765 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2766 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002767 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002768 }
2769 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002770 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002771 }
2772 }
2773
Eric Laurentde070132010-07-13 04:45:46 -07002774 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 }
2776
2777 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2778 AudioBufferProvider::Buffer buffer;
2779 size_t frameCount = mFrameCount;
2780 curBuf = (int8_t *)mMixBuffer;
2781 // output audio to hardware
2782 while (frameCount) {
2783 buffer.frameCount = frameCount;
Mike J. Chen535235c2011-08-15 13:28:26 -07002784 activeTrack->getNextBuffer(&buffer,
2785 AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002786 if (UNLIKELY(buffer.raw == 0)) {
2787 memset(curBuf, 0, frameCount * mFrameSize);
2788 break;
2789 }
2790 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2791 frameCount -= buffer.frameCount;
2792 curBuf += buffer.frameCount * mFrameSize;
2793 activeTrack->releaseBuffer(&buffer);
2794 }
2795 sleepTime = 0;
2796 standbyTime = systemTime() + standbyDelay;
2797 } else {
2798 if (sleepTime == 0) {
2799 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2800 sleepTime = activeSleepTime;
2801 } else {
2802 sleepTime = idleSleepTime;
2803 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002804 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002805 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2806 sleepTime = 0;
2807 }
2808 }
2809
2810 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002811 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002812 }
2813 // sleepTime == 0 means we must write to audio hardware
2814 if (sleepTime == 0) {
2815 if (mixerStatus == MIXER_TRACKS_READY) {
2816 applyVolume(leftVol, rightVol, rampVolume);
2817 }
2818 for (size_t i = 0; i < effectChains.size(); i ++) {
2819 effectChains[i]->process_l();
2820 }
Eric Laurentde070132010-07-13 04:45:46 -07002821 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822
2823 mLastWriteTime = systemTime();
2824 mInWrite = true;
2825 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002826 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002827 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2828 mNumWrites++;
2829 mInWrite = false;
2830 mStandby = false;
2831 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002832 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002833 usleep(sleepTime);
2834 }
2835
2836 // finally let go of removed track, without the lock held
2837 // since we can't guarantee the destructors won't acquire that
2838 // same lock.
2839 trackToRemove.clear();
2840 activeTrack.clear();
2841
2842 // Effect chains will be actually deleted here if they were removed from
2843 // mEffectChains list during mixing or effects processing
2844 effectChains.clear();
2845 }
2846
2847 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002848 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002849 }
2850
Eric Laurentfeb0db62011-07-22 09:04:31 -07002851 releaseWakeLock();
2852
Mathias Agopian65ab4712010-07-14 17:59:35 -07002853 LOGV("DirectOutputThread %p exiting", this);
2854 return false;
2855}
2856
2857// getTrackName_l() must be called with ThreadBase::mLock held
2858int AudioFlinger::DirectOutputThread::getTrackName_l()
2859{
2860 return 0;
2861}
2862
2863// deleteTrackName_l() must be called with ThreadBase::mLock held
2864void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2865{
2866}
2867
2868// checkForNewParameters_l() must be called with ThreadBase::mLock held
2869bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2870{
2871 bool reconfig = false;
2872
2873 while (!mNewParameters.isEmpty()) {
2874 status_t status = NO_ERROR;
2875 String8 keyValuePair = mNewParameters[0];
2876 AudioParameter param = AudioParameter(keyValuePair);
2877 int value;
2878
2879 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2880 // do not accept frame count changes if tracks are open as the track buffer
2881 // size depends on frame count and correct behavior would not be garantied
2882 // if frame count is changed after track creation
2883 if (!mTracks.isEmpty()) {
2884 status = INVALID_OPERATION;
2885 } else {
2886 reconfig = true;
2887 }
2888 }
2889 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002890 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002891 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002892 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002893 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002894 mStandby = true;
2895 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002896 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002897 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002898 }
2899 if (status == NO_ERROR && reconfig) {
2900 readOutputParameters();
2901 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2902 }
2903 }
2904
2905 mNewParameters.removeAt(0);
2906
2907 mParamStatus = status;
2908 mParamCond.signal();
2909 mWaitWorkCV.wait(mLock);
2910 }
2911 return reconfig;
2912}
2913
2914uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2915{
2916 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002917 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002918 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002919 } else {
2920 time = 10000;
2921 }
2922 return time;
2923}
2924
2925uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2926{
2927 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002928 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002929 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002930 } else {
2931 time = 10000;
2932 }
2933 return time;
2934}
2935
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002936uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2937{
2938 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002939 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002940 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2941 } else {
2942 time = 10000;
2943 }
2944 return time;
2945}
2946
2947
Mathias Agopian65ab4712010-07-14 17:59:35 -07002948// ----------------------------------------------------------------------------
2949
2950AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2951 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2952{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002953 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002954 addOutputTrack(mainThread);
2955}
2956
2957AudioFlinger::DuplicatingThread::~DuplicatingThread()
2958{
2959 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2960 mOutputTracks[i]->destroy();
2961 }
2962 mOutputTracks.clear();
2963}
2964
2965bool AudioFlinger::DuplicatingThread::threadLoop()
2966{
2967 Vector< sp<Track> > tracksToRemove;
2968 uint32_t mixerStatus = MIXER_IDLE;
2969 nsecs_t standbyTime = systemTime();
2970 size_t mixBufferSize = mFrameCount*mFrameSize;
2971 SortedVector< sp<OutputTrack> > outputTracks;
2972 uint32_t writeFrames = 0;
2973 uint32_t activeSleepTime = activeSleepTimeUs();
2974 uint32_t idleSleepTime = idleSleepTimeUs();
2975 uint32_t sleepTime = idleSleepTime;
2976 Vector< sp<EffectChain> > effectChains;
2977
Eric Laurentfeb0db62011-07-22 09:04:31 -07002978 acquireWakeLock();
2979
Mathias Agopian65ab4712010-07-14 17:59:35 -07002980 while (!exitPending())
2981 {
2982 processConfigEvents();
2983
2984 mixerStatus = MIXER_IDLE;
2985 { // scope for the mLock
2986
2987 Mutex::Autolock _l(mLock);
2988
2989 if (checkForNewParameters_l()) {
2990 mixBufferSize = mFrameCount*mFrameSize;
2991 updateWaitTime();
2992 activeSleepTime = activeSleepTimeUs();
2993 idleSleepTime = idleSleepTimeUs();
2994 }
2995
2996 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2997
2998 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2999 outputTracks.add(mOutputTracks[i]);
3000 }
3001
3002 // put audio hardware into standby after short delay
3003 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
3004 mSuspended) {
3005 if (!mStandby) {
3006 for (size_t i = 0; i < outputTracks.size(); i++) {
3007 outputTracks[i]->stop();
3008 }
3009 mStandby = true;
3010 mBytesWritten = 0;
3011 }
3012
3013 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3014 // we're about to wait, flush the binder command buffer
3015 IPCThreadState::self()->flushCommands();
3016 outputTracks.clear();
3017
3018 if (exitPending()) break;
3019
Eric Laurentfeb0db62011-07-22 09:04:31 -07003020 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003021 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
3022 mWaitWorkCV.wait(mLock);
3023 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003024 acquireWakeLock_l();
3025
Mathias Agopian65ab4712010-07-14 17:59:35 -07003026 if (mMasterMute == false) {
3027 char value[PROPERTY_VALUE_MAX];
3028 property_get("ro.audio.silent", value, "0");
3029 if (atoi(value)) {
3030 LOGD("Silence is golden");
3031 setMasterMute(true);
3032 }
3033 }
3034
3035 standbyTime = systemTime() + kStandbyTimeInNsecs;
3036 sleepTime = idleSleepTime;
3037 continue;
3038 }
3039 }
3040
3041 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3042
3043 // prevent any changes in effect chain list and in each effect chain
3044 // during mixing and effect process as the audio buffers could be deleted
3045 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003046 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003047 }
3048
3049 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3050 // mix buffers...
3051 if (outputsReady(outputTracks)) {
Mike J. Chen535235c2011-08-15 13:28:26 -07003052 mAudioMixer->process(AudioBufferProvider::kInvalidPTS);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003053 } else {
3054 memset(mMixBuffer, 0, mixBufferSize);
3055 }
3056 sleepTime = 0;
3057 writeFrames = mFrameCount;
3058 } else {
3059 if (sleepTime == 0) {
3060 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3061 sleepTime = activeSleepTime;
3062 } else {
3063 sleepTime = idleSleepTime;
3064 }
3065 } else if (mBytesWritten != 0) {
3066 // flush remaining overflow buffers in output tracks
3067 for (size_t i = 0; i < outputTracks.size(); i++) {
3068 if (outputTracks[i]->isActive()) {
3069 sleepTime = 0;
3070 writeFrames = 0;
3071 memset(mMixBuffer, 0, mixBufferSize);
3072 break;
3073 }
3074 }
3075 }
3076 }
3077
3078 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003079 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003080 }
3081 // sleepTime == 0 means we must write to audio hardware
3082 if (sleepTime == 0) {
3083 for (size_t i = 0; i < effectChains.size(); i ++) {
3084 effectChains[i]->process_l();
3085 }
3086 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003087 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088
3089 standbyTime = systemTime() + kStandbyTimeInNsecs;
3090 for (size_t i = 0; i < outputTracks.size(); i++) {
3091 outputTracks[i]->write(mMixBuffer, writeFrames);
3092 }
3093 mStandby = false;
3094 mBytesWritten += mixBufferSize;
3095 } else {
3096 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003097 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003098 usleep(sleepTime);
3099 }
3100
3101 // finally let go of all our tracks, without the lock held
3102 // since we can't guarantee the destructors won't acquire that
3103 // same lock.
3104 tracksToRemove.clear();
3105 outputTracks.clear();
3106
3107 // Effect chains will be actually deleted here if they were removed from
3108 // mEffectChains list during mixing or effects processing
3109 effectChains.clear();
3110 }
3111
Eric Laurentfeb0db62011-07-22 09:04:31 -07003112 releaseWakeLock();
3113
Mathias Agopian65ab4712010-07-14 17:59:35 -07003114 return false;
3115}
3116
3117void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3118{
3119 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3120 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3121 this,
3122 mSampleRate,
3123 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003124 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003125 frameCount);
3126 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003127 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003128 mOutputTracks.add(outputTrack);
3129 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
3130 updateWaitTime();
3131 }
3132}
3133
3134void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3135{
3136 Mutex::Autolock _l(mLock);
3137 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3138 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3139 mOutputTracks[i]->destroy();
3140 mOutputTracks.removeAt(i);
3141 updateWaitTime();
3142 return;
3143 }
3144 }
3145 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
3146}
3147
3148void AudioFlinger::DuplicatingThread::updateWaitTime()
3149{
3150 mWaitTimeMs = UINT_MAX;
3151 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3152 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3153 if (strong != NULL) {
3154 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3155 if (waitTimeMs < mWaitTimeMs) {
3156 mWaitTimeMs = waitTimeMs;
3157 }
3158 }
3159 }
3160}
3161
3162
3163bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3164{
3165 for (size_t i = 0; i < outputTracks.size(); i++) {
3166 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3167 if (thread == 0) {
3168 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3169 return false;
3170 }
3171 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3172 if (playbackThread->standby() && !playbackThread->isSuspended()) {
3173 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
3174 return false;
3175 }
3176 }
3177 return true;
3178}
3179
3180uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3181{
3182 return (mWaitTimeMs * 1000) / 2;
3183}
3184
3185// ----------------------------------------------------------------------------
3186
3187// TrackBase constructor must be called with AudioFlinger::mLock held
3188AudioFlinger::ThreadBase::TrackBase::TrackBase(
3189 const wp<ThreadBase>& thread,
3190 const sp<Client>& client,
3191 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003192 uint32_t format,
3193 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 int frameCount,
3195 uint32_t flags,
3196 const sp<IMemory>& sharedBuffer,
3197 int sessionId)
3198 : RefBase(),
3199 mThread(thread),
3200 mClient(client),
3201 mCblk(0),
3202 mFrameCount(0),
3203 mState(IDLE),
3204 mClientTid(-1),
3205 mFormat(format),
3206 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3207 mSessionId(sessionId)
3208{
3209 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3210
3211 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3212 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003213 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003214 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3215 if (sharedBuffer == 0) {
3216 size += bufferSize;
3217 }
3218
3219 if (client != NULL) {
3220 mCblkMemory = client->heap()->allocate(size);
3221 if (mCblkMemory != 0) {
3222 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3223 if (mCblk) { // construct the shared structure in-place.
3224 new(mCblk) audio_track_cblk_t();
3225 // clear all buffers
3226 mCblk->frameCount = frameCount;
3227 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003228 mChannelCount = channelCount;
3229 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 if (sharedBuffer == 0) {
3231 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3232 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3233 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003234 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003235 mCblk->flags = CBLK_UNDERRUN_ON;
3236 } else {
3237 mBuffer = sharedBuffer->pointer();
3238 }
3239 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3240 }
3241 } else {
3242 LOGE("not enough memory for AudioTrack size=%u", size);
3243 client->heap()->dump("AudioTrack");
3244 return;
3245 }
3246 } else {
3247 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3248 if (mCblk) { // construct the shared structure in-place.
3249 new(mCblk) audio_track_cblk_t();
3250 // clear all buffers
3251 mCblk->frameCount = frameCount;
3252 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003253 mChannelCount = channelCount;
3254 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003255 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3256 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3257 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003258 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003259 mCblk->flags = CBLK_UNDERRUN_ON;
3260 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3261 }
3262 }
3263}
3264
3265AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3266{
3267 if (mCblk) {
3268 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3269 if (mClient == NULL) {
3270 delete mCblk;
3271 }
3272 }
3273 mCblkMemory.clear(); // and free the shared memory
3274 if (mClient != NULL) {
3275 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3276 mClient.clear();
3277 }
3278}
3279
3280void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3281{
3282 buffer->raw = 0;
3283 mFrameCount = buffer->frameCount;
3284 step();
3285 buffer->frameCount = 0;
3286}
3287
3288bool AudioFlinger::ThreadBase::TrackBase::step() {
3289 bool result;
3290 audio_track_cblk_t* cblk = this->cblk();
3291
3292 result = cblk->stepServer(mFrameCount);
3293 if (!result) {
3294 LOGV("stepServer failed acquiring cblk mutex");
3295 mFlags |= STEPSERVER_FAILED;
3296 }
3297 return result;
3298}
3299
3300void AudioFlinger::ThreadBase::TrackBase::reset() {
3301 audio_track_cblk_t* cblk = this->cblk();
3302
3303 cblk->user = 0;
3304 cblk->server = 0;
3305 cblk->userBase = 0;
3306 cblk->serverBase = 0;
3307 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3308 LOGV("TrackBase::reset");
3309}
3310
3311sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3312{
3313 return mCblkMemory;
3314}
3315
3316int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3317 return (int)mCblk->sampleRate;
3318}
3319
3320int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003321 return (const int)mChannelCount;
3322}
3323
3324uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3325 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003326}
3327
3328void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3329 audio_track_cblk_t* cblk = this->cblk();
3330 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3331 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3332
3333 // Check validity of returned pointer in case the track control block would have been corrupted.
3334 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3335 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3336 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 -07003337 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003338 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003339 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003340 return 0;
3341 }
3342
3343 return bufferStart;
3344}
3345
3346// ----------------------------------------------------------------------------
3347
3348// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3349AudioFlinger::PlaybackThread::Track::Track(
3350 const wp<ThreadBase>& thread,
3351 const sp<Client>& client,
3352 int streamType,
3353 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003354 uint32_t format,
3355 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003356 int frameCount,
3357 const sp<IMemory>& sharedBuffer,
3358 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003359 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003360 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3361 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003362{
3363 if (mCblk != NULL) {
3364 sp<ThreadBase> baseThread = thread.promote();
3365 if (baseThread != 0) {
3366 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3367 mName = playbackThread->getTrackName_l();
3368 mMainBuffer = playbackThread->mixBuffer();
3369 }
3370 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3371 if (mName < 0) {
3372 LOGE("no more track names available");
3373 }
3374 mVolume[0] = 1.0f;
3375 mVolume[1] = 1.0f;
3376 mStreamType = streamType;
3377 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3378 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003379 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003380 }
3381}
3382
3383AudioFlinger::PlaybackThread::Track::~Track()
3384{
3385 LOGV("PlaybackThread::Track destructor");
3386 sp<ThreadBase> thread = mThread.promote();
3387 if (thread != 0) {
3388 Mutex::Autolock _l(thread->mLock);
3389 mState = TERMINATED;
3390 }
3391}
3392
3393void AudioFlinger::PlaybackThread::Track::destroy()
3394{
3395 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3396 // by removing it from mTracks vector, so there is a risk that this Tracks's
3397 // desctructor is called. As the destructor needs to lock mLock,
3398 // we must acquire a strong reference on this Track before locking mLock
3399 // here so that the destructor is called only when exiting this function.
3400 // On the other hand, as long as Track::destroy() is only called by
3401 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3402 // this Track with its member mTrack.
3403 sp<Track> keep(this);
3404 { // scope for mLock
3405 sp<ThreadBase> thread = mThread.promote();
3406 if (thread != 0) {
3407 if (!isOutputTrack()) {
3408 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003409 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003410 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003411 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003412
3413 // to track the speaker usage
3414 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415 }
3416 AudioSystem::releaseOutput(thread->id());
3417 }
3418 Mutex::Autolock _l(thread->mLock);
3419 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3420 playbackThread->destroyTrack_l(this);
3421 }
3422 }
3423}
3424
3425void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3426{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003427 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 -07003428 mName - AudioMixer::TRACK0,
3429 (mClient == NULL) ? getpid() : mClient->pid(),
3430 mStreamType,
3431 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003432 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003433 mSessionId,
3434 mFrameCount,
3435 mState,
3436 mMute,
3437 mFillingUpStatus,
3438 mCblk->sampleRate,
3439 mCblk->volume[0],
3440 mCblk->volume[1],
3441 mCblk->server,
3442 mCblk->user,
3443 (int)mMainBuffer,
3444 (int)mAuxBuffer);
3445}
3446
Mike J. Chen535235c2011-08-15 13:28:26 -07003447status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
3448 AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003449{
3450 audio_track_cblk_t* cblk = this->cblk();
3451 uint32_t framesReady;
3452 uint32_t framesReq = buffer->frameCount;
3453
3454 // Check if last stepServer failed, try to step now
3455 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3456 if (!step()) goto getNextBuffer_exit;
3457 LOGV("stepServer recovered");
3458 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3459 }
3460
3461 framesReady = cblk->framesReady();
3462
3463 if (LIKELY(framesReady)) {
3464 uint32_t s = cblk->server;
3465 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3466
3467 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3468 if (framesReq > framesReady) {
3469 framesReq = framesReady;
3470 }
3471 if (s + framesReq > bufferEnd) {
3472 framesReq = bufferEnd - s;
3473 }
3474
3475 buffer->raw = getBuffer(s, framesReq);
3476 if (buffer->raw == 0) goto getNextBuffer_exit;
3477
3478 buffer->frameCount = framesReq;
3479 return NO_ERROR;
3480 }
3481
3482getNextBuffer_exit:
3483 buffer->raw = 0;
3484 buffer->frameCount = 0;
3485 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3486 return NOT_ENOUGH_DATA;
3487}
3488
Mike J. Chen535235c2011-08-15 13:28:26 -07003489uint32_t AudioFlinger::PlaybackThread::Track::framesReady() const{
3490 return mCblk->framesReady();
3491}
3492
Mathias Agopian65ab4712010-07-14 17:59:35 -07003493bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003494 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495
Mike J. Chen535235c2011-08-15 13:28:26 -07003496 if (framesReady() >= mCblk->frameCount ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07003497 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3498 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003499 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003500 return true;
3501 }
3502 return false;
3503}
3504
3505status_t AudioFlinger::PlaybackThread::Track::start()
3506{
3507 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003508 LOGV("start(%d), calling thread %d session %d",
3509 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003510 sp<ThreadBase> thread = mThread.promote();
3511 if (thread != 0) {
3512 Mutex::Autolock _l(thread->mLock);
3513 int state = mState;
3514 // here the track could be either new, or restarted
3515 // in both cases "unstop" the track
3516 if (mState == PAUSED) {
3517 mState = TrackBase::RESUMING;
3518 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3519 } else {
3520 mState = TrackBase::ACTIVE;
3521 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3522 }
3523
3524 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3525 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003526 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003527 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003528 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003529 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003530
3531 // to track the speaker usage
3532 if (status == NO_ERROR) {
3533 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3534 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003535 }
3536 if (status == NO_ERROR) {
3537 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3538 playbackThread->addTrack_l(this);
3539 } else {
3540 mState = state;
3541 }
3542 } else {
3543 status = BAD_VALUE;
3544 }
3545 return status;
3546}
3547
3548void AudioFlinger::PlaybackThread::Track::stop()
3549{
3550 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3551 sp<ThreadBase> thread = mThread.promote();
3552 if (thread != 0) {
3553 Mutex::Autolock _l(thread->mLock);
3554 int state = mState;
3555 if (mState > STOPPED) {
3556 mState = STOPPED;
3557 // If the track is not active (PAUSED and buffers full), flush buffers
3558 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3559 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3560 reset();
3561 }
3562 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3563 }
3564 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3565 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003566 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003567 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003568 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003569 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003570
3571 // to track the speaker usage
3572 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003573 }
3574 }
3575}
3576
3577void AudioFlinger::PlaybackThread::Track::pause()
3578{
3579 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3580 sp<ThreadBase> thread = mThread.promote();
3581 if (thread != 0) {
3582 Mutex::Autolock _l(thread->mLock);
3583 if (mState == ACTIVE || mState == RESUMING) {
3584 mState = PAUSING;
3585 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3586 if (!isOutputTrack()) {
3587 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003588 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003589 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003590 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003591 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003592
3593 // to track the speaker usage
3594 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 }
3596 }
3597 }
3598}
3599
3600void AudioFlinger::PlaybackThread::Track::flush()
3601{
3602 LOGV("flush(%d)", mName);
3603 sp<ThreadBase> thread = mThread.promote();
3604 if (thread != 0) {
3605 Mutex::Autolock _l(thread->mLock);
3606 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3607 return;
3608 }
3609 // No point remaining in PAUSED state after a flush => go to
3610 // STOPPED state
3611 mState = STOPPED;
3612
Eric Laurent38ccae22011-03-28 18:37:07 -07003613 // do not reset the track if it is still in the process of being stopped or paused.
3614 // this will be done by prepareTracks_l() when the track is stopped.
3615 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3616 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3617 reset();
3618 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 }
3620}
3621
3622void AudioFlinger::PlaybackThread::Track::reset()
3623{
3624 // Do not reset twice to avoid discarding data written just after a flush and before
3625 // the audioflinger thread detects the track is stopped.
3626 if (!mResetDone) {
3627 TrackBase::reset();
3628 // Force underrun condition to avoid false underrun callback until first data is
3629 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003630 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3631 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632 mFillingUpStatus = FS_FILLING;
3633 mResetDone = true;
3634 }
3635}
3636
3637void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3638{
3639 mMute = muted;
3640}
3641
3642void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3643{
3644 mVolume[0] = left;
3645 mVolume[1] = right;
3646}
3647
3648status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3649{
3650 status_t status = DEAD_OBJECT;
3651 sp<ThreadBase> thread = mThread.promote();
3652 if (thread != 0) {
3653 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3654 status = playbackThread->attachAuxEffect(this, EffectId);
3655 }
3656 return status;
3657}
3658
3659void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3660{
3661 mAuxEffectId = EffectId;
3662 mAuxBuffer = buffer;
3663}
3664
Mike J. Chen535235c2011-08-15 13:28:26 -07003665// timed audio tracks
3666
3667sp<AudioFlinger::PlaybackThread::TimedTrack>
3668AudioFlinger::PlaybackThread::TimedTrack::create(
3669 const wp<ThreadBase>& thread,
3670 const sp<Client>& client,
3671 int streamType,
3672 uint32_t sampleRate,
3673 uint32_t format,
3674 uint32_t channelMask,
3675 int frameCount,
3676 const sp<IMemory>& sharedBuffer,
3677 int sessionId) {
3678 if (!client->reserveTimedTrack())
3679 return NULL;
3680
3681 sp<TimedTrack> track = new TimedTrack(
3682 thread, client, streamType, sampleRate, format, channelMask, frameCount,
3683 sharedBuffer, sessionId);
3684
3685 if (track == NULL) {
3686 client->releaseTimedTrack();
3687 return NULL;
3688 }
3689
3690 return track;
3691}
3692
3693AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
3694 const wp<ThreadBase>& thread,
3695 const sp<Client>& client,
3696 int streamType,
3697 uint32_t sampleRate,
3698 uint32_t format,
3699 uint32_t channelMask,
3700 int frameCount,
3701 const sp<IMemory>& sharedBuffer,
3702 int sessionId)
3703 : Track(thread, client, streamType, sampleRate, format, channelMask,
3704 frameCount, sharedBuffer, sessionId),
3705 mTimedSilenceBuffer(NULL),
3706 mTimedSilenceBufferSize(0),
3707 mTimedAudioOutputOnTime(false),
3708 mMediaTimeTransformValid(false)
3709{
3710 LocalClock lc;
3711 mLocalTimeFreq = lc.getLocalFreq();
3712
3713 mLocalTimeToSampleTransform.a_zero = 0;
3714 mLocalTimeToSampleTransform.b_zero = 0;
3715 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
3716 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
3717 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
3718 &mLocalTimeToSampleTransform.a_to_b_denom);
3719}
3720
3721AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
3722 mClient->releaseTimedTrack();
3723 delete [] mTimedSilenceBuffer;
3724}
3725
3726status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
3727 size_t size, sp<IMemory>* buffer) {
3728
3729 Mutex::Autolock _l(mTimedBufferQueueLock);
3730
3731 trimTimedBufferQueue_l();
3732
3733 // lazily initialize the shared memory heap for timed buffers
3734 if (mTimedMemoryDealer == NULL) {
3735 const int kTimedBufferHeapSize = 512 << 10;
3736
3737 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
3738 "AudioFlingerTimed");
3739 if (mTimedMemoryDealer == NULL)
3740 return NO_MEMORY;
3741 }
3742
3743 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
3744 if (newBuffer == NULL) {
3745 newBuffer = mTimedMemoryDealer->allocate(size);
3746 if (newBuffer == NULL)
3747 return NO_MEMORY;
3748 }
3749
3750 *buffer = newBuffer;
3751 return NO_ERROR;
3752}
3753
3754// caller must hold mTimedBufferQueueLock
3755void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
3756 int64_t mediaTimeNow;
3757 {
3758 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3759 if (!mMediaTimeTransformValid)
3760 return;
3761
3762 int64_t targetTimeNow;
3763 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
3764 ? CCHelper::getCommonTime(&targetTimeNow)
3765 : CCHelper::getLocalTime(&targetTimeNow);
3766
3767 if (OK != res)
3768 return;
3769
3770 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
3771 &mediaTimeNow)) {
3772 return;
3773 }
3774 }
3775
3776 size_t trimIndex;
3777 for (trimIndex = 0; trimIndex < mTimedBufferQueue.size(); trimIndex++) {
3778 if (mTimedBufferQueue[trimIndex].pts() > mediaTimeNow)
3779 break;
3780 }
3781
3782 if (trimIndex) {
3783 mTimedBufferQueue.removeItemsAt(0, trimIndex);
3784 }
3785}
3786
3787status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
3788 const sp<IMemory>& buffer, int64_t pts) {
3789
3790 {
3791 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3792 if (!mMediaTimeTransformValid)
3793 return INVALID_OPERATION;
3794 }
3795
3796 Mutex::Autolock _l(mTimedBufferQueueLock);
3797
3798 mTimedBufferQueue.add(TimedBuffer(buffer, pts));
3799
3800 return NO_ERROR;
3801}
3802
3803status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
3804 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
3805
3806 LOGV("%s az=%lld bz=%lld n=%d d=%u tgt=%d", __PRETTY_FUNCTION__,
3807 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
3808 target);
3809
3810 if (!(target == TimedAudioTrack::LOCAL_TIME ||
3811 target == TimedAudioTrack::COMMON_TIME)) {
3812 return BAD_VALUE;
3813 }
3814
3815 Mutex::Autolock lock(mMediaTimeTransformLock);
3816 mMediaTimeTransform = xform;
3817 mMediaTimeTransformTarget = target;
3818 mMediaTimeTransformValid = true;
3819
3820 return NO_ERROR;
3821}
3822
3823#define min(a, b) ((a) < (b) ? (a) : (b))
3824
3825// implementation of getNextBuffer for tracks whose buffers have timestamps
3826status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
3827 AudioBufferProvider::Buffer* buffer, int64_t pts)
3828{
3829 if (pts == AudioBufferProvider::kInvalidPTS) {
3830 buffer->raw = 0;
3831 buffer->frameCount = 0;
3832 return INVALID_OPERATION;
3833 }
3834
3835 // get ahold of the output stream that these samples will be written to
3836 sp<ThreadBase> thread = mThread.promote();
3837 if (thread == NULL) {
3838 buffer->raw = 0;
3839 buffer->frameCount = 0;
3840 return INVALID_OPERATION;
3841 }
3842 PlaybackThread* playbackThread = static_cast<PlaybackThread*>(thread.get());
3843
3844 Mutex::Autolock _l(mTimedBufferQueueLock);
3845
3846 while (true) {
3847
3848 // if we have no timed buffers, then fail
3849 if (mTimedBufferQueue.isEmpty()) {
3850 buffer->raw = 0;
3851 buffer->frameCount = 0;
3852 return NOT_ENOUGH_DATA;
3853 }
3854
3855 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
3856
3857 // calculate the PTS of the head of the timed buffer queue expressed in
3858 // local time
3859 int64_t headLocalPTS;
3860 {
3861 Mutex::Autolock mttLock(mMediaTimeTransformLock);
3862
3863 assert(mMediaTimeTransformValid);
3864
3865 if (mMediaTimeTransform.a_to_b_denom == 0) {
3866 // the transform represents a pause, so yield silence
3867 timedYieldSilence(buffer->frameCount, buffer);
3868 return NO_ERROR;
3869 }
3870
3871 int64_t transformedPTS;
3872 if (!mMediaTimeTransform.doForwardTransform(head.pts(),
3873 &transformedPTS)) {
3874 // the transform failed. this shouldn't happen, but if it does
3875 // then just drop this buffer
3876 LOGW("timedGetNextBuffer transform failed");
3877 buffer->raw = 0;
3878 buffer->frameCount = 0;
3879 mTimedBufferQueue.removeAt(0);
3880 return NO_ERROR;
3881 }
3882
3883 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
3884 if (OK != CCHelper::commonTimeToLocalTime(transformedPTS,
3885 &headLocalPTS)) {
3886 buffer->raw = 0;
3887 buffer->frameCount = 0;
3888 return INVALID_OPERATION;
3889 }
3890 } else {
3891 headLocalPTS = transformedPTS;
3892 }
3893 }
3894
3895 // adjust the head buffer's PTS to reflect the portion of the head buffer
3896 // that has already been consumed
3897 int64_t effectivePTS = headLocalPTS +
3898 ((head.position() / mCblk->frameSize) * mLocalTimeFreq / sampleRate());
3899
3900 // Calculate the delta in samples between the head of the input buffer
3901 // queue and the start of the next output buffer that will be written.
3902 // If the transformation fails because of over or underflow, it means
3903 // that the sample's position in the output stream is so far out of
3904 // whack that it should just be dropped.
3905 int64_t sampleDelta;
3906 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
3907 LOGV("*** head buffer is too far from PTS: dropped buffer");
3908 mTimedBufferQueue.removeAt(0);
3909 continue;
3910 }
3911 if (!mLocalTimeToSampleTransform.doForwardTransform(
3912 (effectivePTS - pts) << 32, &sampleDelta)) {
3913 LOGV("*** too late during sample rate transform: dropped buffer");
3914 mTimedBufferQueue.removeAt(0);
3915 continue;
3916 }
3917
3918 LOGV("*** %s head.pts=%lld head.pos=%d pts=%lld sampleDelta=[%d.%08x]",
3919 __PRETTY_FUNCTION__, head.pts(), head.position(), pts,
3920 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) + (sampleDelta >> 32)),
3921 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
3922
3923 // if the delta between the ideal placement for the next input sample and
3924 // the current output position is within this threshold, then we will
3925 // concatenate the next input samples to the previous output
3926 const int64_t kSampleContinuityThreshold =
3927 (static_cast<int64_t>(sampleRate()) << 32) / 10;
3928
3929 // if this is the first buffer of audio that we're emitting from this track
3930 // then it should be almost exactly on time.
3931 const int64_t kSampleStartupThreshold = 1LL << 32;
3932
3933 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
3934 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
3935 // the next input is close enough to being on time, so concatenate it
3936 // with the last output
3937 timedYieldSamples(buffer);
3938
3939 LOGV("*** on time: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3940 return NO_ERROR;
3941 } else if (sampleDelta > 0) {
3942 // the gap between the current output position and the proper start of
3943 // the next input sample is too big, so fill it with silence
3944 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
3945
3946 timedYieldSilence(framesUntilNextInput, buffer);
3947 LOGV("*** silence: frameCount=%u", buffer->frameCount);
3948 return NO_ERROR;
3949 } else {
3950 // the next input sample is late
3951 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
3952 size_t onTimeSamplePosition =
3953 head.position() + lateFrames * mCblk->frameSize;
3954
3955 if (onTimeSamplePosition > head.buffer()->size()) {
3956 // all the remaining samples in the head are too late, so
3957 // drop it and move on
3958 LOGV("*** too late: dropped buffer");
3959 mTimedBufferQueue.removeAt(0);
3960 continue;
3961 } else {
3962 // skip over the late samples
3963 head.setPosition(onTimeSamplePosition);
3964
3965 // yield the available samples
3966 timedYieldSamples(buffer);
3967
3968 LOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
3969 return NO_ERROR;
3970 }
3971 }
3972 }
3973}
3974
3975// Yield samples from the timed buffer queue head up to the given output
3976// buffer's capacity.
3977//
3978// Caller must hold mTimedBufferQueueLock
3979void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples(
3980 AudioBufferProvider::Buffer* buffer) {
3981
3982 const TimedBuffer& head = mTimedBufferQueue[0];
3983
3984 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
3985 head.position());
3986
3987 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
3988 mCblk->frameSize);
3989 size_t framesRequested = buffer->frameCount;
3990 buffer->frameCount = min(framesLeftInHead, framesRequested);
3991
3992 mTimedAudioOutputOnTime = true;
3993}
3994
3995// Yield samples of silence up to the given output buffer's capacity
3996//
3997// Caller must hold mTimedBufferQueueLock
3998void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence(
3999 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
4000
4001 // lazily allocate a buffer filled with silence
4002 if (mTimedSilenceBufferSize < numFrames * mCblk->frameSize) {
4003 delete [] mTimedSilenceBuffer;
4004 mTimedSilenceBufferSize = numFrames * mCblk->frameSize;
4005 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
4006 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
4007 }
4008
4009 buffer->raw = mTimedSilenceBuffer;
4010 size_t framesRequested = buffer->frameCount;
4011 buffer->frameCount = min(numFrames, framesRequested);
4012
4013 mTimedAudioOutputOnTime = false;
4014}
4015
4016void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
4017 AudioBufferProvider::Buffer* buffer) {
4018
4019 Mutex::Autolock _l(mTimedBufferQueueLock);
4020
4021 if (buffer->raw != mTimedSilenceBuffer) {
4022 TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
4023 head.setPosition(head.position() + buffer->frameCount * mCblk->frameSize);
4024 if (static_cast<size_t>(head.position()) >= head.buffer()->size()) {
4025 mTimedBufferQueue.removeAt(0);
4026 }
4027 }
4028
4029 buffer->raw = 0;
4030 buffer->frameCount = 0;
4031}
4032
4033uint32_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
4034 Mutex::Autolock _l(mTimedBufferQueueLock);
4035
4036 uint32_t frames = 0;
4037 for (size_t i = 0; i < mTimedBufferQueue.size(); i++) {
4038 const TimedBuffer& tb = mTimedBufferQueue[i];
4039 frames += (tb.buffer()->size() - tb.position()) / mCblk->frameSize;
4040 }
4041
4042 return frames;
4043}
4044
4045AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
4046 : mPTS(0), mPosition(0) {}
4047
4048AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
4049 const sp<IMemory>& buffer, int64_t pts)
4050 : mBuffer(buffer), mPTS(pts), mPosition(0) {}
4051
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052// ----------------------------------------------------------------------------
4053
4054// RecordTrack constructor must be called with AudioFlinger::mLock held
4055AudioFlinger::RecordThread::RecordTrack::RecordTrack(
4056 const wp<ThreadBase>& thread,
4057 const sp<Client>& client,
4058 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004059 uint32_t format,
4060 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 int frameCount,
4062 uint32_t flags,
4063 int sessionId)
4064 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004065 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004066 mOverflow(false)
4067{
4068 if (mCblk != NULL) {
4069 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07004070 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004071 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07004072 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004073 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074 } else {
4075 mCblk->frameSize = sizeof(int8_t);
4076 }
4077 }
4078}
4079
4080AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
4081{
4082 sp<ThreadBase> thread = mThread.promote();
4083 if (thread != 0) {
4084 AudioSystem::releaseInput(thread->id());
4085 }
4086}
4087
Mike J. Chen535235c2011-08-15 13:28:26 -07004088status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089{
4090 audio_track_cblk_t* cblk = this->cblk();
4091 uint32_t framesAvail;
4092 uint32_t framesReq = buffer->frameCount;
4093
4094 // Check if last stepServer failed, try to step now
4095 if (mFlags & TrackBase::STEPSERVER_FAILED) {
4096 if (!step()) goto getNextBuffer_exit;
4097 LOGV("stepServer recovered");
4098 mFlags &= ~TrackBase::STEPSERVER_FAILED;
4099 }
4100
4101 framesAvail = cblk->framesAvailable_l();
4102
4103 if (LIKELY(framesAvail)) {
4104 uint32_t s = cblk->server;
4105 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
4106
4107 if (framesReq > framesAvail) {
4108 framesReq = framesAvail;
4109 }
4110 if (s + framesReq > bufferEnd) {
4111 framesReq = bufferEnd - s;
4112 }
4113
4114 buffer->raw = getBuffer(s, framesReq);
4115 if (buffer->raw == 0) goto getNextBuffer_exit;
4116
4117 buffer->frameCount = framesReq;
4118 return NO_ERROR;
4119 }
4120
4121getNextBuffer_exit:
4122 buffer->raw = 0;
4123 buffer->frameCount = 0;
4124 return NOT_ENOUGH_DATA;
4125}
4126
4127status_t AudioFlinger::RecordThread::RecordTrack::start()
4128{
4129 sp<ThreadBase> thread = mThread.promote();
4130 if (thread != 0) {
4131 RecordThread *recordThread = (RecordThread *)thread.get();
4132 return recordThread->start(this);
4133 } else {
4134 return BAD_VALUE;
4135 }
4136}
4137
4138void AudioFlinger::RecordThread::RecordTrack::stop()
4139{
4140 sp<ThreadBase> thread = mThread.promote();
4141 if (thread != 0) {
4142 RecordThread *recordThread = (RecordThread *)thread.get();
4143 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07004144 TrackBase::reset();
4145 // Force overerrun condition to avoid false overrun callback until first data is
4146 // read from buffer
4147 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 }
4149}
4150
4151void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
4152{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004153 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004154 (mClient == NULL) ? getpid() : mClient->pid(),
4155 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004156 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004157 mSessionId,
4158 mFrameCount,
4159 mState,
4160 mCblk->sampleRate,
4161 mCblk->server,
4162 mCblk->user);
4163}
4164
4165
4166// ----------------------------------------------------------------------------
4167
4168AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
4169 const wp<ThreadBase>& thread,
4170 DuplicatingThread *sourceThread,
4171 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004172 uint32_t format,
4173 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004174 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004175 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176 mActive(false), mSourceThread(sourceThread)
4177{
4178
4179 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
4180 if (mCblk != NULL) {
4181 mCblk->flags |= CBLK_DIRECTION_OUT;
4182 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
4183 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
4184 mOutBuffer.frameCount = 0;
4185 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004186 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
4187 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
4188 mCblk, mBuffer, mCblk->buffers,
4189 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004190 } else {
4191 LOGW("Error creating output track on thread %p", playbackThread);
4192 }
4193}
4194
4195AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
4196{
4197 clearBufferQueue();
4198}
4199
4200status_t AudioFlinger::PlaybackThread::OutputTrack::start()
4201{
4202 status_t status = Track::start();
4203 if (status != NO_ERROR) {
4204 return status;
4205 }
4206
4207 mActive = true;
4208 mRetryCount = 127;
4209 return status;
4210}
4211
4212void AudioFlinger::PlaybackThread::OutputTrack::stop()
4213{
4214 Track::stop();
4215 clearBufferQueue();
4216 mOutBuffer.frameCount = 0;
4217 mActive = false;
4218}
4219
4220bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
4221{
4222 Buffer *pInBuffer;
4223 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004224 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004225 bool outputBufferFull = false;
4226 inBuffer.frameCount = frames;
4227 inBuffer.i16 = data;
4228
4229 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
4230
4231 if (!mActive && frames != 0) {
4232 start();
4233 sp<ThreadBase> thread = mThread.promote();
4234 if (thread != 0) {
4235 MixerThread *mixerThread = (MixerThread *)thread.get();
4236 if (mCblk->frameCount > frames){
4237 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4238 uint32_t startFrames = (mCblk->frameCount - frames);
4239 pInBuffer = new Buffer;
4240 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
4241 pInBuffer->frameCount = startFrames;
4242 pInBuffer->i16 = pInBuffer->mBuffer;
4243 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
4244 mBufferQueue.add(pInBuffer);
4245 } else {
4246 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
4247 }
4248 }
4249 }
4250 }
4251
4252 while (waitTimeLeftMs) {
4253 // First write pending buffers, then new data
4254 if (mBufferQueue.size()) {
4255 pInBuffer = mBufferQueue.itemAt(0);
4256 } else {
4257 pInBuffer = &inBuffer;
4258 }
4259
4260 if (pInBuffer->frameCount == 0) {
4261 break;
4262 }
4263
4264 if (mOutBuffer.frameCount == 0) {
4265 mOutBuffer.frameCount = pInBuffer->frameCount;
4266 nsecs_t startTime = systemTime();
4267 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
4268 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
4269 outputBufferFull = true;
4270 break;
4271 }
4272 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
4273 if (waitTimeLeftMs >= waitTimeMs) {
4274 waitTimeLeftMs -= waitTimeMs;
4275 } else {
4276 waitTimeLeftMs = 0;
4277 }
4278 }
4279
4280 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
4281 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
4282 mCblk->stepUser(outFrames);
4283 pInBuffer->frameCount -= outFrames;
4284 pInBuffer->i16 += outFrames * channelCount;
4285 mOutBuffer.frameCount -= outFrames;
4286 mOutBuffer.i16 += outFrames * channelCount;
4287
4288 if (pInBuffer->frameCount == 0) {
4289 if (mBufferQueue.size()) {
4290 mBufferQueue.removeAt(0);
4291 delete [] pInBuffer->mBuffer;
4292 delete pInBuffer;
4293 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4294 } else {
4295 break;
4296 }
4297 }
4298 }
4299
4300 // If we could not write all frames, allocate a buffer and queue it for next time.
4301 if (inBuffer.frameCount) {
4302 sp<ThreadBase> thread = mThread.promote();
4303 if (thread != 0 && !thread->standby()) {
4304 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
4305 pInBuffer = new Buffer;
4306 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
4307 pInBuffer->frameCount = inBuffer.frameCount;
4308 pInBuffer->i16 = pInBuffer->mBuffer;
4309 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
4310 mBufferQueue.add(pInBuffer);
4311 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
4312 } else {
4313 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
4314 }
4315 }
4316 }
4317
4318 // Calling write() with a 0 length buffer, means that no more data will be written:
4319 // If no more buffers are pending, fill output track buffer to make sure it is started
4320 // by output mixer.
4321 if (frames == 0 && mBufferQueue.size() == 0) {
4322 if (mCblk->user < mCblk->frameCount) {
4323 frames = mCblk->frameCount - mCblk->user;
4324 pInBuffer = new Buffer;
4325 pInBuffer->mBuffer = new int16_t[frames * channelCount];
4326 pInBuffer->frameCount = frames;
4327 pInBuffer->i16 = pInBuffer->mBuffer;
4328 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
4329 mBufferQueue.add(pInBuffer);
4330 } else if (mActive) {
4331 stop();
4332 }
4333 }
4334
4335 return outputBufferFull;
4336}
4337
4338status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
4339{
4340 int active;
4341 status_t result;
4342 audio_track_cblk_t* cblk = mCblk;
4343 uint32_t framesReq = buffer->frameCount;
4344
4345// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
4346 buffer->frameCount = 0;
4347
4348 uint32_t framesAvail = cblk->framesAvailable();
4349
4350
4351 if (framesAvail == 0) {
4352 Mutex::Autolock _l(cblk->lock);
4353 goto start_loop_here;
4354 while (framesAvail == 0) {
4355 active = mActive;
4356 if (UNLIKELY(!active)) {
4357 LOGV("Not active and NO_MORE_BUFFERS");
4358 return AudioTrack::NO_MORE_BUFFERS;
4359 }
4360 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
4361 if (result != NO_ERROR) {
4362 return AudioTrack::NO_MORE_BUFFERS;
4363 }
4364 // read the server count again
4365 start_loop_here:
4366 framesAvail = cblk->framesAvailable_l();
4367 }
4368 }
4369
4370// if (framesAvail < framesReq) {
4371// return AudioTrack::NO_MORE_BUFFERS;
4372// }
4373
4374 if (framesReq > framesAvail) {
4375 framesReq = framesAvail;
4376 }
4377
4378 uint32_t u = cblk->user;
4379 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
4380
4381 if (u + framesReq > bufferEnd) {
4382 framesReq = bufferEnd - u;
4383 }
4384
4385 buffer->frameCount = framesReq;
4386 buffer->raw = (void *)cblk->buffer(u);
4387 return NO_ERROR;
4388}
4389
4390
4391void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
4392{
4393 size_t size = mBufferQueue.size();
4394 Buffer *pBuffer;
4395
4396 for (size_t i = 0; i < size; i++) {
4397 pBuffer = mBufferQueue.itemAt(i);
4398 delete [] pBuffer->mBuffer;
4399 delete pBuffer;
4400 }
4401 mBufferQueue.clear();
4402}
4403
4404// ----------------------------------------------------------------------------
4405
4406AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4407 : RefBase(),
4408 mAudioFlinger(audioFlinger),
4409 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
Mike J. Chen535235c2011-08-15 13:28:26 -07004410 mPid(pid),
4411 mTimedTrackCount(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004412{
4413 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4414}
4415
4416// Client destructor must be called with AudioFlinger::mLock held
4417AudioFlinger::Client::~Client()
4418{
4419 mAudioFlinger->removeClient_l(mPid);
4420}
4421
4422const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4423{
4424 return mMemoryDealer;
4425}
4426
Mike J. Chen535235c2011-08-15 13:28:26 -07004427// Reserve one of the limited slots for a timed audio track associated
4428// with this client
4429bool AudioFlinger::Client::reserveTimedTrack()
4430{
4431 const int kMaxTimedTracksPerClient = 4;
4432
4433 Mutex::Autolock _l(mTimedTrackLock);
4434
4435 if (mTimedTrackCount >= kMaxTimedTracksPerClient) {
4436 LOGW("can not create timed track - pid %d has exceeded the limit",
4437 mPid);
4438 return false;
4439 }
4440
4441 mTimedTrackCount++;
4442 return true;
4443}
4444
4445// Release a slot for a timed audio track
4446void AudioFlinger::Client::releaseTimedTrack()
4447{
4448 Mutex::Autolock _l(mTimedTrackLock);
4449 mTimedTrackCount--;
4450}
4451
Mathias Agopian65ab4712010-07-14 17:59:35 -07004452// ----------------------------------------------------------------------------
4453
4454AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4455 const sp<IAudioFlingerClient>& client,
4456 pid_t pid)
4457 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4458{
4459}
4460
4461AudioFlinger::NotificationClient::~NotificationClient()
4462{
4463 mClient.clear();
4464}
4465
4466void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4467{
4468 sp<NotificationClient> keep(this);
4469 {
4470 mAudioFlinger->removeNotificationClient(mPid);
4471 }
4472}
4473
4474// ----------------------------------------------------------------------------
4475
4476AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4477 : BnAudioTrack(),
4478 mTrack(track)
4479{
4480}
4481
4482AudioFlinger::TrackHandle::~TrackHandle() {
4483 // just stop the track on deletion, associated resources
4484 // will be freed from the main thread once all pending buffers have
4485 // been played. Unless it's not in the active track list, in which
4486 // case we free everything now...
4487 mTrack->destroy();
4488}
4489
4490status_t AudioFlinger::TrackHandle::start() {
4491 return mTrack->start();
4492}
4493
4494void AudioFlinger::TrackHandle::stop() {
4495 mTrack->stop();
4496}
4497
4498void AudioFlinger::TrackHandle::flush() {
4499 mTrack->flush();
4500}
4501
4502void AudioFlinger::TrackHandle::mute(bool e) {
4503 mTrack->mute(e);
4504}
4505
4506void AudioFlinger::TrackHandle::pause() {
4507 mTrack->pause();
4508}
4509
4510void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4511 mTrack->setVolume(left, right);
4512}
4513
4514sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4515 return mTrack->getCblk();
4516}
4517
4518status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4519{
4520 return mTrack->attachAuxEffect(EffectId);
4521}
4522
Mike J. Chen535235c2011-08-15 13:28:26 -07004523status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size,
4524 sp<IMemory>* buffer) {
4525 if (!mTrack->isTimedTrack())
4526 return INVALID_OPERATION;
4527
4528 PlaybackThread::TimedTrack* tt =
4529 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4530 return tt->allocateTimedBuffer(size, buffer);
4531}
4532
4533status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer,
4534 int64_t pts) {
4535 if (!mTrack->isTimedTrack())
4536 return INVALID_OPERATION;
4537
4538 PlaybackThread::TimedTrack* tt =
4539 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4540 return tt->queueTimedBuffer(buffer, pts);
4541}
4542
4543status_t AudioFlinger::TrackHandle::setMediaTimeTransform(
4544 const LinearTransform& xform, int target) {
4545
4546 if (!mTrack->isTimedTrack())
4547 return INVALID_OPERATION;
4548
4549 PlaybackThread::TimedTrack* tt =
4550 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get());
4551 return tt->setMediaTimeTransform(
4552 xform, static_cast<TimedAudioTrack::TargetTimeline>(target));
4553}
4554
Mathias Agopian65ab4712010-07-14 17:59:35 -07004555status_t AudioFlinger::TrackHandle::onTransact(
4556 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4557{
4558 return BnAudioTrack::onTransact(code, data, reply, flags);
4559}
4560
4561// ----------------------------------------------------------------------------
4562
4563sp<IAudioRecord> AudioFlinger::openRecord(
4564 pid_t pid,
4565 int input,
4566 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004567 uint32_t format,
4568 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004569 int frameCount,
4570 uint32_t flags,
4571 int *sessionId,
4572 status_t *status)
4573{
4574 sp<RecordThread::RecordTrack> recordTrack;
4575 sp<RecordHandle> recordHandle;
4576 sp<Client> client;
4577 wp<Client> wclient;
4578 status_t lStatus;
4579 RecordThread *thread;
4580 size_t inFrameCount;
4581 int lSessionId;
4582
4583 // check calling permissions
4584 if (!recordingAllowed()) {
4585 lStatus = PERMISSION_DENIED;
4586 goto Exit;
4587 }
4588
4589 // add client to list
4590 { // scope for mLock
4591 Mutex::Autolock _l(mLock);
4592 thread = checkRecordThread_l(input);
4593 if (thread == NULL) {
4594 lStatus = BAD_VALUE;
4595 goto Exit;
4596 }
4597
4598 wclient = mClients.valueFor(pid);
4599 if (wclient != NULL) {
4600 client = wclient.promote();
4601 } else {
4602 client = new Client(this, pid);
4603 mClients.add(pid, client);
4604 }
4605
4606 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004607 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004608 lSessionId = *sessionId;
4609 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004610 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004611 if (sessionId != NULL) {
4612 *sessionId = lSessionId;
4613 }
4614 }
4615 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004616 recordTrack = thread->createRecordTrack_l(client,
4617 sampleRate,
4618 format,
4619 channelMask,
4620 frameCount,
4621 flags,
4622 lSessionId,
4623 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004624 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004625 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004626 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4627 // destructor is called by the TrackBase destructor with mLock held
4628 client.clear();
4629 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004630 goto Exit;
4631 }
4632
4633 // return to handle to client
4634 recordHandle = new RecordHandle(recordTrack);
4635 lStatus = NO_ERROR;
4636
4637Exit:
4638 if (status) {
4639 *status = lStatus;
4640 }
4641 return recordHandle;
4642}
4643
4644// ----------------------------------------------------------------------------
4645
4646AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4647 : BnAudioRecord(),
4648 mRecordTrack(recordTrack)
4649{
4650}
4651
4652AudioFlinger::RecordHandle::~RecordHandle() {
4653 stop();
4654}
4655
4656status_t AudioFlinger::RecordHandle::start() {
4657 LOGV("RecordHandle::start()");
4658 return mRecordTrack->start();
4659}
4660
4661void AudioFlinger::RecordHandle::stop() {
4662 LOGV("RecordHandle::stop()");
4663 mRecordTrack->stop();
4664}
4665
4666sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4667 return mRecordTrack->getCblk();
4668}
4669
4670status_t AudioFlinger::RecordHandle::onTransact(
4671 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4672{
4673 return BnAudioRecord::onTransact(code, data, reply, flags);
4674}
4675
4676// ----------------------------------------------------------------------------
4677
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004678AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4679 AudioStreamIn *input,
4680 uint32_t sampleRate,
4681 uint32_t channels,
4682 int id,
4683 uint32_t device) :
4684 ThreadBase(audioFlinger, id, device),
4685 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004686{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004687 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004688
4689 snprintf(mName, kNameLength, "AudioIn_%d", id);
4690
Dima Zavinfce7a472011-04-19 22:30:36 -07004691 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692 mReqSampleRate = sampleRate;
4693 readInputParameters();
4694}
4695
4696
4697AudioFlinger::RecordThread::~RecordThread()
4698{
4699 delete[] mRsmpInBuffer;
4700 if (mResampler != 0) {
4701 delete mResampler;
4702 delete[] mRsmpOutBuffer;
4703 }
4704}
4705
4706void AudioFlinger::RecordThread::onFirstRef()
4707{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004708 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004709}
4710
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004711status_t AudioFlinger::RecordThread::readyToRun()
4712{
4713 status_t status = initCheck();
4714 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4715 return status;
4716}
4717
Mathias Agopian65ab4712010-07-14 17:59:35 -07004718bool AudioFlinger::RecordThread::threadLoop()
4719{
4720 AudioBufferProvider::Buffer buffer;
4721 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004722 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004723
Eric Laurent44d98482010-09-30 16:12:31 -07004724 nsecs_t lastWarning = 0;
4725
Eric Laurentfeb0db62011-07-22 09:04:31 -07004726 acquireWakeLock();
4727
Mathias Agopian65ab4712010-07-14 17:59:35 -07004728 // start recording
4729 while (!exitPending()) {
4730
4731 processConfigEvents();
4732
4733 { // scope for mLock
4734 Mutex::Autolock _l(mLock);
4735 checkForNewParameters_l();
4736 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4737 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004738 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004739 mStandby = true;
4740 }
4741
4742 if (exitPending()) break;
4743
Eric Laurentfeb0db62011-07-22 09:04:31 -07004744 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004745 LOGV("RecordThread: loop stopping");
4746 // go to sleep
4747 mWaitWorkCV.wait(mLock);
4748 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004749 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750 continue;
4751 }
4752 if (mActiveTrack != 0) {
4753 if (mActiveTrack->mState == TrackBase::PAUSING) {
4754 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004755 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004756 mStandby = true;
4757 }
4758 mActiveTrack.clear();
4759 mStartStopCond.broadcast();
4760 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4761 if (mReqChannelCount != mActiveTrack->channelCount()) {
4762 mActiveTrack.clear();
4763 mStartStopCond.broadcast();
4764 } else if (mBytesRead != 0) {
4765 // record start succeeds only if first read from audio input
4766 // succeeds
4767 if (mBytesRead > 0) {
4768 mActiveTrack->mState = TrackBase::ACTIVE;
4769 } else {
4770 mActiveTrack.clear();
4771 }
4772 mStartStopCond.broadcast();
4773 }
4774 mStandby = false;
4775 }
4776 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004777 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004778 }
4779
4780 if (mActiveTrack != 0) {
4781 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4782 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004783 unlockEffectChains(effectChains);
4784 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004785 continue;
4786 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004787 for (size_t i = 0; i < effectChains.size(); i ++) {
4788 effectChains[i]->process_l();
4789 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004790
Mathias Agopian65ab4712010-07-14 17:59:35 -07004791 buffer.frameCount = mFrameCount;
Mike J. Chen535235c2011-08-15 13:28:26 -07004792 if (LIKELY(mActiveTrack->getNextBuffer(
4793 &buffer, AudioBufferProvider::kInvalidPTS) == NO_ERROR)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794 size_t framesOut = buffer.frameCount;
4795 if (mResampler == 0) {
4796 // no resampling
4797 while (framesOut) {
4798 size_t framesIn = mFrameCount - mRsmpInIndex;
4799 if (framesIn) {
4800 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4801 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4802 if (framesIn > framesOut)
4803 framesIn = framesOut;
4804 mRsmpInIndex += framesIn;
4805 framesOut -= framesIn;
4806 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004807 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004808 memcpy(dst, src, framesIn * mFrameSize);
4809 } else {
4810 int16_t *src16 = (int16_t *)src;
4811 int16_t *dst16 = (int16_t *)dst;
4812 if (mChannelCount == 1) {
4813 while (framesIn--) {
4814 *dst16++ = *src16;
4815 *dst16++ = *src16++;
4816 }
4817 } else {
4818 while (framesIn--) {
4819 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4820 src16 += 2;
4821 }
4822 }
4823 }
4824 }
4825 if (framesOut && mFrameCount == mRsmpInIndex) {
4826 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004827 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004828 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004829 framesOut = 0;
4830 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004831 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004832 mRsmpInIndex = 0;
4833 }
4834 if (mBytesRead < 0) {
4835 LOGE("Error reading audio input");
4836 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4837 // Force input into standby so that it tries to
4838 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004839 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004840 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004841 }
4842 mRsmpInIndex = mFrameCount;
4843 framesOut = 0;
4844 buffer.frameCount = 0;
4845 }
4846 }
4847 }
4848 } else {
4849 // resampling
4850
4851 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4852 // alter output frame count as if we were expecting stereo samples
4853 if (mChannelCount == 1 && mReqChannelCount == 1) {
4854 framesOut >>= 1;
4855 }
4856 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4857 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4858 // are 32 bit aligned which should be always true.
4859 if (mChannelCount == 2 && mReqChannelCount == 1) {
4860 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4861 // the resampler always outputs stereo samples: do post stereo to mono conversion
4862 int16_t *src = (int16_t *)mRsmpOutBuffer;
4863 int16_t *dst = buffer.i16;
4864 while (framesOut--) {
4865 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4866 src += 2;
4867 }
4868 } else {
4869 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4870 }
4871
4872 }
4873 mActiveTrack->releaseBuffer(&buffer);
4874 mActiveTrack->overflow();
4875 }
4876 // client isn't retrieving buffers fast enough
4877 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004878 if (!mActiveTrack->setOverflow()) {
4879 nsecs_t now = systemTime();
4880 if ((now - lastWarning) > kWarningThrottle) {
4881 LOGW("RecordThread: buffer overflow");
4882 lastWarning = now;
4883 }
4884 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004885 // Release the processor for a while before asking for a new buffer.
4886 // This will give the application more chance to read from the buffer and
4887 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004888 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004889 }
4890 }
Eric Laurentec437d82011-07-26 20:54:46 -07004891 // enable changes in effect chain
4892 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004893 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004894 }
4895
4896 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004897 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898 }
4899 mActiveTrack.clear();
4900
4901 mStartStopCond.broadcast();
4902
Eric Laurentfeb0db62011-07-22 09:04:31 -07004903 releaseWakeLock();
4904
Mathias Agopian65ab4712010-07-14 17:59:35 -07004905 LOGV("RecordThread %p exiting", this);
4906 return false;
4907}
4908
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004909
4910sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4911 const sp<AudioFlinger::Client>& client,
4912 uint32_t sampleRate,
4913 int format,
4914 int channelMask,
4915 int frameCount,
4916 uint32_t flags,
4917 int sessionId,
4918 status_t *status)
4919{
4920 sp<RecordTrack> track;
4921 status_t lStatus;
4922
4923 lStatus = initCheck();
4924 if (lStatus != NO_ERROR) {
4925 LOGE("Audio driver not initialized.");
4926 goto Exit;
4927 }
4928
4929 { // scope for mLock
4930 Mutex::Autolock _l(mLock);
4931
4932 track = new RecordTrack(this, client, sampleRate,
4933 format, channelMask, frameCount, flags, sessionId);
4934
4935 if (track->getCblk() == NULL) {
4936 lStatus = NO_MEMORY;
4937 goto Exit;
4938 }
4939
4940 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004941 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4942 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004943 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004944 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4945 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004946 }
4947 lStatus = NO_ERROR;
4948
4949Exit:
4950 if (status) {
4951 *status = lStatus;
4952 }
4953 return track;
4954}
4955
Mathias Agopian65ab4712010-07-14 17:59:35 -07004956status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4957{
4958 LOGV("RecordThread::start");
4959 sp <ThreadBase> strongMe = this;
4960 status_t status = NO_ERROR;
4961 {
4962 AutoMutex lock(&mLock);
4963 if (mActiveTrack != 0) {
4964 if (recordTrack != mActiveTrack.get()) {
4965 status = -EBUSY;
4966 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4967 mActiveTrack->mState = TrackBase::ACTIVE;
4968 }
4969 return status;
4970 }
4971
4972 recordTrack->mState = TrackBase::IDLE;
4973 mActiveTrack = recordTrack;
4974 mLock.unlock();
4975 status_t status = AudioSystem::startInput(mId);
4976 mLock.lock();
4977 if (status != NO_ERROR) {
4978 mActiveTrack.clear();
4979 return status;
4980 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004981 mRsmpInIndex = mFrameCount;
4982 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004983 if (mResampler != NULL) {
4984 mResampler->reset();
4985 }
4986 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 // signal thread to start
4988 LOGV("Signal record thread");
4989 mWaitWorkCV.signal();
4990 // do not wait for mStartStopCond if exiting
4991 if (mExiting) {
4992 mActiveTrack.clear();
4993 status = INVALID_OPERATION;
4994 goto startError;
4995 }
4996 mStartStopCond.wait(mLock);
4997 if (mActiveTrack == 0) {
4998 LOGV("Record failed to start");
4999 status = BAD_VALUE;
5000 goto startError;
5001 }
5002 LOGV("Record started OK");
5003 return status;
5004 }
5005startError:
5006 AudioSystem::stopInput(mId);
5007 return status;
5008}
5009
5010void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
5011 LOGV("RecordThread::stop");
5012 sp <ThreadBase> strongMe = this;
5013 {
5014 AutoMutex lock(&mLock);
5015 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
5016 mActiveTrack->mState = TrackBase::PAUSING;
5017 // do not wait for mStartStopCond if exiting
5018 if (mExiting) {
5019 return;
5020 }
5021 mStartStopCond.wait(mLock);
5022 // if we have been restarted, recordTrack == mActiveTrack.get() here
5023 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
5024 mLock.unlock();
5025 AudioSystem::stopInput(mId);
5026 mLock.lock();
5027 LOGV("Record stopped OK");
5028 }
5029 }
5030 }
5031}
5032
5033status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
5034{
5035 const size_t SIZE = 256;
5036 char buffer[SIZE];
5037 String8 result;
5038 pid_t pid = 0;
5039
5040 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
5041 result.append(buffer);
5042
5043 if (mActiveTrack != 0) {
5044 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005045 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005046 mActiveTrack->dump(buffer, SIZE);
5047 result.append(buffer);
5048
5049 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
5050 result.append(buffer);
5051 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
5052 result.append(buffer);
5053 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
5054 result.append(buffer);
5055 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
5056 result.append(buffer);
5057 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
5058 result.append(buffer);
5059
5060
5061 } else {
5062 result.append("No record client\n");
5063 }
5064 write(fd, result.string(), result.size());
5065
5066 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07005067 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005068
5069 return NO_ERROR;
5070}
5071
Mike J. Chen535235c2011-08-15 13:28:26 -07005072status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer, int64_t pts)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005073{
5074 size_t framesReq = buffer->frameCount;
5075 size_t framesReady = mFrameCount - mRsmpInIndex;
5076 int channelCount;
5077
5078 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005079 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005080 if (mBytesRead < 0) {
5081 LOGE("RecordThread::getNextBuffer() Error reading audio input");
5082 if (mActiveTrack->mState == TrackBase::ACTIVE) {
5083 // Force input into standby so that it tries to
5084 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07005085 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005086 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005087 }
5088 buffer->raw = 0;
5089 buffer->frameCount = 0;
5090 return NOT_ENOUGH_DATA;
5091 }
5092 mRsmpInIndex = 0;
5093 framesReady = mFrameCount;
5094 }
5095
5096 if (framesReq > framesReady) {
5097 framesReq = framesReady;
5098 }
5099
5100 if (mChannelCount == 1 && mReqChannelCount == 2) {
5101 channelCount = 1;
5102 } else {
5103 channelCount = 2;
5104 }
5105 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
5106 buffer->frameCount = framesReq;
5107 return NO_ERROR;
5108}
5109
5110void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
5111{
5112 mRsmpInIndex += buffer->frameCount;
5113 buffer->frameCount = 0;
5114}
5115
5116bool AudioFlinger::RecordThread::checkForNewParameters_l()
5117{
5118 bool reconfig = false;
5119
5120 while (!mNewParameters.isEmpty()) {
5121 status_t status = NO_ERROR;
5122 String8 keyValuePair = mNewParameters[0];
5123 AudioParameter param = AudioParameter(keyValuePair);
5124 int value;
5125 int reqFormat = mFormat;
5126 int reqSamplingRate = mReqSampleRate;
5127 int reqChannelCount = mReqChannelCount;
5128
5129 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5130 reqSamplingRate = value;
5131 reconfig = true;
5132 }
5133 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
5134 reqFormat = value;
5135 reconfig = true;
5136 }
5137 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005138 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005139 reconfig = true;
5140 }
5141 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5142 // do not accept frame count changes if tracks are open as the track buffer
5143 // size depends on frame count and correct behavior would not be garantied
5144 // if frame count is changed after track creation
5145 if (mActiveTrack != 0) {
5146 status = INVALID_OPERATION;
5147 } else {
5148 reconfig = true;
5149 }
5150 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005151 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
5152 // forward device change to effects that have requested to be
5153 // aware of attached audio device.
5154 for (size_t i = 0; i < mEffectChains.size(); i++) {
5155 mEffectChains[i]->setDevice_l(value);
5156 }
5157 // store input device and output device but do not forward output device to audio HAL.
5158 // Note that status is ignored by the caller for output device
5159 // (see AudioFlinger::setParameters()
5160 if (value & AUDIO_DEVICE_OUT_ALL) {
5161 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
5162 status = BAD_VALUE;
5163 } else {
5164 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07005165 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
5166 if (mTrack != NULL) {
5167 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07005168 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07005169 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
5170 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
5171 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005172 }
5173 mDevice |= (uint32_t)value;
5174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005176 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07005178 mInput->stream->common.standby(&mInput->stream->common);
5179 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005180 }
5181 if (reconfig) {
5182 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005183 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005184 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07005185 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
5186 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005187 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005188 status = NO_ERROR;
5189 }
5190 if (status == NO_ERROR) {
5191 readInputParameters();
5192 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
5193 }
5194 }
5195 }
5196
5197 mNewParameters.removeAt(0);
5198
5199 mParamStatus = status;
5200 mParamCond.signal();
5201 mWaitWorkCV.wait(mLock);
5202 }
5203 return reconfig;
5204}
5205
5206String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
5207{
Dima Zavinfce7a472011-04-19 22:30:36 -07005208 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005209 String8 out_s8 = String8();
5210
5211 Mutex::Autolock _l(mLock);
5212 if (initCheck() != NO_ERROR) {
5213 return out_s8;
5214 }
Dima Zavinfce7a472011-04-19 22:30:36 -07005215
Dima Zavin799a70e2011-04-18 16:57:27 -07005216 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07005217 out_s8 = String8(s);
5218 free(s);
5219 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005220}
5221
5222void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
5223 AudioSystem::OutputDescriptor desc;
5224 void *param2 = 0;
5225
5226 switch (event) {
5227 case AudioSystem::INPUT_OPENED:
5228 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005229 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005230 desc.samplingRate = mSampleRate;
5231 desc.format = mFormat;
5232 desc.frameCount = mFrameCount;
5233 desc.latency = 0;
5234 param2 = &desc;
5235 break;
5236
5237 case AudioSystem::INPUT_CLOSED:
5238 default:
5239 break;
5240 }
5241 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
5242}
5243
5244void AudioFlinger::RecordThread::readInputParameters()
5245{
5246 if (mRsmpInBuffer) delete mRsmpInBuffer;
5247 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
5248 if (mResampler) delete mResampler;
5249 mResampler = 0;
5250
Dima Zavin799a70e2011-04-18 16:57:27 -07005251 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07005252 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
5253 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07005254 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
5255 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
5256 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005257 mFrameCount = mInputBytes / mFrameSize;
5258 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
5259
5260 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
5261 {
5262 int channelCount;
5263 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
5264 // stereo to mono post process as the resampler always outputs stereo.
5265 if (mChannelCount == 1 && mReqChannelCount == 2) {
5266 channelCount = 1;
5267 } else {
5268 channelCount = 2;
5269 }
5270 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
5271 mResampler->setSampleRate(mSampleRate);
5272 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
5273 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
5274
5275 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
5276 if (mChannelCount == 1 && mReqChannelCount == 1) {
5277 mFrameCount >>= 1;
5278 }
5279
5280 }
5281 mRsmpInIndex = mFrameCount;
5282}
5283
5284unsigned int AudioFlinger::RecordThread::getInputFramesLost()
5285{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005286 Mutex::Autolock _l(mLock);
5287 if (initCheck() != NO_ERROR) {
5288 return 0;
5289 }
5290
Dima Zavin799a70e2011-04-18 16:57:27 -07005291 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005292}
5293
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005294uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
5295{
5296 Mutex::Autolock _l(mLock);
5297 uint32_t result = 0;
5298 if (getEffectChain_l(sessionId) != 0) {
5299 result = EFFECT_SESSION;
5300 }
5301
5302 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
5303 result |= TRACK_SESSION;
5304 }
5305
5306 return result;
5307}
5308
Eric Laurent59bd0da2011-08-01 09:52:20 -07005309AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
5310{
5311 Mutex::Autolock _l(mLock);
5312 return mTrack;
5313}
5314
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005315AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
5316{
5317 Mutex::Autolock _l(mLock);
5318 return mInput;
5319}
5320
5321AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
5322{
5323 Mutex::Autolock _l(mLock);
5324 AudioStreamIn *input = mInput;
5325 mInput = NULL;
5326 return input;
5327}
5328
5329// this method must always be called either with ThreadBase mLock held or inside the thread loop
5330audio_stream_t* AudioFlinger::RecordThread::stream()
5331{
5332 if (mInput == NULL) {
5333 return NULL;
5334 }
5335 return &mInput->stream->common;
5336}
5337
5338
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339// ----------------------------------------------------------------------------
5340
5341int AudioFlinger::openOutput(uint32_t *pDevices,
5342 uint32_t *pSamplingRate,
5343 uint32_t *pFormat,
5344 uint32_t *pChannels,
5345 uint32_t *pLatencyMs,
5346 uint32_t flags)
5347{
5348 status_t status;
5349 PlaybackThread *thread = NULL;
5350 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
5351 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5352 uint32_t format = pFormat ? *pFormat : 0;
5353 uint32_t channels = pChannels ? *pChannels : 0;
5354 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07005355 audio_stream_out_t *outStream;
5356 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005357
5358 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
5359 pDevices ? *pDevices : 0,
5360 samplingRate,
5361 format,
5362 channels,
5363 flags);
5364
5365 if (pDevices == NULL || *pDevices == 0) {
5366 return 0;
5367 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005368
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 Mutex::Autolock _l(mLock);
5370
Dima Zavin799a70e2011-04-18 16:57:27 -07005371 outHwDev = findSuitableHwDev_l(*pDevices);
5372 if (outHwDev == NULL)
5373 return 0;
5374
5375 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
5376 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005377 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005378 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005379 samplingRate,
5380 format,
5381 channels,
5382 status);
5383
5384 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07005385 if (outStream != NULL) {
5386 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005387 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07005388
Dima Zavinfce7a472011-04-19 22:30:36 -07005389 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
5390 (format != AUDIO_FORMAT_PCM_16_BIT) ||
5391 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005392 thread = new DirectOutputThread(this, output, id, *pDevices);
5393 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
5394 } else {
5395 thread = new MixerThread(this, output, id, *pDevices);
5396 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005397 }
5398 mPlaybackThreads.add(id, thread);
5399
5400 if (pSamplingRate) *pSamplingRate = samplingRate;
5401 if (pFormat) *pFormat = format;
5402 if (pChannels) *pChannels = channels;
5403 if (pLatencyMs) *pLatencyMs = thread->latency();
5404
5405 // notify client processes of the new output creation
5406 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5407 return id;
5408 }
5409
5410 return 0;
5411}
5412
5413int AudioFlinger::openDuplicateOutput(int output1, int output2)
5414{
5415 Mutex::Autolock _l(mLock);
5416 MixerThread *thread1 = checkMixerThread_l(output1);
5417 MixerThread *thread2 = checkMixerThread_l(output2);
5418
5419 if (thread1 == NULL || thread2 == NULL) {
5420 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
5421 return 0;
5422 }
5423
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005424 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005425 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
5426 thread->addOutputTrack(thread2);
5427 mPlaybackThreads.add(id, thread);
5428 // notify client processes of the new output creation
5429 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
5430 return id;
5431}
5432
5433status_t AudioFlinger::closeOutput(int output)
5434{
5435 // keep strong reference on the playback thread so that
5436 // it is not destroyed while exit() is executed
5437 sp <PlaybackThread> thread;
5438 {
5439 Mutex::Autolock _l(mLock);
5440 thread = checkPlaybackThread_l(output);
5441 if (thread == NULL) {
5442 return BAD_VALUE;
5443 }
5444
5445 LOGV("closeOutput() %d", output);
5446
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005447 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005448 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005449 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005450 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
5451 dupThread->removeOutputTrack((MixerThread *)thread.get());
5452 }
5453 }
5454 }
5455 void *param2 = 0;
5456 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
5457 mPlaybackThreads.removeItem(output);
5458 }
5459 thread->exit();
5460
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005461 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005462 AudioStreamOut *out = thread->clearOutput();
5463 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005464 out->hwDev->close_output_stream(out->hwDev, out->stream);
5465 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005466 }
5467 return NO_ERROR;
5468}
5469
5470status_t AudioFlinger::suspendOutput(int output)
5471{
5472 Mutex::Autolock _l(mLock);
5473 PlaybackThread *thread = checkPlaybackThread_l(output);
5474
5475 if (thread == NULL) {
5476 return BAD_VALUE;
5477 }
5478
5479 LOGV("suspendOutput() %d", output);
5480 thread->suspend();
5481
5482 return NO_ERROR;
5483}
5484
5485status_t AudioFlinger::restoreOutput(int output)
5486{
5487 Mutex::Autolock _l(mLock);
5488 PlaybackThread *thread = checkPlaybackThread_l(output);
5489
5490 if (thread == NULL) {
5491 return BAD_VALUE;
5492 }
5493
5494 LOGV("restoreOutput() %d", output);
5495
5496 thread->restore();
5497
5498 return NO_ERROR;
5499}
5500
5501int AudioFlinger::openInput(uint32_t *pDevices,
5502 uint32_t *pSamplingRate,
5503 uint32_t *pFormat,
5504 uint32_t *pChannels,
5505 uint32_t acoustics)
5506{
5507 status_t status;
5508 RecordThread *thread = NULL;
5509 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5510 uint32_t format = pFormat ? *pFormat : 0;
5511 uint32_t channels = pChannels ? *pChannels : 0;
5512 uint32_t reqSamplingRate = samplingRate;
5513 uint32_t reqFormat = format;
5514 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005515 audio_stream_in_t *inStream;
5516 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517
5518 if (pDevices == NULL || *pDevices == 0) {
5519 return 0;
5520 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005521
Mathias Agopian65ab4712010-07-14 17:59:35 -07005522 Mutex::Autolock _l(mLock);
5523
Dima Zavin799a70e2011-04-18 16:57:27 -07005524 inHwDev = findSuitableHwDev_l(*pDevices);
5525 if (inHwDev == NULL)
5526 return 0;
5527
5528 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5529 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005530 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005531 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005532 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005533 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005534 samplingRate,
5535 format,
5536 channels,
5537 acoustics,
5538 status);
5539
5540 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5541 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5542 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005543 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005544 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005546 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005547 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005548 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5549 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005550 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005551 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552 }
5553
Dima Zavin799a70e2011-04-18 16:57:27 -07005554 if (inStream != NULL) {
5555 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5556
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005557 int id = nextUniqueId();
5558 // Start record thread
5559 // RecorThread require both input and output device indication to forward to audio
5560 // pre processing modules
5561 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5562 thread = new RecordThread(this,
5563 input,
5564 reqSamplingRate,
5565 reqChannels,
5566 id,
5567 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005568 mRecordThreads.add(id, thread);
5569 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
5570 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5571 if (pFormat) *pFormat = format;
5572 if (pChannels) *pChannels = reqChannels;
5573
Dima Zavin799a70e2011-04-18 16:57:27 -07005574 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005575
5576 // notify client processes of the new input creation
5577 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5578 return id;
5579 }
5580
5581 return 0;
5582}
5583
5584status_t AudioFlinger::closeInput(int input)
5585{
5586 // keep strong reference on the record thread so that
5587 // it is not destroyed while exit() is executed
5588 sp <RecordThread> thread;
5589 {
5590 Mutex::Autolock _l(mLock);
5591 thread = checkRecordThread_l(input);
5592 if (thread == NULL) {
5593 return BAD_VALUE;
5594 }
5595
5596 LOGV("closeInput() %d", input);
5597 void *param2 = 0;
5598 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5599 mRecordThreads.removeItem(input);
5600 }
5601 thread->exit();
5602
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005603 AudioStreamIn *in = thread->clearInput();
5604 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005605 in->hwDev->close_input_stream(in->hwDev, in->stream);
5606 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005607
5608 return NO_ERROR;
5609}
5610
5611status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5612{
5613 Mutex::Autolock _l(mLock);
5614 MixerThread *dstThread = checkMixerThread_l(output);
5615 if (dstThread == NULL) {
5616 LOGW("setStreamOutput() bad output id %d", output);
5617 return BAD_VALUE;
5618 }
5619
5620 LOGV("setStreamOutput() stream %d to output %d", stream, output);
5621 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5622
5623 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5624 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5625 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005626 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005627 MixerThread *srcThread = (MixerThread *)thread;
5628 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629 }
Eric Laurentde070132010-07-13 04:45:46 -07005630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005631
5632 return NO_ERROR;
5633}
5634
5635
5636int AudioFlinger::newAudioSessionId()
5637{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005638 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005639}
5640
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005641void AudioFlinger::acquireAudioSessionId(int audioSession)
5642{
5643 Mutex::Autolock _l(mLock);
5644 int caller = IPCThreadState::self()->getCallingPid();
5645 LOGV("acquiring %d from %d", audioSession, caller);
5646 int num = mAudioSessionRefs.size();
5647 for (int i = 0; i< num; i++) {
5648 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5649 if (ref->sessionid == audioSession && ref->pid == caller) {
5650 ref->cnt++;
5651 LOGV(" incremented refcount to %d", ref->cnt);
5652 return;
5653 }
5654 }
5655 AudioSessionRef *ref = new AudioSessionRef();
5656 ref->sessionid = audioSession;
5657 ref->pid = caller;
5658 ref->cnt = 1;
5659 mAudioSessionRefs.push(ref);
5660 LOGV(" added new entry for %d", ref->sessionid);
5661}
5662
5663void AudioFlinger::releaseAudioSessionId(int audioSession)
5664{
5665 Mutex::Autolock _l(mLock);
5666 int caller = IPCThreadState::self()->getCallingPid();
5667 LOGV("releasing %d from %d", audioSession, caller);
5668 int num = mAudioSessionRefs.size();
5669 for (int i = 0; i< num; i++) {
5670 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5671 if (ref->sessionid == audioSession && ref->pid == caller) {
5672 ref->cnt--;
5673 LOGV(" decremented refcount to %d", ref->cnt);
5674 if (ref->cnt == 0) {
5675 mAudioSessionRefs.removeAt(i);
5676 delete ref;
5677 purgeStaleEffects_l();
5678 }
5679 return;
5680 }
5681 }
5682 LOGW("session id %d not found for pid %d", audioSession, caller);
5683}
5684
5685void AudioFlinger::purgeStaleEffects_l() {
5686
5687 LOGV("purging stale effects");
5688
5689 Vector< sp<EffectChain> > chains;
5690
5691 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5692 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5693 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5694 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005695 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5696 chains.push(ec);
5697 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005698 }
5699 }
5700 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5701 sp<RecordThread> t = mRecordThreads.valueAt(i);
5702 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5703 sp<EffectChain> ec = t->mEffectChains[j];
5704 chains.push(ec);
5705 }
5706 }
5707
5708 for (size_t i = 0; i < chains.size(); i++) {
5709 sp<EffectChain> ec = chains[i];
5710 int sessionid = ec->sessionId();
5711 sp<ThreadBase> t = ec->mThread.promote();
5712 if (t == 0) {
5713 continue;
5714 }
5715 size_t numsessionrefs = mAudioSessionRefs.size();
5716 bool found = false;
5717 for (size_t k = 0; k < numsessionrefs; k++) {
5718 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5719 if (ref->sessionid == sessionid) {
5720 LOGV(" session %d still exists for %d with %d refs",
5721 sessionid, ref->pid, ref->cnt);
5722 found = true;
5723 break;
5724 }
5725 }
5726 if (!found) {
5727 // remove all effects from the chain
5728 while (ec->mEffects.size()) {
5729 sp<EffectModule> effect = ec->mEffects[0];
5730 effect->unPin();
5731 Mutex::Autolock _l (t->mLock);
5732 t->removeEffect_l(effect);
5733 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5734 sp<EffectHandle> handle = effect->mHandles[j].promote();
5735 if (handle != 0) {
5736 handle->mEffect.clear();
5737 }
5738 }
5739 AudioSystem::unregisterEffect(effect->id());
5740 }
5741 }
5742 }
5743 return;
5744}
5745
Mathias Agopian65ab4712010-07-14 17:59:35 -07005746// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5747AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5748{
5749 PlaybackThread *thread = NULL;
5750 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5751 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5752 }
5753 return thread;
5754}
5755
5756// checkMixerThread_l() must be called with AudioFlinger::mLock held
5757AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5758{
5759 PlaybackThread *thread = checkPlaybackThread_l(output);
5760 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005761 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005762 thread = NULL;
5763 }
5764 }
5765 return (MixerThread *)thread;
5766}
5767
5768// checkRecordThread_l() must be called with AudioFlinger::mLock held
5769AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5770{
5771 RecordThread *thread = NULL;
5772 if (mRecordThreads.indexOfKey(input) >= 0) {
5773 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5774 }
5775 return thread;
5776}
5777
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005778uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005779{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005780 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781}
5782
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005783AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5784{
5785 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5786 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005787 AudioStreamOut *output = thread->getOutput();
5788 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005789 return thread;
5790 }
5791 }
5792 return NULL;
5793}
5794
5795uint32_t AudioFlinger::primaryOutputDevice_l()
5796{
5797 PlaybackThread *thread = primaryPlaybackThread_l();
5798
5799 if (thread == NULL) {
5800 return 0;
5801 }
5802
5803 return thread->device();
5804}
5805
5806
Mathias Agopian65ab4712010-07-14 17:59:35 -07005807// ----------------------------------------------------------------------------
5808// Effect management
5809// ----------------------------------------------------------------------------
5810
5811
Mathias Agopian65ab4712010-07-14 17:59:35 -07005812status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5813{
5814 Mutex::Autolock _l(mLock);
5815 return EffectQueryNumberEffects(numEffects);
5816}
5817
5818status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5819{
5820 Mutex::Autolock _l(mLock);
5821 return EffectQueryEffect(index, descriptor);
5822}
5823
5824status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5825{
5826 Mutex::Autolock _l(mLock);
5827 return EffectGetDescriptor(pUuid, descriptor);
5828}
5829
5830
Mathias Agopian65ab4712010-07-14 17:59:35 -07005831sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5832 effect_descriptor_t *pDesc,
5833 const sp<IEffectClient>& effectClient,
5834 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005835 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005836 int sessionId,
5837 status_t *status,
5838 int *id,
5839 int *enabled)
5840{
5841 status_t lStatus = NO_ERROR;
5842 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005843 effect_descriptor_t desc;
5844 sp<Client> client;
5845 wp<Client> wclient;
5846
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005847 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5848 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005849
5850 if (pDesc == NULL) {
5851 lStatus = BAD_VALUE;
5852 goto Exit;
5853 }
5854
Eric Laurent84e9a102010-09-23 16:10:16 -07005855 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005856 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005857 lStatus = PERMISSION_DENIED;
5858 goto Exit;
5859 }
5860
Dima Zavinfce7a472011-04-19 22:30:36 -07005861 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005862 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005863 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005864 lStatus = PERMISSION_DENIED;
5865 goto Exit;
5866 }
5867
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005868 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005869 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005870 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005871 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005872 lStatus = BAD_VALUE;
5873 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005874 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005875 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005876 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005877 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005878 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005879 }
5880 }
5881
Mathias Agopian65ab4712010-07-14 17:59:35 -07005882 {
5883 Mutex::Autolock _l(mLock);
5884
Mathias Agopian65ab4712010-07-14 17:59:35 -07005885
5886 if (!EffectIsNullUuid(&pDesc->uuid)) {
5887 // if uuid is specified, request effect descriptor
5888 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5889 if (lStatus < 0) {
5890 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5891 goto Exit;
5892 }
5893 } else {
5894 // if uuid is not specified, look for an available implementation
5895 // of the required type in effect factory
5896 if (EffectIsNullUuid(&pDesc->type)) {
5897 LOGW("createEffect() no effect type");
5898 lStatus = BAD_VALUE;
5899 goto Exit;
5900 }
5901 uint32_t numEffects = 0;
5902 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005903 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 bool found = false;
5905
5906 lStatus = EffectQueryNumberEffects(&numEffects);
5907 if (lStatus < 0) {
5908 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5909 goto Exit;
5910 }
5911 for (uint32_t i = 0; i < numEffects; i++) {
5912 lStatus = EffectQueryEffect(i, &desc);
5913 if (lStatus < 0) {
5914 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5915 continue;
5916 }
5917 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5918 // If matching type found save effect descriptor. If the session is
5919 // 0 and the effect is not auxiliary, continue enumeration in case
5920 // an auxiliary version of this effect type is available
5921 found = true;
5922 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005923 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005924 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5925 break;
5926 }
5927 }
5928 }
5929 if (!found) {
5930 lStatus = BAD_VALUE;
5931 LOGW("createEffect() effect not found");
5932 goto Exit;
5933 }
5934 // For same effect type, chose auxiliary version over insert version if
5935 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005936 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005937 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5938 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5939 }
5940 }
5941
5942 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005943 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005944 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5945 lStatus = INVALID_OPERATION;
5946 goto Exit;
5947 }
5948
Eric Laurent59255e42011-07-27 19:49:51 -07005949 // check recording permission for visualizer
5950 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5951 !recordingAllowed()) {
5952 lStatus = PERMISSION_DENIED;
5953 goto Exit;
5954 }
5955
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956 // return effect descriptor
5957 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5958
5959 // If output is not specified try to find a matching audio session ID in one of the
5960 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005961 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5962 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005963 // Note: io is never 0 when creating an effect on an input
5964 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005965 // look for the thread where the specified audio session is present
5966 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5967 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005968 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005969 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005971 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005972 if (io == 0) {
5973 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5974 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5975 io = mRecordThreads.keyAt(i);
5976 break;
5977 }
5978 }
5979 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005980 // If no output thread contains the requested session ID, default to
5981 // first output. The effect chain will be moved to the correct output
5982 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005983 if (io == 0 && mPlaybackThreads.size()) {
5984 io = mPlaybackThreads.keyAt(0);
5985 }
5986 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5987 }
5988 ThreadBase *thread = checkRecordThread_l(io);
5989 if (thread == NULL) {
5990 thread = checkPlaybackThread_l(io);
5991 if (thread == NULL) {
5992 LOGE("createEffect() unknown output thread");
5993 lStatus = BAD_VALUE;
5994 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005995 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005996 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005997
Mathias Agopian65ab4712010-07-14 17:59:35 -07005998 wclient = mClients.valueFor(pid);
5999
6000 if (wclient != NULL) {
6001 client = wclient.promote();
6002 } else {
6003 client = new Client(this, pid);
6004 mClients.add(pid, client);
6005 }
6006
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006007 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07006008 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
6009 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006010 if (handle != 0 && id != NULL) {
6011 *id = handle->id();
6012 }
6013 }
6014
6015Exit:
6016 if(status) {
6017 *status = lStatus;
6018 }
6019 return handle;
6020}
6021
Eric Laurent59255e42011-07-27 19:49:51 -07006022status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07006023{
6024 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07006025 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07006026 Mutex::Autolock _l(mLock);
6027 if (srcOutput == dstOutput) {
6028 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
6029 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006030 }
Eric Laurentde070132010-07-13 04:45:46 -07006031 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
6032 if (srcThread == NULL) {
6033 LOGW("moveEffects() bad srcOutput %d", srcOutput);
6034 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035 }
Eric Laurentde070132010-07-13 04:45:46 -07006036 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
6037 if (dstThread == NULL) {
6038 LOGW("moveEffects() bad dstOutput %d", dstOutput);
6039 return BAD_VALUE;
6040 }
6041
6042 Mutex::Autolock _dl(dstThread->mLock);
6043 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07006044 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07006045
Mathias Agopian65ab4712010-07-14 17:59:35 -07006046 return NO_ERROR;
6047}
6048
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006049// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07006050status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07006051 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07006052 AudioFlinger::PlaybackThread *dstThread,
6053 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07006054{
6055 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006056 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07006057
Eric Laurent59255e42011-07-27 19:49:51 -07006058 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07006059 if (chain == 0) {
6060 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07006061 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07006062 return INVALID_OPERATION;
6063 }
6064
Eric Laurent39e94f82010-07-28 01:32:47 -07006065 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07006066 // so that a new chain is created with correct parameters when first effect is added. This is
6067 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
6068 // removed.
6069 srcThread->removeEffectChain_l(chain);
6070
6071 // transfer all effects one by one so that new effect chain is created on new thread with
6072 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07006073 int dstOutput = dstThread->id();
6074 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006075 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07006076 sp<EffectModule> effect = chain->getEffectFromId_l(0);
6077 while (effect != 0) {
6078 srcThread->removeEffect_l(effect);
6079 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07006080 // if the move request is not received from audio policy manager, the effect must be
6081 // re-registered with the new strategy and output
6082 if (dstChain == 0) {
6083 dstChain = effect->chain().promote();
6084 if (dstChain == 0) {
6085 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
6086 srcThread->addEffect_l(effect);
6087 return NO_INIT;
6088 }
6089 strategy = dstChain->strategy();
6090 }
6091 if (reRegister) {
6092 AudioSystem::unregisterEffect(effect->id());
6093 AudioSystem::registerEffect(&effect->desc(),
6094 dstOutput,
6095 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07006096 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07006097 effect->id());
6098 }
Eric Laurentde070132010-07-13 04:45:46 -07006099 effect = chain->getEffectFromId_l(0);
6100 }
6101
6102 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006103}
6104
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006105
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006107sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07006108 const sp<AudioFlinger::Client>& client,
6109 const sp<IEffectClient>& effectClient,
6110 int32_t priority,
6111 int sessionId,
6112 effect_descriptor_t *desc,
6113 int *enabled,
6114 status_t *status
6115 )
6116{
6117 sp<EffectModule> effect;
6118 sp<EffectHandle> handle;
6119 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006120 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07006121 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122 bool effectCreated = false;
6123 bool effectRegistered = false;
6124
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006125 lStatus = initCheck();
6126 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006127 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006128 goto Exit;
6129 }
6130
6131 // Do not allow effects with session ID 0 on direct output or duplicating threads
6132 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07006133 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07006134 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
6135 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006136 lStatus = BAD_VALUE;
6137 goto Exit;
6138 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006139 // Only Pre processor effects are allowed on input threads and only on input threads
6140 if ((mType == RECORD &&
6141 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
6142 (mType != RECORD &&
6143 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
6144 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
6145 desc->name, desc->flags, mType);
6146 lStatus = BAD_VALUE;
6147 goto Exit;
6148 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006149
6150 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
6151
6152 { // scope for mLock
6153 Mutex::Autolock _l(mLock);
6154
6155 // check for existing effect chain with the requested audio session
6156 chain = getEffectChain_l(sessionId);
6157 if (chain == 0) {
6158 // create a new chain for this session
6159 LOGV("createEffect_l() new effect chain for session %d", sessionId);
6160 chain = new EffectChain(this, sessionId);
6161 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07006162 chain->setStrategy(getStrategyForSession_l(sessionId));
6163 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006164 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07006165 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 }
6167
6168 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
6169
6170 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006171 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006172 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07006173 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006174 if (lStatus != NO_ERROR) {
6175 goto Exit;
6176 }
6177 effectRegistered = true;
6178 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07006179 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006180 lStatus = effect->status();
6181 if (lStatus != NO_ERROR) {
6182 goto Exit;
6183 }
Eric Laurentcab11242010-07-15 12:50:15 -07006184 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185 if (lStatus != NO_ERROR) {
6186 goto Exit;
6187 }
6188 effectCreated = true;
6189
6190 effect->setDevice(mDevice);
6191 effect->setMode(mAudioFlinger->getMode());
6192 }
6193 // create effect handle and connect it to effect module
6194 handle = new EffectHandle(effect, client, effectClient, priority);
6195 lStatus = effect->addHandle(handle);
6196 if (enabled) {
6197 *enabled = (int)effect->isEnabled();
6198 }
6199 }
6200
6201Exit:
6202 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07006203 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006204 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07006205 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006206 }
6207 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07006208 AudioSystem::unregisterEffect(effect->id());
6209 }
6210 if (chainCreated) {
6211 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006212 }
6213 handle.clear();
6214 }
6215
6216 if(status) {
6217 *status = lStatus;
6218 }
6219 return handle;
6220}
6221
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006222sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
6223{
6224 sp<EffectModule> effect;
6225
6226 sp<EffectChain> chain = getEffectChain_l(sessionId);
6227 if (chain != 0) {
6228 effect = chain->getEffectFromId_l(effectId);
6229 }
6230 return effect;
6231}
6232
Eric Laurentde070132010-07-13 04:45:46 -07006233// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
6234// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006235status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07006236{
6237 // check for existing effect chain with the requested audio session
6238 int sessionId = effect->sessionId();
6239 sp<EffectChain> chain = getEffectChain_l(sessionId);
6240 bool chainCreated = false;
6241
6242 if (chain == 0) {
6243 // create a new chain for this session
6244 LOGV("addEffect_l() new effect chain for session %d", sessionId);
6245 chain = new EffectChain(this, sessionId);
6246 addEffectChain_l(chain);
6247 chain->setStrategy(getStrategyForSession_l(sessionId));
6248 chainCreated = true;
6249 }
6250 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
6251
6252 if (chain->getEffectFromId_l(effect->id()) != 0) {
6253 LOGW("addEffect_l() %p effect %s already present in chain %p",
6254 this, effect->desc().name, chain.get());
6255 return BAD_VALUE;
6256 }
6257
6258 status_t status = chain->addEffect_l(effect);
6259 if (status != NO_ERROR) {
6260 if (chainCreated) {
6261 removeEffectChain_l(chain);
6262 }
6263 return status;
6264 }
6265
6266 effect->setDevice(mDevice);
6267 effect->setMode(mAudioFlinger->getMode());
6268 return NO_ERROR;
6269}
6270
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006271void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07006272
6273 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006274 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07006275 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6276 detachAuxEffect_l(effect->id());
6277 }
6278
6279 sp<EffectChain> chain = effect->chain().promote();
6280 if (chain != 0) {
6281 // remove effect chain if removing last effect
6282 if (chain->removeEffect_l(effect) == 0) {
6283 removeEffectChain_l(chain);
6284 }
6285 } else {
6286 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
6287 }
6288}
6289
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006290void AudioFlinger::ThreadBase::lockEffectChains_l(
6291 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6292{
6293 effectChains = mEffectChains;
6294 for (size_t i = 0; i < mEffectChains.size(); i++) {
6295 mEffectChains[i]->lock();
6296 }
6297}
6298
6299void AudioFlinger::ThreadBase::unlockEffectChains(
6300 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
6301{
6302 for (size_t i = 0; i < effectChains.size(); i++) {
6303 effectChains[i]->unlock();
6304 }
6305}
6306
6307sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
6308{
6309 Mutex::Autolock _l(mLock);
6310 return getEffectChain_l(sessionId);
6311}
6312
6313sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
6314{
6315 sp<EffectChain> chain;
6316
6317 size_t size = mEffectChains.size();
6318 for (size_t i = 0; i < size; i++) {
6319 if (mEffectChains[i]->sessionId() == sessionId) {
6320 chain = mEffectChains[i];
6321 break;
6322 }
6323 }
6324 return chain;
6325}
6326
6327void AudioFlinger::ThreadBase::setMode(uint32_t mode)
6328{
6329 Mutex::Autolock _l(mLock);
6330 size_t size = mEffectChains.size();
6331 for (size_t i = 0; i < size; i++) {
6332 mEffectChains[i]->setMode_l(mode);
6333 }
6334}
6335
6336void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006337 const wp<EffectHandle>& handle,
6338 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07006339
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006341 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006342 // delete the effect module if removing last handle on it
6343 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006344 if (!effect->isPinned() || unpiniflast) {
6345 removeEffect_l(effect);
6346 AudioSystem::unregisterEffect(effect->id());
6347 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006348 }
6349}
6350
6351status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
6352{
6353 int session = chain->sessionId();
6354 int16_t *buffer = mMixBuffer;
6355 bool ownsBuffer = false;
6356
6357 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
6358 if (session > 0) {
6359 // Only one effect chain can be present in direct output thread and it uses
6360 // the mix buffer as input
6361 if (mType != DIRECT) {
6362 size_t numSamples = mFrameCount * mChannelCount;
6363 buffer = new int16_t[numSamples];
6364 memset(buffer, 0, numSamples * sizeof(int16_t));
6365 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
6366 ownsBuffer = true;
6367 }
6368
6369 // Attach all tracks with same session ID to this chain.
6370 for (size_t i = 0; i < mTracks.size(); ++i) {
6371 sp<Track> track = mTracks[i];
6372 if (session == track->sessionId()) {
6373 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
6374 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006375 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006376 }
6377 }
6378
6379 // indicate all active tracks in the chain
6380 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6381 sp<Track> track = mActiveTracks[i].promote();
6382 if (track == 0) continue;
6383 if (session == track->sessionId()) {
6384 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07006385 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006386 }
6387 }
6388 }
6389
6390 chain->setInBuffer(buffer, ownsBuffer);
6391 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07006392 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07006393 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07006394 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
6395 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006396 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07006397 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
6398 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07006399 // Effect chain for other sessions are inserted at beginning of effect
6400 // chains list to be processed before output mix effects. Relative order between other
6401 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07006402 size_t size = mEffectChains.size();
6403 size_t i = 0;
6404 for (i = 0; i < size; i++) {
6405 if (mEffectChains[i]->sessionId() < session) break;
6406 }
6407 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07006408 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409
6410 return NO_ERROR;
6411}
6412
6413size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
6414{
6415 int session = chain->sessionId();
6416
6417 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
6418
6419 for (size_t i = 0; i < mEffectChains.size(); i++) {
6420 if (chain == mEffectChains[i]) {
6421 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07006422 // detach all active tracks from the chain
6423 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
6424 sp<Track> track = mActiveTracks[i].promote();
6425 if (track == 0) continue;
6426 if (session == track->sessionId()) {
6427 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
6428 chain.get(), session);
6429 chain->decActiveTrackCnt();
6430 }
6431 }
6432
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433 // detach all tracks with same session ID from this chain
6434 for (size_t i = 0; i < mTracks.size(); ++i) {
6435 sp<Track> track = mTracks[i];
6436 if (session == track->sessionId()) {
6437 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07006438 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006439 }
6440 }
Eric Laurentde070132010-07-13 04:45:46 -07006441 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006442 }
6443 }
6444 return mEffectChains.size();
6445}
6446
Eric Laurentde070132010-07-13 04:45:46 -07006447status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6448 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006449{
6450 Mutex::Autolock _l(mLock);
6451 return attachAuxEffect_l(track, EffectId);
6452}
6453
Eric Laurentde070132010-07-13 04:45:46 -07006454status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6455 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006456{
6457 status_t status = NO_ERROR;
6458
6459 if (EffectId == 0) {
6460 track->setAuxBuffer(0, NULL);
6461 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006462 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6463 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006464 if (effect != 0) {
6465 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6466 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6467 } else {
6468 status = INVALID_OPERATION;
6469 }
6470 } else {
6471 status = BAD_VALUE;
6472 }
6473 }
6474 return status;
6475}
6476
6477void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6478{
6479 for (size_t i = 0; i < mTracks.size(); ++i) {
6480 sp<Track> track = mTracks[i];
6481 if (track->auxEffectId() == effectId) {
6482 attachAuxEffect_l(track, 0);
6483 }
6484 }
6485}
6486
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006487status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6488{
6489 // only one chain per input thread
6490 if (mEffectChains.size() != 0) {
6491 return INVALID_OPERATION;
6492 }
6493 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
6494
6495 chain->setInBuffer(NULL);
6496 chain->setOutBuffer(NULL);
6497
Eric Laurent59255e42011-07-27 19:49:51 -07006498 checkSuspendOnAddEffectChain_l(chain);
6499
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006500 mEffectChains.add(chain);
6501
6502 return NO_ERROR;
6503}
6504
6505size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6506{
6507 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
6508 LOGW_IF(mEffectChains.size() != 1,
6509 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6510 chain.get(), mEffectChains.size(), this);
6511 if (mEffectChains.size() == 1) {
6512 mEffectChains.removeAt(0);
6513 }
6514 return 0;
6515}
6516
Mathias Agopian65ab4712010-07-14 17:59:35 -07006517// ----------------------------------------------------------------------------
6518// EffectModule implementation
6519// ----------------------------------------------------------------------------
6520
6521#undef LOG_TAG
6522#define LOG_TAG "AudioFlinger::EffectModule"
6523
6524AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6525 const wp<AudioFlinger::EffectChain>& chain,
6526 effect_descriptor_t *desc,
6527 int id,
6528 int sessionId)
6529 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006530 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006531{
6532 LOGV("Constructor %p", this);
6533 int lStatus;
6534 sp<ThreadBase> thread = mThread.promote();
6535 if (thread == 0) {
6536 return;
6537 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006538
6539 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6540
6541 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006542 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006543
6544 if (mStatus != NO_ERROR) {
6545 return;
6546 }
6547 lStatus = init();
6548 if (lStatus < 0) {
6549 mStatus = lStatus;
6550 goto Error;
6551 }
6552
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006553 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6554 mPinned = true;
6555 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006556 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
6557 return;
6558Error:
6559 EffectRelease(mEffectInterface);
6560 mEffectInterface = NULL;
6561 LOGV("Constructor Error %d", mStatus);
6562}
6563
6564AudioFlinger::EffectModule::~EffectModule()
6565{
6566 LOGV("Destructor %p", this);
6567 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006568 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6569 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6570 sp<ThreadBase> thread = mThread.promote();
6571 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006572 audio_stream_t *stream = thread->stream();
6573 if (stream != NULL) {
6574 stream->remove_audio_effect(stream, mEffectInterface);
6575 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006576 }
6577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006578 // release effect engine
6579 EffectRelease(mEffectInterface);
6580 }
6581}
6582
6583status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6584{
6585 status_t status;
6586
6587 Mutex::Autolock _l(mLock);
6588 // First handle in mHandles has highest priority and controls the effect module
6589 int priority = handle->priority();
6590 size_t size = mHandles.size();
6591 sp<EffectHandle> h;
6592 size_t i;
6593 for (i = 0; i < size; i++) {
6594 h = mHandles[i].promote();
6595 if (h == 0) continue;
6596 if (h->priority() <= priority) break;
6597 }
6598 // if inserted in first place, move effect control from previous owner to this handle
6599 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006600 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006601 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006602 enabled = h->enabled();
6603 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006604 }
Eric Laurent59255e42011-07-27 19:49:51 -07006605 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006606 status = NO_ERROR;
6607 } else {
6608 status = ALREADY_EXISTS;
6609 }
Eric Laurent59255e42011-07-27 19:49:51 -07006610 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006611 mHandles.insertAt(handle, i);
6612 return status;
6613}
6614
6615size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6616{
6617 Mutex::Autolock _l(mLock);
6618 size_t size = mHandles.size();
6619 size_t i;
6620 for (i = 0; i < size; i++) {
6621 if (mHandles[i] == handle) break;
6622 }
6623 if (i == size) {
6624 return size;
6625 }
Eric Laurent59255e42011-07-27 19:49:51 -07006626 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
6627
6628 bool enabled = false;
6629 EffectHandle *hdl = handle.unsafe_get();
6630 if (hdl) {
6631 LOGV("removeHandle() unsafe_get OK");
6632 enabled = hdl->enabled();
6633 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006634 mHandles.removeAt(i);
6635 size = mHandles.size();
6636 // if removed from first place, move effect control from this handle to next in line
6637 if (i == 0 && size != 0) {
6638 sp<EffectHandle> h = mHandles[0].promote();
6639 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006640 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006641 }
6642 }
6643
Eric Laurentec437d82011-07-26 20:54:46 -07006644 // Prevent calls to process() and other functions on effect interface from now on.
6645 // The effect engine will be released by the destructor when the last strong reference on
6646 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006647 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006648 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006649 }
6650
Mathias Agopian65ab4712010-07-14 17:59:35 -07006651 return size;
6652}
6653
Eric Laurent59255e42011-07-27 19:49:51 -07006654sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6655{
6656 Mutex::Autolock _l(mLock);
6657 sp<EffectHandle> handle;
6658 if (mHandles.size() != 0) {
6659 handle = mHandles[0].promote();
6660 }
6661 return handle;
6662}
6663
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006664void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006665{
Eric Laurent59255e42011-07-27 19:49:51 -07006666 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006667 // keep a strong reference on this EffectModule to avoid calling the
6668 // destructor before we exit
6669 sp<EffectModule> keep(this);
6670 {
6671 sp<ThreadBase> thread = mThread.promote();
6672 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006673 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006674 }
6675 }
6676}
6677
6678void AudioFlinger::EffectModule::updateState() {
6679 Mutex::Autolock _l(mLock);
6680
6681 switch (mState) {
6682 case RESTART:
6683 reset_l();
6684 // FALL THROUGH
6685
6686 case STARTING:
6687 // clear auxiliary effect input buffer for next accumulation
6688 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6689 memset(mConfig.inputCfg.buffer.raw,
6690 0,
6691 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6692 }
6693 start_l();
6694 mState = ACTIVE;
6695 break;
6696 case STOPPING:
6697 stop_l();
6698 mDisableWaitCnt = mMaxDisableWaitCnt;
6699 mState = STOPPED;
6700 break;
6701 case STOPPED:
6702 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6703 // turn off sequence.
6704 if (--mDisableWaitCnt == 0) {
6705 reset_l();
6706 mState = IDLE;
6707 }
6708 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006709 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006710 break;
6711 }
6712}
6713
6714void AudioFlinger::EffectModule::process()
6715{
6716 Mutex::Autolock _l(mLock);
6717
Eric Laurentec437d82011-07-26 20:54:46 -07006718 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006719 mConfig.inputCfg.buffer.raw == NULL ||
6720 mConfig.outputCfg.buffer.raw == NULL) {
6721 return;
6722 }
6723
Eric Laurent8f45bd72010-08-31 13:50:07 -07006724 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006725 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6726 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6727 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
6728 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006729 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730 }
6731
6732 // do the actual processing in the effect engine
6733 int ret = (*mEffectInterface)->process(mEffectInterface,
6734 &mConfig.inputCfg.buffer,
6735 &mConfig.outputCfg.buffer);
6736
6737 // force transition to IDLE state when engine is ready
6738 if (mState == STOPPED && ret == -ENODATA) {
6739 mDisableWaitCnt = 1;
6740 }
6741
6742 // clear auxiliary effect input buffer for next accumulation
6743 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006744 memset(mConfig.inputCfg.buffer.raw, 0,
6745 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006746 }
6747 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006748 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6749 // If an insert effect is idle and input buffer is different from output buffer,
6750 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006751 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006752 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006753 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6754 int16_t *in = mConfig.inputCfg.buffer.s16;
6755 int16_t *out = mConfig.outputCfg.buffer.s16;
6756 for (size_t i = 0; i < frameCnt; i++) {
6757 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006758 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006759 }
6760 }
6761}
6762
6763void AudioFlinger::EffectModule::reset_l()
6764{
6765 if (mEffectInterface == NULL) {
6766 return;
6767 }
6768 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6769}
6770
6771status_t AudioFlinger::EffectModule::configure()
6772{
6773 uint32_t channels;
6774 if (mEffectInterface == NULL) {
6775 return NO_INIT;
6776 }
6777
6778 sp<ThreadBase> thread = mThread.promote();
6779 if (thread == 0) {
6780 return DEAD_OBJECT;
6781 }
6782
6783 // TODO: handle configuration of effects replacing track process
6784 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006785 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006786 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006787 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006788 }
6789
6790 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006791 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006792 } else {
6793 mConfig.inputCfg.channels = channels;
6794 }
6795 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006796 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6797 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006798 mConfig.inputCfg.samplingRate = thread->sampleRate();
6799 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6800 mConfig.inputCfg.bufferProvider.cookie = NULL;
6801 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6802 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6803 mConfig.outputCfg.bufferProvider.cookie = NULL;
6804 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6805 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6806 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6807 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006808 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006809 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006810 // - in other sessions:
6811 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6812 // other effect: overwrites output buffer: input buffer == output buffer
6813 // Auxiliary effect:
6814 // accumulates in output buffer: input buffer != output buffer
6815 // Therefore: accumulate <=> input buffer != output buffer
6816 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6817 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6818 } else {
6819 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6820 }
6821 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6822 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6823 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6824 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6825
Eric Laurentde070132010-07-13 04:45:46 -07006826 LOGV("configure() %p thread %p buffer %p framecount %d",
6827 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6828
Mathias Agopian65ab4712010-07-14 17:59:35 -07006829 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006830 uint32_t size = sizeof(int);
6831 status_t status = (*mEffectInterface)->command(mEffectInterface,
6832 EFFECT_CMD_CONFIGURE,
6833 sizeof(effect_config_t),
6834 &mConfig,
6835 &size,
6836 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 if (status == 0) {
6838 status = cmdStatus;
6839 }
6840
6841 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6842 (1000 * mConfig.outputCfg.buffer.frameCount);
6843
6844 return status;
6845}
6846
6847status_t AudioFlinger::EffectModule::init()
6848{
6849 Mutex::Autolock _l(mLock);
6850 if (mEffectInterface == NULL) {
6851 return NO_INIT;
6852 }
6853 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006854 uint32_t size = sizeof(status_t);
6855 status_t status = (*mEffectInterface)->command(mEffectInterface,
6856 EFFECT_CMD_INIT,
6857 0,
6858 NULL,
6859 &size,
6860 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006861 if (status == 0) {
6862 status = cmdStatus;
6863 }
6864 return status;
6865}
6866
6867status_t AudioFlinger::EffectModule::start_l()
6868{
6869 if (mEffectInterface == NULL) {
6870 return NO_INIT;
6871 }
6872 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006873 uint32_t size = sizeof(status_t);
6874 status_t status = (*mEffectInterface)->command(mEffectInterface,
6875 EFFECT_CMD_ENABLE,
6876 0,
6877 NULL,
6878 &size,
6879 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 if (status == 0) {
6881 status = cmdStatus;
6882 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006883 if (status == 0 &&
6884 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6885 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6886 sp<ThreadBase> thread = mThread.promote();
6887 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006888 audio_stream_t *stream = thread->stream();
6889 if (stream != NULL) {
6890 stream->add_audio_effect(stream, mEffectInterface);
6891 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006892 }
6893 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006894 return status;
6895}
6896
Eric Laurentec437d82011-07-26 20:54:46 -07006897status_t AudioFlinger::EffectModule::stop()
6898{
6899 Mutex::Autolock _l(mLock);
6900 return stop_l();
6901}
6902
Mathias Agopian65ab4712010-07-14 17:59:35 -07006903status_t AudioFlinger::EffectModule::stop_l()
6904{
6905 if (mEffectInterface == NULL) {
6906 return NO_INIT;
6907 }
6908 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006909 uint32_t size = sizeof(status_t);
6910 status_t status = (*mEffectInterface)->command(mEffectInterface,
6911 EFFECT_CMD_DISABLE,
6912 0,
6913 NULL,
6914 &size,
6915 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006916 if (status == 0) {
6917 status = cmdStatus;
6918 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006919 if (status == 0 &&
6920 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6921 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6922 sp<ThreadBase> thread = mThread.promote();
6923 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006924 audio_stream_t *stream = thread->stream();
6925 if (stream != NULL) {
6926 stream->remove_audio_effect(stream, mEffectInterface);
6927 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006928 }
6929 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006930 return status;
6931}
6932
Eric Laurent25f43952010-07-28 05:40:18 -07006933status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6934 uint32_t cmdSize,
6935 void *pCmdData,
6936 uint32_t *replySize,
6937 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938{
6939 Mutex::Autolock _l(mLock);
6940// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6941
Eric Laurentec437d82011-07-26 20:54:46 -07006942 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006943 return NO_INIT;
6944 }
Eric Laurent25f43952010-07-28 05:40:18 -07006945 status_t status = (*mEffectInterface)->command(mEffectInterface,
6946 cmdCode,
6947 cmdSize,
6948 pCmdData,
6949 replySize,
6950 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006951 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006952 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006953 for (size_t i = 1; i < mHandles.size(); i++) {
6954 sp<EffectHandle> h = mHandles[i].promote();
6955 if (h != 0) {
6956 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6957 }
6958 }
6959 }
6960 return status;
6961}
6962
6963status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6964{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006965
Mathias Agopian65ab4712010-07-14 17:59:35 -07006966 Mutex::Autolock _l(mLock);
6967 LOGV("setEnabled %p enabled %d", this, enabled);
6968
6969 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006970 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6971 if (enabled && status != NO_ERROR) {
6972 return status;
6973 }
6974
Mathias Agopian65ab4712010-07-14 17:59:35 -07006975 switch (mState) {
6976 // going from disabled to enabled
6977 case IDLE:
6978 mState = STARTING;
6979 break;
6980 case STOPPED:
6981 mState = RESTART;
6982 break;
6983 case STOPPING:
6984 mState = ACTIVE;
6985 break;
6986
6987 // going from enabled to disabled
6988 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006989 mState = STOPPED;
6990 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006991 case STARTING:
6992 mState = IDLE;
6993 break;
6994 case ACTIVE:
6995 mState = STOPPING;
6996 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006997 case DESTROYED:
6998 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006999 }
7000 for (size_t i = 1; i < mHandles.size(); i++) {
7001 sp<EffectHandle> h = mHandles[i].promote();
7002 if (h != 0) {
7003 h->setEnabled(enabled);
7004 }
7005 }
7006 }
7007 return NO_ERROR;
7008}
7009
7010bool AudioFlinger::EffectModule::isEnabled()
7011{
7012 switch (mState) {
7013 case RESTART:
7014 case STARTING:
7015 case ACTIVE:
7016 return true;
7017 case IDLE:
7018 case STOPPING:
7019 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07007020 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07007021 default:
7022 return false;
7023 }
7024}
7025
Eric Laurent8f45bd72010-08-31 13:50:07 -07007026bool AudioFlinger::EffectModule::isProcessEnabled()
7027{
7028 switch (mState) {
7029 case RESTART:
7030 case ACTIVE:
7031 case STOPPING:
7032 case STOPPED:
7033 return true;
7034 case IDLE:
7035 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07007036 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07007037 default:
7038 return false;
7039 }
7040}
7041
Mathias Agopian65ab4712010-07-14 17:59:35 -07007042status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
7043{
7044 Mutex::Autolock _l(mLock);
7045 status_t status = NO_ERROR;
7046
7047 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
7048 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07007049 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07007050 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
7051 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007052 status_t cmdStatus;
7053 uint32_t volume[2];
7054 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07007055 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007056 volume[0] = *left;
7057 volume[1] = *right;
7058 if (controller) {
7059 pVolume = volume;
7060 }
Eric Laurent25f43952010-07-28 05:40:18 -07007061 status = (*mEffectInterface)->command(mEffectInterface,
7062 EFFECT_CMD_SET_VOLUME,
7063 size,
7064 volume,
7065 &size,
7066 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007067 if (controller && status == NO_ERROR && size == sizeof(volume)) {
7068 *left = volume[0];
7069 *right = volume[1];
7070 }
7071 }
7072 return status;
7073}
7074
7075status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
7076{
7077 Mutex::Autolock _l(mLock);
7078 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007079 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
7080 // audio pre processing modules on RecordThread can receive both output and
7081 // input device indication in the same call
7082 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
7083 if (dev) {
7084 status_t cmdStatus;
7085 uint32_t size = sizeof(status_t);
7086
7087 status = (*mEffectInterface)->command(mEffectInterface,
7088 EFFECT_CMD_SET_DEVICE,
7089 sizeof(uint32_t),
7090 &dev,
7091 &size,
7092 &cmdStatus);
7093 if (status == NO_ERROR) {
7094 status = cmdStatus;
7095 }
7096 }
7097 dev = device & AUDIO_DEVICE_IN_ALL;
7098 if (dev) {
7099 status_t cmdStatus;
7100 uint32_t size = sizeof(status_t);
7101
7102 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
7103 EFFECT_CMD_SET_INPUT_DEVICE,
7104 sizeof(uint32_t),
7105 &dev,
7106 &size,
7107 &cmdStatus);
7108 if (status2 == NO_ERROR) {
7109 status2 = cmdStatus;
7110 }
7111 if (status == NO_ERROR) {
7112 status = status2;
7113 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007114 }
7115 }
7116 return status;
7117}
7118
7119status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
7120{
7121 Mutex::Autolock _l(mLock);
7122 status_t status = NO_ERROR;
7123 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007124 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07007125 uint32_t size = sizeof(status_t);
7126 status = (*mEffectInterface)->command(mEffectInterface,
7127 EFFECT_CMD_SET_AUDIO_MODE,
7128 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07007129 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07007130 &size,
7131 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007132 if (status == NO_ERROR) {
7133 status = cmdStatus;
7134 }
7135 }
7136 return status;
7137}
7138
Eric Laurent59255e42011-07-27 19:49:51 -07007139void AudioFlinger::EffectModule::setSuspended(bool suspended)
7140{
7141 Mutex::Autolock _l(mLock);
7142 mSuspended = suspended;
7143}
7144bool AudioFlinger::EffectModule::suspended()
7145{
7146 Mutex::Autolock _l(mLock);
7147 return mSuspended;
7148}
7149
Mathias Agopian65ab4712010-07-14 17:59:35 -07007150status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
7151{
7152 const size_t SIZE = 256;
7153 char buffer[SIZE];
7154 String8 result;
7155
7156 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
7157 result.append(buffer);
7158
7159 bool locked = tryLock(mLock);
7160 // failed to lock - AudioFlinger is probably deadlocked
7161 if (!locked) {
7162 result.append("\t\tCould not lock Fx mutex:\n");
7163 }
7164
7165 result.append("\t\tSession Status State Engine:\n");
7166 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
7167 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
7168 result.append(buffer);
7169
7170 result.append("\t\tDescriptor:\n");
7171 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7172 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
7173 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
7174 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
7175 result.append(buffer);
7176 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
7177 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
7178 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
7179 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
7180 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07007181 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007182 mDescriptor.apiVersion,
7183 mDescriptor.flags);
7184 result.append(buffer);
7185 snprintf(buffer, SIZE, "\t\t- name: %s\n",
7186 mDescriptor.name);
7187 result.append(buffer);
7188 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
7189 mDescriptor.implementor);
7190 result.append(buffer);
7191
7192 result.append("\t\t- Input configuration:\n");
7193 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7194 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7195 (uint32_t)mConfig.inputCfg.buffer.raw,
7196 mConfig.inputCfg.buffer.frameCount,
7197 mConfig.inputCfg.samplingRate,
7198 mConfig.inputCfg.channels,
7199 mConfig.inputCfg.format);
7200 result.append(buffer);
7201
7202 result.append("\t\t- Output configuration:\n");
7203 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
7204 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
7205 (uint32_t)mConfig.outputCfg.buffer.raw,
7206 mConfig.outputCfg.buffer.frameCount,
7207 mConfig.outputCfg.samplingRate,
7208 mConfig.outputCfg.channels,
7209 mConfig.outputCfg.format);
7210 result.append(buffer);
7211
7212 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
7213 result.append(buffer);
7214 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
7215 for (size_t i = 0; i < mHandles.size(); ++i) {
7216 sp<EffectHandle> handle = mHandles[i].promote();
7217 if (handle != 0) {
7218 handle->dump(buffer, SIZE);
7219 result.append(buffer);
7220 }
7221 }
7222
7223 result.append("\n");
7224
7225 write(fd, result.string(), result.length());
7226
7227 if (locked) {
7228 mLock.unlock();
7229 }
7230
7231 return NO_ERROR;
7232}
7233
7234// ----------------------------------------------------------------------------
7235// EffectHandle implementation
7236// ----------------------------------------------------------------------------
7237
7238#undef LOG_TAG
7239#define LOG_TAG "AudioFlinger::EffectHandle"
7240
7241AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
7242 const sp<AudioFlinger::Client>& client,
7243 const sp<IEffectClient>& effectClient,
7244 int32_t priority)
7245 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007246 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07007247 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007248{
7249 LOGV("constructor %p", this);
7250
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007251 if (client == 0) {
7252 return;
7253 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007254 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
7255 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
7256 if (mCblkMemory != 0) {
7257 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
7258
7259 if (mCblk) {
7260 new(mCblk) effect_param_cblk_t();
7261 mBuffer = (uint8_t *)mCblk + bufOffset;
7262 }
7263 } else {
7264 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
7265 return;
7266 }
7267}
7268
7269AudioFlinger::EffectHandle::~EffectHandle()
7270{
7271 LOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007272 disconnect(false);
Eric Laurent59255e42011-07-27 19:49:51 -07007273 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007274}
7275
7276status_t AudioFlinger::EffectHandle::enable()
7277{
Eric Laurent59255e42011-07-27 19:49:51 -07007278 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007279 if (!mHasControl) return INVALID_OPERATION;
7280 if (mEffect == 0) return DEAD_OBJECT;
7281
Eric Laurentdb7c0792011-08-10 10:37:50 -07007282 if (mEnabled) {
7283 return NO_ERROR;
7284 }
7285
Eric Laurent59255e42011-07-27 19:49:51 -07007286 mEnabled = true;
7287
7288 sp<ThreadBase> thread = mEffect->thread().promote();
7289 if (thread != 0) {
7290 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
7291 }
7292
7293 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
7294 if (mEffect->suspended()) {
7295 return NO_ERROR;
7296 }
7297
Eric Laurentdb7c0792011-08-10 10:37:50 -07007298 status_t status = mEffect->setEnabled(true);
7299 if (status != NO_ERROR) {
7300 if (thread != 0) {
7301 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7302 }
7303 mEnabled = false;
7304 }
7305 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007306}
7307
7308status_t AudioFlinger::EffectHandle::disable()
7309{
Eric Laurent59255e42011-07-27 19:49:51 -07007310 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007311 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07007312 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007313
Eric Laurentdb7c0792011-08-10 10:37:50 -07007314 if (!mEnabled) {
7315 return NO_ERROR;
7316 }
Eric Laurent59255e42011-07-27 19:49:51 -07007317 mEnabled = false;
7318
7319 if (mEffect->suspended()) {
7320 return NO_ERROR;
7321 }
7322
7323 status_t status = mEffect->setEnabled(false);
7324
7325 sp<ThreadBase> thread = mEffect->thread().promote();
7326 if (thread != 0) {
7327 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7328 }
7329
7330 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007331}
7332
7333void AudioFlinger::EffectHandle::disconnect()
7334{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007335 disconnect(true);
7336}
7337
7338void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
7339{
7340 LOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07007341 if (mEffect == 0) {
7342 return;
7343 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007344 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07007345
Eric Laurentdb7c0792011-08-10 10:37:50 -07007346 if (mEnabled) {
7347 sp<ThreadBase> thread = mEffect->thread().promote();
7348 if (thread != 0) {
7349 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
7350 }
Eric Laurent59255e42011-07-27 19:49:51 -07007351 }
7352
Mathias Agopian65ab4712010-07-14 17:59:35 -07007353 // release sp on module => module destructor can be called now
7354 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007355 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007356 if (mCblk) {
7357 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
7358 }
7359 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07007360 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
7361 mClient.clear();
7362 }
7363}
7364
Eric Laurent25f43952010-07-28 05:40:18 -07007365status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
7366 uint32_t cmdSize,
7367 void *pCmdData,
7368 uint32_t *replySize,
7369 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007370{
Eric Laurent25f43952010-07-28 05:40:18 -07007371// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
7372// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07007373
7374 // only get parameter command is permitted for applications not controlling the effect
7375 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
7376 return INVALID_OPERATION;
7377 }
7378 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007379 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007380
7381 // handle commands that are not forwarded transparently to effect engine
7382 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
7383 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
7384 // no risk to block the whole media server process or mixer threads is we are stuck here
7385 Mutex::Autolock _l(mCblk->lock);
7386 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
7387 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
7388 mCblk->serverIndex = 0;
7389 mCblk->clientIndex = 0;
7390 return BAD_VALUE;
7391 }
7392 status_t status = NO_ERROR;
7393 while (mCblk->serverIndex < mCblk->clientIndex) {
7394 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07007395 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007396 int *p = (int *)(mBuffer + mCblk->serverIndex);
7397 int size = *p++;
7398 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
7399 LOGW("command(): invalid parameter block size");
7400 break;
7401 }
7402 effect_param_t *param = (effect_param_t *)p;
7403 if (param->psize == 0 || param->vsize == 0) {
7404 LOGW("command(): null parameter or value size");
7405 mCblk->serverIndex += size;
7406 continue;
7407 }
Eric Laurent25f43952010-07-28 05:40:18 -07007408 uint32_t psize = sizeof(effect_param_t) +
7409 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
7410 param->vsize;
7411 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
7412 psize,
7413 p,
7414 &rsize,
7415 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07007416 // stop at first error encountered
7417 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007418 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07007419 *(int *)pReplyData = reply;
7420 break;
7421 } else if (reply != NO_ERROR) {
7422 *(int *)pReplyData = reply;
7423 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007424 }
7425 mCblk->serverIndex += size;
7426 }
7427 mCblk->serverIndex = 0;
7428 mCblk->clientIndex = 0;
7429 return status;
7430 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007431 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007432 return enable();
7433 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07007434 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007435 return disable();
7436 }
7437
7438 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7439}
7440
7441sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7442 return mCblkMemory;
7443}
7444
Eric Laurent59255e42011-07-27 19:49:51 -07007445void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007446{
7447 LOGV("setControl %p control %d", this, hasControl);
7448
7449 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007450 mEnabled = enabled;
7451
Mathias Agopian65ab4712010-07-14 17:59:35 -07007452 if (signal && mEffectClient != 0) {
7453 mEffectClient->controlStatusChanged(hasControl);
7454 }
7455}
7456
Eric Laurent25f43952010-07-28 05:40:18 -07007457void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7458 uint32_t cmdSize,
7459 void *pCmdData,
7460 uint32_t replySize,
7461 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007462{
7463 if (mEffectClient != 0) {
7464 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7465 }
7466}
7467
7468
7469
7470void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7471{
7472 if (mEffectClient != 0) {
7473 mEffectClient->enableStatusChanged(enabled);
7474 }
7475}
7476
7477status_t AudioFlinger::EffectHandle::onTransact(
7478 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7479{
7480 return BnEffect::onTransact(code, data, reply, flags);
7481}
7482
7483
7484void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7485{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007486 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007487
7488 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7489 (mClient == NULL) ? getpid() : mClient->pid(),
7490 mPriority,
7491 mHasControl,
7492 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007493 mCblk ? mCblk->clientIndex : 0,
7494 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007495 );
7496
7497 if (locked) {
7498 mCblk->lock.unlock();
7499 }
7500}
7501
7502#undef LOG_TAG
7503#define LOG_TAG "AudioFlinger::EffectChain"
7504
7505AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7506 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07007507 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
7508 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7509 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007510{
Dima Zavinfce7a472011-04-19 22:30:36 -07007511 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007512}
7513
7514AudioFlinger::EffectChain::~EffectChain()
7515{
7516 if (mOwnInBuffer) {
7517 delete mInBuffer;
7518 }
7519
7520}
7521
Eric Laurent59255e42011-07-27 19:49:51 -07007522// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007523sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007524{
7525 sp<EffectModule> effect;
7526 size_t size = mEffects.size();
7527
7528 for (size_t i = 0; i < size; i++) {
7529 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7530 effect = mEffects[i];
7531 break;
7532 }
7533 }
7534 return effect;
7535}
7536
Eric Laurent59255e42011-07-27 19:49:51 -07007537// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007538sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007539{
7540 sp<EffectModule> effect;
7541 size_t size = mEffects.size();
7542
7543 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007544 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7545 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007546 effect = mEffects[i];
7547 break;
7548 }
7549 }
7550 return effect;
7551}
7552
Eric Laurent59255e42011-07-27 19:49:51 -07007553// getEffectFromType_l() must be called with ThreadBase::mLock held
7554sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7555 const effect_uuid_t *type)
7556{
7557 sp<EffectModule> effect;
7558 size_t size = mEffects.size();
7559
7560 for (size_t i = 0; i < size; i++) {
7561 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7562 effect = mEffects[i];
7563 break;
7564 }
7565 }
7566 return effect;
7567}
7568
Mathias Agopian65ab4712010-07-14 17:59:35 -07007569// Must be called with EffectChain::mLock locked
7570void AudioFlinger::EffectChain::process_l()
7571{
Eric Laurentdac69112010-09-28 14:09:57 -07007572 sp<ThreadBase> thread = mThread.promote();
7573 if (thread == 0) {
7574 LOGW("process_l(): cannot promote mixer thread");
7575 return;
7576 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007577 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7578 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07007579 bool tracksOnSession = false;
7580 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07007581 tracksOnSession = (trackCnt() != 0);
7582 }
7583
7584 // if no track is active, input buffer must be cleared here as the mixer process
7585 // will not do it
7586 if (tracksOnSession &&
7587 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07007588 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07007589 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07007590 }
7591
Mathias Agopian65ab4712010-07-14 17:59:35 -07007592 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07007593 // do not process effect if no track is present in same audio session
7594 if (isGlobalSession || tracksOnSession) {
7595 for (size_t i = 0; i < size; i++) {
7596 mEffects[i]->process();
7597 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007598 }
7599 for (size_t i = 0; i < size; i++) {
7600 mEffects[i]->updateState();
7601 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007602}
7603
Eric Laurentcab11242010-07-15 12:50:15 -07007604// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007605status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007606{
7607 effect_descriptor_t desc = effect->desc();
7608 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7609
7610 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007611 effect->setChain(this);
7612 sp<ThreadBase> thread = mThread.promote();
7613 if (thread == 0) {
7614 return NO_INIT;
7615 }
7616 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007617
7618 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7619 // Auxiliary effects are inserted at the beginning of mEffects vector as
7620 // they are processed first and accumulated in chain input buffer
7621 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007622
Mathias Agopian65ab4712010-07-14 17:59:35 -07007623 // the input buffer for auxiliary effect contains mono samples in
7624 // 32 bit format. This is to avoid saturation in AudoMixer
7625 // accumulation stage. Saturation is done in EffectModule::process() before
7626 // calling the process in effect engine
7627 size_t numSamples = thread->frameCount();
7628 int32_t *buffer = new int32_t[numSamples];
7629 memset(buffer, 0, numSamples * sizeof(int32_t));
7630 effect->setInBuffer((int16_t *)buffer);
7631 // auxiliary effects output samples to chain input buffer for further processing
7632 // by insert effects
7633 effect->setOutBuffer(mInBuffer);
7634 } else {
7635 // Insert effects are inserted at the end of mEffects vector as they are processed
7636 // after track and auxiliary effects.
7637 // Insert effect order as a function of indicated preference:
7638 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7639 // another effect is present
7640 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7641 // last effect claiming first position
7642 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7643 // first effect claiming last position
7644 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7645 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7646 // already present
7647
7648 int size = (int)mEffects.size();
7649 int idx_insert = size;
7650 int idx_insert_first = -1;
7651 int idx_insert_last = -1;
7652
7653 for (int i = 0; i < size; i++) {
7654 effect_descriptor_t d = mEffects[i]->desc();
7655 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7656 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7657 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7658 // check invalid effect chaining combinations
7659 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7660 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007661 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007662 return INVALID_OPERATION;
7663 }
7664 // remember position of first insert effect and by default
7665 // select this as insert position for new effect
7666 if (idx_insert == size) {
7667 idx_insert = i;
7668 }
7669 // remember position of last insert effect claiming
7670 // first position
7671 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7672 idx_insert_first = i;
7673 }
7674 // remember position of first insert effect claiming
7675 // last position
7676 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7677 idx_insert_last == -1) {
7678 idx_insert_last = i;
7679 }
7680 }
7681 }
7682
7683 // modify idx_insert from first position if needed
7684 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7685 if (idx_insert_last != -1) {
7686 idx_insert = idx_insert_last;
7687 } else {
7688 idx_insert = size;
7689 }
7690 } else {
7691 if (idx_insert_first != -1) {
7692 idx_insert = idx_insert_first + 1;
7693 }
7694 }
7695
7696 // always read samples from chain input buffer
7697 effect->setInBuffer(mInBuffer);
7698
7699 // if last effect in the chain, output samples to chain
7700 // output buffer, otherwise to chain input buffer
7701 if (idx_insert == size) {
7702 if (idx_insert != 0) {
7703 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7704 mEffects[idx_insert-1]->configure();
7705 }
7706 effect->setOutBuffer(mOutBuffer);
7707 } else {
7708 effect->setOutBuffer(mInBuffer);
7709 }
7710 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007711
Eric Laurentcab11242010-07-15 12:50:15 -07007712 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007713 }
7714 effect->configure();
7715 return NO_ERROR;
7716}
7717
Eric Laurentcab11242010-07-15 12:50:15 -07007718// removeEffect_l() must be called with PlaybackThread::mLock held
7719size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007720{
7721 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007722 int size = (int)mEffects.size();
7723 int i;
7724 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7725
7726 for (i = 0; i < size; i++) {
7727 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007728 // calling stop here will remove pre-processing effect from the audio HAL.
7729 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7730 // the middle of a read from audio HAL
7731 mEffects[i]->stop();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007732 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7733 delete[] effect->inBuffer();
7734 } else {
7735 if (i == size - 1 && i != 0) {
7736 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7737 mEffects[i - 1]->configure();
7738 }
7739 }
7740 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07007741 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007742 break;
7743 }
7744 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007745
7746 return mEffects.size();
7747}
7748
Eric Laurentcab11242010-07-15 12:50:15 -07007749// setDevice_l() must be called with PlaybackThread::mLock held
7750void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007751{
7752 size_t size = mEffects.size();
7753 for (size_t i = 0; i < size; i++) {
7754 mEffects[i]->setDevice(device);
7755 }
7756}
7757
Eric Laurentcab11242010-07-15 12:50:15 -07007758// setMode_l() must be called with PlaybackThread::mLock held
7759void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007760{
7761 size_t size = mEffects.size();
7762 for (size_t i = 0; i < size; i++) {
7763 mEffects[i]->setMode(mode);
7764 }
7765}
7766
Eric Laurentcab11242010-07-15 12:50:15 -07007767// setVolume_l() must be called with PlaybackThread::mLock held
7768bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007769{
7770 uint32_t newLeft = *left;
7771 uint32_t newRight = *right;
7772 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007773 int ctrlIdx = -1;
7774 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007775
Eric Laurentcab11242010-07-15 12:50:15 -07007776 // first update volume controller
7777 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007778 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007779 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7780 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007781 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007782 break;
7783 }
7784 }
7785
7786 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007787 if (hasControl) {
7788 *left = mNewLeftVolume;
7789 *right = mNewRightVolume;
7790 }
7791 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007792 }
7793
7794 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007795 mLeftVolume = newLeft;
7796 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007797
7798 // second get volume update from volume controller
7799 if (ctrlIdx >= 0) {
7800 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007801 mNewLeftVolume = newLeft;
7802 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007803 }
7804 // then indicate volume to all other effects in chain.
7805 // Pass altered volume to effects before volume controller
7806 // and requested volume to effects after controller
7807 uint32_t lVol = newLeft;
7808 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007809
Mathias Agopian65ab4712010-07-14 17:59:35 -07007810 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007811 if ((int)i == ctrlIdx) continue;
7812 // this also works for ctrlIdx == -1 when there is no volume controller
7813 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007814 lVol = *left;
7815 rVol = *right;
7816 }
7817 mEffects[i]->setVolume(&lVol, &rVol, false);
7818 }
7819 *left = newLeft;
7820 *right = newRight;
7821
7822 return hasControl;
7823}
7824
Mathias Agopian65ab4712010-07-14 17:59:35 -07007825status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7826{
7827 const size_t SIZE = 256;
7828 char buffer[SIZE];
7829 String8 result;
7830
7831 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7832 result.append(buffer);
7833
7834 bool locked = tryLock(mLock);
7835 // failed to lock - AudioFlinger is probably deadlocked
7836 if (!locked) {
7837 result.append("\tCould not lock mutex:\n");
7838 }
7839
Eric Laurentcab11242010-07-15 12:50:15 -07007840 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7841 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007842 mEffects.size(),
7843 (uint32_t)mInBuffer,
7844 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007845 mActiveTrackCnt);
7846 result.append(buffer);
7847 write(fd, result.string(), result.size());
7848
7849 for (size_t i = 0; i < mEffects.size(); ++i) {
7850 sp<EffectModule> effect = mEffects[i];
7851 if (effect != 0) {
7852 effect->dump(fd, args);
7853 }
7854 }
7855
7856 if (locked) {
7857 mLock.unlock();
7858 }
7859
7860 return NO_ERROR;
7861}
7862
Eric Laurent59255e42011-07-27 19:49:51 -07007863// must be called with ThreadBase::mLock held
7864void AudioFlinger::EffectChain::setEffectSuspended_l(
7865 const effect_uuid_t *type, bool suspend)
7866{
7867 sp<SuspendedEffectDesc> desc;
7868 // use effect type UUID timelow as key as there is no real risk of identical
7869 // timeLow fields among effect type UUIDs.
7870 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7871 if (suspend) {
7872 if (index >= 0) {
7873 desc = mSuspendedEffects.valueAt(index);
7874 } else {
7875 desc = new SuspendedEffectDesc();
7876 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7877 mSuspendedEffects.add(type->timeLow, desc);
7878 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7879 }
7880 if (desc->mRefCount++ == 0) {
7881 sp<EffectModule> effect = getEffectIfEnabled(type);
7882 if (effect != 0) {
7883 desc->mEffect = effect;
7884 effect->setSuspended(true);
7885 effect->setEnabled(false);
7886 }
7887 }
7888 } else {
7889 if (index < 0) {
7890 return;
7891 }
7892 desc = mSuspendedEffects.valueAt(index);
7893 if (desc->mRefCount <= 0) {
7894 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7895 desc->mRefCount = 1;
7896 }
7897 if (--desc->mRefCount == 0) {
7898 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7899 if (desc->mEffect != 0) {
7900 sp<EffectModule> effect = desc->mEffect.promote();
7901 if (effect != 0) {
7902 effect->setSuspended(false);
7903 sp<EffectHandle> handle = effect->controlHandle();
7904 if (handle != 0) {
7905 effect->setEnabled(handle->enabled());
7906 }
7907 }
7908 desc->mEffect.clear();
7909 }
7910 mSuspendedEffects.removeItemsAt(index);
7911 }
7912 }
7913}
7914
7915// must be called with ThreadBase::mLock held
7916void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7917{
7918 sp<SuspendedEffectDesc> desc;
7919
7920 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7921 if (suspend) {
7922 if (index >= 0) {
7923 desc = mSuspendedEffects.valueAt(index);
7924 } else {
7925 desc = new SuspendedEffectDesc();
7926 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7927 LOGV("setEffectSuspendedAll_l() add entry for 0");
7928 }
7929 if (desc->mRefCount++ == 0) {
7930 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7931 for (size_t i = 0; i < effects.size(); i++) {
7932 setEffectSuspended_l(&effects[i]->desc().type, true);
7933 }
7934 }
7935 } else {
7936 if (index < 0) {
7937 return;
7938 }
7939 desc = mSuspendedEffects.valueAt(index);
7940 if (desc->mRefCount <= 0) {
7941 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7942 desc->mRefCount = 1;
7943 }
7944 if (--desc->mRefCount == 0) {
7945 Vector<const effect_uuid_t *> types;
7946 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7947 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7948 continue;
7949 }
7950 types.add(&mSuspendedEffects.valueAt(i)->mType);
7951 }
7952 for (size_t i = 0; i < types.size(); i++) {
7953 setEffectSuspended_l(types[i], false);
7954 }
7955 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7956 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7957 }
7958 }
7959}
7960
Eric Laurentdb7c0792011-08-10 10:37:50 -07007961bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7962{
7963 // auxiliary effects and visualizer are never suspended on output mix
7964 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7965 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7966 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0))) {
7967 return false;
7968 }
7969 return true;
7970}
7971
Eric Laurent59255e42011-07-27 19:49:51 -07007972Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7973{
7974 Vector< sp<EffectModule> > effects;
7975 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007976 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007977 continue;
7978 }
7979 effects.add(mEffects[i]);
7980 }
7981 return effects;
7982}
7983
7984sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7985 const effect_uuid_t *type)
7986{
7987 sp<EffectModule> effect;
7988 effect = getEffectFromType_l(type);
7989 if (effect != 0 && !effect->isEnabled()) {
7990 effect.clear();
7991 }
7992 return effect;
7993}
7994
7995void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7996 bool enabled)
7997{
7998 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7999 if (enabled) {
8000 if (index < 0) {
8001 // if the effect is not suspend check if all effects are suspended
8002 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
8003 if (index < 0) {
8004 return;
8005 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07008006 if (!isEffectEligibleForSuspend(effect->desc())) {
8007 return;
8008 }
Eric Laurent59255e42011-07-27 19:49:51 -07008009 setEffectSuspended_l(&effect->desc().type, enabled);
8010 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07008011 if (index < 0) {
8012 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
8013 return;
8014 }
Eric Laurent59255e42011-07-27 19:49:51 -07008015 }
8016 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
8017 effect->desc().type.timeLow);
8018 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8019 // if effect is requested to suspended but was not yet enabled, supend it now.
8020 if (desc->mEffect == 0) {
8021 desc->mEffect = effect;
8022 effect->setEnabled(false);
8023 effect->setSuspended(true);
8024 }
8025 } else {
8026 if (index < 0) {
8027 return;
8028 }
8029 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
8030 effect->desc().type.timeLow);
8031 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
8032 desc->mEffect.clear();
8033 effect->setSuspended(false);
8034 }
8035}
8036
Mathias Agopian65ab4712010-07-14 17:59:35 -07008037#undef LOG_TAG
8038#define LOG_TAG "AudioFlinger"
8039
8040// ----------------------------------------------------------------------------
8041
8042status_t AudioFlinger::onTransact(
8043 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
8044{
8045 return BnAudioFlinger::onTransact(code, data, reply, flags);
8046}
8047
Mathias Agopian65ab4712010-07-14 17:59:35 -07008048}; // namespace android