blob: c6be9be49e0371ada28e1ae2a3eaff84cf82184f [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 Kasten3b21c502011-12-15 09:52:39 -080057#include <audio_utils/primitives.h>
58
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070059#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070060#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070061// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
62
Mathias Agopian65ab4712010-07-14 17:59:35 -070063// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070064
Eric Laurentde070132010-07-13 04:45:46 -070065
Mathias Agopian65ab4712010-07-14 17:59:35 -070066namespace android {
67
Glenn Kastenec1d6b52011-12-12 09:04:45 -080068static const char kDeadlockedString[] = "AudioFlinger may be deadlocked\n";
69static const char kHardwareLockedString[] = "Hardware lock is taken\n";
Mathias Agopian65ab4712010-07-14 17:59:35 -070070
71//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
72static const float MAX_GAIN = 4096.0f;
73static const float MAX_GAIN_INT = 0x1000;
74
75// retry counts for buffer fill timeout
76// 50 * ~20msecs = 1 second
77static const int8_t kMaxTrackRetries = 50;
78static const int8_t kMaxTrackStartupRetries = 50;
79// allow less retry attempts on direct output thread.
80// direct outputs can be a scarce resource in audio hardware and should
81// be released as quickly as possible.
82static const int8_t kMaxTrackRetriesDirect = 2;
83
84static const int kDumpLockRetries = 50;
Glenn Kasten7dede872011-12-13 11:04:14 -080085static const int kDumpLockSleepUs = 20000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Glenn Kasten7dede872011-12-13 11:04:14 -080087// don't warn about blocked writes or record buffer overflows more often than this
88static const nsecs_t kWarningThrottleNs = seconds(5);
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
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
Glenn Kasten7dede872011-12-13 11:04:14 -080093// maximum time to wait for setParameters to complete
94static const nsecs_t kSetParametersTimeoutNs = seconds(2);
Eric Laurent60cd0a02011-09-13 11:40:21 -070095
Eric Laurent7cafbb32011-11-22 18:50:29 -080096// minimum sleep time for the mixer thread loop when tracks are active but in underrun
97static const uint32_t kMinThreadSleepTimeUs = 5000;
98// maximum divider applied to the active sleep time in the mixer thread loop
99static const uint32_t kMaxThreadSleepTimeShift = 2;
100
101
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102// ----------------------------------------------------------------------------
103
104static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700105 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
106 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
107 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
108 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109}
110
111static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
113 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
114 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
115 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116}
117
Gloria Wang9ee159b2011-02-24 14:51:45 -0800118// To collect the amplifier usage
119static void addBatteryData(uint32_t params) {
120 sp<IBinder> binder =
121 defaultServiceManager()->getService(String16("media.player"));
122 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
123 if (service.get() == NULL) {
124 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
125 return;
126 }
127
128 service->addBatteryData(params);
129}
130
Dima Zavin799a70e2011-04-18 16:57:27 -0700131static int load_audio_interface(const char *if_name, const hw_module_t **mod,
132 audio_hw_device_t **dev)
133{
134 int rc;
135
136 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
137 if (rc)
138 goto out;
139
140 rc = audio_hw_device_open(*mod, dev);
141 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
142 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
143 if (rc)
144 goto out;
145
146 return 0;
147
148out:
149 *mod = NULL;
150 *dev = NULL;
151 return rc;
152}
153
Glenn Kastenec1d6b52011-12-12 09:04:45 -0800154static const char * const audio_interfaces[] = {
Dima Zavin799a70e2011-04-18 16:57:27 -0700155 "primary",
156 "a2dp",
157 "usb",
158};
159#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
160
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161// ----------------------------------------------------------------------------
162
163AudioFlinger::AudioFlinger()
164 : BnAudioFlinger(),
Glenn Kastene0feee32011-12-13 11:53:26 -0800165 mPrimaryHardwareDev(NULL), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1),
Eric Laurentbee53372011-08-29 12:42:48 -0700166 mBtNrecIsOff(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700167{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700168}
169
170void AudioFlinger::onFirstRef()
171{
Dima Zavin799a70e2011-04-18 16:57:27 -0700172 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700173
Eric Laurent93575202011-01-18 18:39:02 -0800174 Mutex::Autolock _l(mLock);
175
Dima Zavin799a70e2011-04-18 16:57:27 -0700176 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700177 mHardwareStatus = AUDIO_HW_IDLE;
178
Dima Zavin799a70e2011-04-18 16:57:27 -0700179 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
180 const hw_module_t *mod;
181 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700182
Dima Zavin799a70e2011-04-18 16:57:27 -0700183 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
184 if (rc)
185 continue;
186
187 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
188 mod->name, mod->id);
189 mAudioHwDevs.push(dev);
190
191 if (!mPrimaryHardwareDev) {
192 mPrimaryHardwareDev = dev;
193 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700194 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700195 }
196 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700197
198 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700199
Dima Zavin799a70e2011-04-18 16:57:27 -0700200 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
201 LOGE("Primary audio interface not found");
202 return;
203 }
204
205 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
206 audio_hw_device_t *dev = mAudioHwDevs[i];
207
208 mHardwareStatus = AUDIO_HW_INIT;
209 rc = dev->init_check(dev);
210 if (rc == 0) {
211 AutoMutex lock(mHardwareLock);
212
213 mMode = AUDIO_MODE_NORMAL;
214 mHardwareStatus = AUDIO_HW_SET_MODE;
215 dev->set_mode(dev, mMode);
216 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
217 dev->set_master_volume(dev, 1.0f);
218 mHardwareStatus = AUDIO_HW_IDLE;
219 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221}
222
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700223status_t AudioFlinger::initCheck() const
224{
225 Mutex::Autolock _l(mLock);
226 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
227 return NO_INIT;
228 return NO_ERROR;
229}
230
Mathias Agopian65ab4712010-07-14 17:59:35 -0700231AudioFlinger::~AudioFlinger()
232{
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 int num_devs = mAudioHwDevs.size();
234
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235 while (!mRecordThreads.isEmpty()) {
236 // closeInput() will remove first entry from mRecordThreads
237 closeInput(mRecordThreads.keyAt(0));
238 }
239 while (!mPlaybackThreads.isEmpty()) {
240 // closeOutput() will remove first entry from mPlaybackThreads
241 closeOutput(mPlaybackThreads.keyAt(0));
242 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700243
244 for (int i = 0; i < num_devs; i++) {
245 audio_hw_device_t *dev = mAudioHwDevs[i];
246 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700248 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700249}
250
Dima Zavin799a70e2011-04-18 16:57:27 -0700251audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
252{
253 /* first matching HW device is returned */
254 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
255 audio_hw_device_t *dev = mAudioHwDevs[i];
256 if ((dev->get_supported_devices(dev) & devices) == devices)
257 return dev;
258 }
259 return NULL;
260}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700261
262status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
263{
264 const size_t SIZE = 256;
265 char buffer[SIZE];
266 String8 result;
267
268 result.append("Clients:\n");
269 for (size_t i = 0; i < mClients.size(); ++i) {
270 wp<Client> wClient = mClients.valueAt(i);
271 if (wClient != 0) {
272 sp<Client> client = wClient.promote();
273 if (client != 0) {
274 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
275 result.append(buffer);
276 }
277 }
278 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700279
280 result.append("Global session refs:\n");
281 result.append(" session pid cnt\n");
282 for (size_t i = 0; i < mAudioSessionRefs.size(); i++) {
283 AudioSessionRef *r = mAudioSessionRefs[i];
284 snprintf(buffer, SIZE, " %7d %3d %3d\n", r->sessionid, r->pid, r->cnt);
285 result.append(buffer);
286 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700287 write(fd, result.string(), result.size());
288 return NO_ERROR;
289}
290
291
292status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
293{
294 const size_t SIZE = 256;
295 char buffer[SIZE];
296 String8 result;
297 int hardwareStatus = mHardwareStatus;
298
299 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
300 result.append(buffer);
301 write(fd, result.string(), result.size());
302 return NO_ERROR;
303}
304
305status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
306{
307 const size_t SIZE = 256;
308 char buffer[SIZE];
309 String8 result;
310 snprintf(buffer, SIZE, "Permission Denial: "
311 "can't dump AudioFlinger from pid=%d, uid=%d\n",
312 IPCThreadState::self()->getCallingPid(),
313 IPCThreadState::self()->getCallingUid());
314 result.append(buffer);
315 write(fd, result.string(), result.size());
316 return NO_ERROR;
317}
318
319static bool tryLock(Mutex& mutex)
320{
321 bool locked = false;
322 for (int i = 0; i < kDumpLockRetries; ++i) {
323 if (mutex.tryLock() == NO_ERROR) {
324 locked = true;
325 break;
326 }
Glenn Kasten7dede872011-12-13 11:04:14 -0800327 usleep(kDumpLockSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328 }
329 return locked;
330}
331
332status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
333{
334 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
335 dumpPermissionDenial(fd, args);
336 } else {
337 // get state of hardware lock
338 bool hardwareLocked = tryLock(mHardwareLock);
339 if (!hardwareLocked) {
340 String8 result(kHardwareLockedString);
341 write(fd, result.string(), result.size());
342 } else {
343 mHardwareLock.unlock();
344 }
345
346 bool locked = tryLock(mLock);
347
348 // failed to lock - AudioFlinger is probably deadlocked
349 if (!locked) {
350 String8 result(kDeadlockedString);
351 write(fd, result.string(), result.size());
352 }
353
354 dumpClients(fd, args);
355 dumpInternals(fd, args);
356
357 // dump playback threads
358 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
359 mPlaybackThreads.valueAt(i)->dump(fd, args);
360 }
361
362 // dump record threads
363 for (size_t i = 0; i < mRecordThreads.size(); i++) {
364 mRecordThreads.valueAt(i)->dump(fd, args);
365 }
366
Dima Zavin799a70e2011-04-18 16:57:27 -0700367 // dump all hardware devs
368 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
369 audio_hw_device_t *dev = mAudioHwDevs[i];
370 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371 }
372 if (locked) mLock.unlock();
373 }
374 return NO_ERROR;
375}
376
377
378// IAudioFlinger interface
379
380
381sp<IAudioTrack> AudioFlinger::createTrack(
382 pid_t pid,
383 int streamType,
384 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700385 uint32_t format,
386 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700387 int frameCount,
388 uint32_t flags,
389 const sp<IMemory>& sharedBuffer,
390 int output,
391 int *sessionId,
392 status_t *status)
393{
394 sp<PlaybackThread::Track> track;
395 sp<TrackHandle> trackHandle;
396 sp<Client> client;
397 wp<Client> wclient;
398 status_t lStatus;
399 int lSessionId;
400
Dima Zavinfce7a472011-04-19 22:30:36 -0700401 if (streamType >= AUDIO_STREAM_CNT) {
Glenn Kastend8796012011-10-28 10:31:42 -0700402 LOGE("createTrack() invalid stream type %d", streamType);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 lStatus = BAD_VALUE;
404 goto Exit;
405 }
406
407 {
408 Mutex::Autolock _l(mLock);
409 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700410 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700411 if (thread == NULL) {
412 LOGE("unknown output thread");
413 lStatus = BAD_VALUE;
414 goto Exit;
415 }
416
417 wclient = mClients.valueFor(pid);
418
419 if (wclient != NULL) {
420 client = wclient.promote();
421 } else {
422 client = new Client(this, pid);
423 mClients.add(pid, client);
424 }
425
Steve Block3856b092011-10-20 11:56:00 +0100426 ALOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700427 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700428 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700429 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
430 if (mPlaybackThreads.keyAt(i) != output) {
431 // prevent same audio session on different output threads
432 uint32_t sessions = t->hasAudioSession(*sessionId);
433 if (sessions & PlaybackThread::TRACK_SESSION) {
Glenn Kastend8796012011-10-28 10:31:42 -0700434 LOGE("createTrack() session ID %d already in use", *sessionId);
Eric Laurent39e94f82010-07-28 01:32:47 -0700435 lStatus = BAD_VALUE;
436 goto Exit;
437 }
438 // check if an effect with same session ID is waiting for a track to be created
439 if (sessions & PlaybackThread::EFFECT_SESSION) {
440 effectThread = t.get();
441 }
Eric Laurentde070132010-07-13 04:45:46 -0700442 }
443 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700444 lSessionId = *sessionId;
445 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700446 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700447 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700448 if (sessionId != NULL) {
449 *sessionId = lSessionId;
450 }
451 }
Steve Block3856b092011-10-20 11:56:00 +0100452 ALOGV("createTrack() lSessionId: %d", lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700453
454 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700455 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700456
457 // move effect chain to this output thread if an effect on same session was waiting
458 // for a track to be created
459 if (lStatus == NO_ERROR && effectThread != NULL) {
460 Mutex::Autolock _dl(thread->mLock);
461 Mutex::Autolock _sl(effectThread->mLock);
462 moveEffectChain_l(lSessionId, effectThread, thread, true);
463 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700464 }
465 if (lStatus == NO_ERROR) {
466 trackHandle = new TrackHandle(track);
467 } else {
468 // remove local strong reference to Client before deleting the Track so that the Client
469 // destructor is called by the TrackBase destructor with mLock held
470 client.clear();
471 track.clear();
472 }
473
474Exit:
475 if(status) {
476 *status = lStatus;
477 }
478 return trackHandle;
479}
480
481uint32_t AudioFlinger::sampleRate(int output) const
482{
483 Mutex::Autolock _l(mLock);
484 PlaybackThread *thread = checkPlaybackThread_l(output);
485 if (thread == NULL) {
486 LOGW("sampleRate() unknown thread %d", output);
487 return 0;
488 }
489 return thread->sampleRate();
490}
491
492int AudioFlinger::channelCount(int output) const
493{
494 Mutex::Autolock _l(mLock);
495 PlaybackThread *thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
497 LOGW("channelCount() unknown thread %d", output);
498 return 0;
499 }
500 return thread->channelCount();
501}
502
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700503uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700504{
505 Mutex::Autolock _l(mLock);
506 PlaybackThread *thread = checkPlaybackThread_l(output);
507 if (thread == NULL) {
508 LOGW("format() unknown thread %d", output);
509 return 0;
510 }
511 return thread->format();
512}
513
514size_t AudioFlinger::frameCount(int output) const
515{
516 Mutex::Autolock _l(mLock);
517 PlaybackThread *thread = checkPlaybackThread_l(output);
518 if (thread == NULL) {
519 LOGW("frameCount() unknown thread %d", output);
520 return 0;
521 }
522 return thread->frameCount();
523}
524
525uint32_t AudioFlinger::latency(int output) const
526{
527 Mutex::Autolock _l(mLock);
528 PlaybackThread *thread = checkPlaybackThread_l(output);
529 if (thread == NULL) {
530 LOGW("latency() unknown thread %d", output);
531 return 0;
532 }
533 return thread->latency();
534}
535
536status_t AudioFlinger::setMasterVolume(float value)
537{
Eric Laurenta1884f92011-08-23 08:25:03 -0700538 status_t ret = initCheck();
539 if (ret != NO_ERROR) {
540 return ret;
541 }
542
Mathias Agopian65ab4712010-07-14 17:59:35 -0700543 // check calling permissions
544 if (!settingsAllowed()) {
545 return PERMISSION_DENIED;
546 }
547
548 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800549 { // scope for the lock
550 AutoMutex lock(mHardwareLock);
551 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700552 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800553 value = 1.0f;
554 }
555 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700556 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700557
Eric Laurent93575202011-01-18 18:39:02 -0800558 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700559 mMasterVolume = value;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
561 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
562
563 return NO_ERROR;
564}
565
566status_t AudioFlinger::setMode(int mode)
567{
Eric Laurenta1884f92011-08-23 08:25:03 -0700568 status_t ret = initCheck();
569 if (ret != NO_ERROR) {
570 return ret;
571 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700572
573 // check calling permissions
574 if (!settingsAllowed()) {
575 return PERMISSION_DENIED;
576 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700577 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 LOGW("Illegal value: setMode(%d)", mode);
579 return BAD_VALUE;
580 }
581
582 { // scope for the lock
583 AutoMutex lock(mHardwareLock);
584 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700585 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
587 }
588
589 if (NO_ERROR == ret) {
590 Mutex::Autolock _l(mLock);
591 mMode = mode;
592 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
593 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700594 }
595
596 return ret;
597}
598
599status_t AudioFlinger::setMicMute(bool state)
600{
Eric Laurenta1884f92011-08-23 08:25:03 -0700601 status_t ret = initCheck();
602 if (ret != NO_ERROR) {
603 return ret;
604 }
605
Mathias Agopian65ab4712010-07-14 17:59:35 -0700606 // check calling permissions
607 if (!settingsAllowed()) {
608 return PERMISSION_DENIED;
609 }
610
611 AutoMutex lock(mHardwareLock);
612 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Eric Laurenta1884f92011-08-23 08:25:03 -0700613 ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700614 mHardwareStatus = AUDIO_HW_IDLE;
615 return ret;
616}
617
618bool AudioFlinger::getMicMute() const
619{
Eric Laurenta1884f92011-08-23 08:25:03 -0700620 status_t ret = initCheck();
621 if (ret != NO_ERROR) {
622 return false;
623 }
624
Dima Zavinfce7a472011-04-19 22:30:36 -0700625 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700626 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700627 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700628 mHardwareStatus = AUDIO_HW_IDLE;
629 return state;
630}
631
632status_t AudioFlinger::setMasterMute(bool muted)
633{
634 // check calling permissions
635 if (!settingsAllowed()) {
636 return PERMISSION_DENIED;
637 }
638
Eric Laurent93575202011-01-18 18:39:02 -0800639 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700640 mMasterMute = muted;
641 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
642 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
643
644 return NO_ERROR;
645}
646
647float AudioFlinger::masterVolume() const
648{
649 return mMasterVolume;
650}
651
652bool AudioFlinger::masterMute() const
653{
654 return mMasterMute;
655}
656
657status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
658{
659 // check calling permissions
660 if (!settingsAllowed()) {
661 return PERMISSION_DENIED;
662 }
663
Dima Zavinfce7a472011-04-19 22:30:36 -0700664 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Glenn Kastend8796012011-10-28 10:31:42 -0700665 LOGE("setStreamVolume() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700666 return BAD_VALUE;
667 }
668
669 AutoMutex lock(mLock);
670 PlaybackThread *thread = NULL;
671 if (output) {
672 thread = checkPlaybackThread_l(output);
673 if (thread == NULL) {
674 return BAD_VALUE;
675 }
676 }
677
678 mStreamTypes[stream].volume = value;
679
680 if (thread == NULL) {
681 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
682 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
683 }
684 } else {
685 thread->setStreamVolume(stream, value);
686 }
687
688 return NO_ERROR;
689}
690
691status_t AudioFlinger::setStreamMute(int stream, bool muted)
692{
693 // check calling permissions
694 if (!settingsAllowed()) {
695 return PERMISSION_DENIED;
696 }
697
Dima Zavinfce7a472011-04-19 22:30:36 -0700698 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
699 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Glenn Kastend8796012011-10-28 10:31:42 -0700700 LOGE("setStreamMute() invalid stream %d", stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700701 return BAD_VALUE;
702 }
703
Eric Laurent93575202011-01-18 18:39:02 -0800704 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705 mStreamTypes[stream].mute = muted;
706 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
707 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
708
709 return NO_ERROR;
710}
711
712float AudioFlinger::streamVolume(int stream, int output) const
713{
Dima Zavinfce7a472011-04-19 22:30:36 -0700714 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700715 return 0.0f;
716 }
717
718 AutoMutex lock(mLock);
719 float volume;
720 if (output) {
721 PlaybackThread *thread = checkPlaybackThread_l(output);
722 if (thread == NULL) {
723 return 0.0f;
724 }
725 volume = thread->streamVolume(stream);
726 } else {
727 volume = mStreamTypes[stream].volume;
728 }
729
730 return volume;
731}
732
733bool AudioFlinger::streamMute(int stream) const
734{
Dima Zavinfce7a472011-04-19 22:30:36 -0700735 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 return true;
737 }
738
739 return mStreamTypes[stream].mute;
740}
741
Mathias Agopian65ab4712010-07-14 17:59:35 -0700742status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
743{
744 status_t result;
745
Steve Block3856b092011-10-20 11:56:00 +0100746 ALOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700747 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
748 // check calling permissions
749 if (!settingsAllowed()) {
750 return PERMISSION_DENIED;
751 }
752
Mathias Agopian65ab4712010-07-14 17:59:35 -0700753 // ioHandle == 0 means the parameters are global to the audio hardware interface
754 if (ioHandle == 0) {
755 AutoMutex lock(mHardwareLock);
756 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700757 status_t final_result = NO_ERROR;
758 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
759 audio_hw_device_t *dev = mAudioHwDevs[i];
760 result = dev->set_parameters(dev, keyValuePairs.string());
761 final_result = result ?: final_result;
762 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700763 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700764 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
765 AudioParameter param = AudioParameter(keyValuePairs);
766 String8 value;
767 if (param.get(String8(AUDIO_PARAMETER_KEY_BT_NREC), value) == NO_ERROR) {
768 Mutex::Autolock _l(mLock);
Eric Laurentbee53372011-08-29 12:42:48 -0700769 bool btNrecIsOff = (value == AUDIO_PARAMETER_VALUE_OFF);
770 if (mBtNrecIsOff != btNrecIsOff) {
Eric Laurent59bd0da2011-08-01 09:52:20 -0700771 for (size_t i = 0; i < mRecordThreads.size(); i++) {
772 sp<RecordThread> thread = mRecordThreads.valueAt(i);
773 RecordThread::RecordTrack *track = thread->track();
774 if (track != NULL) {
775 audio_devices_t device = (audio_devices_t)(
776 thread->device() & AUDIO_DEVICE_IN_ALL);
Eric Laurentbee53372011-08-29 12:42:48 -0700777 bool suspend = audio_is_bluetooth_sco_device(device) && btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700778 thread->setEffectSuspended(FX_IID_AEC,
779 suspend,
780 track->sessionId());
781 thread->setEffectSuspended(FX_IID_NS,
782 suspend,
783 track->sessionId());
784 }
785 }
Eric Laurentbee53372011-08-29 12:42:48 -0700786 mBtNrecIsOff = btNrecIsOff;
Eric Laurent59bd0da2011-08-01 09:52:20 -0700787 }
788 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700789 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700790 }
791
792 // hold a strong ref on thread in case closeOutput() or closeInput() is called
793 // and the thread is exited once the lock is released
794 sp<ThreadBase> thread;
795 {
796 Mutex::Autolock _l(mLock);
797 thread = checkPlaybackThread_l(ioHandle);
798 if (thread == NULL) {
799 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700800 } else if (thread.get() == primaryPlaybackThread_l()) {
801 // indicate output device change to all input threads for pre processing
802 AudioParameter param = AudioParameter(keyValuePairs);
803 int value;
804 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
805 for (size_t i = 0; i < mRecordThreads.size(); i++) {
806 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
807 }
808 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 }
810 }
811 if (thread != NULL) {
812 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700813 return result;
814 }
815 return BAD_VALUE;
816}
817
818String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
819{
Steve Block3856b092011-10-20 11:56:00 +0100820// ALOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -0700821// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
822
823 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700824 String8 out_s8;
825
Dima Zavin799a70e2011-04-18 16:57:27 -0700826 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
827 audio_hw_device_t *dev = mAudioHwDevs[i];
828 char *s = dev->get_parameters(dev, keys.string());
829 out_s8 += String8(s);
830 free(s);
831 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700832 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700833 }
834
835 Mutex::Autolock _l(mLock);
836
837 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
838 if (playbackThread != NULL) {
839 return playbackThread->getParameters(keys);
840 }
841 RecordThread *recordThread = checkRecordThread_l(ioHandle);
842 if (recordThread != NULL) {
843 return recordThread->getParameters(keys);
844 }
845 return String8("");
846}
847
848size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
849{
Eric Laurenta1884f92011-08-23 08:25:03 -0700850 status_t ret = initCheck();
851 if (ret != NO_ERROR) {
852 return 0;
853 }
854
Dima Zavin799a70e2011-04-18 16:57:27 -0700855 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700856}
857
858unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
859{
860 if (ioHandle == 0) {
861 return 0;
862 }
863
864 Mutex::Autolock _l(mLock);
865
866 RecordThread *recordThread = checkRecordThread_l(ioHandle);
867 if (recordThread != NULL) {
868 return recordThread->getInputFramesLost();
869 }
870 return 0;
871}
872
873status_t AudioFlinger::setVoiceVolume(float value)
874{
Eric Laurenta1884f92011-08-23 08:25:03 -0700875 status_t ret = initCheck();
876 if (ret != NO_ERROR) {
877 return ret;
878 }
879
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880 // check calling permissions
881 if (!settingsAllowed()) {
882 return PERMISSION_DENIED;
883 }
884
885 AutoMutex lock(mHardwareLock);
886 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Eric Laurenta1884f92011-08-23 08:25:03 -0700887 ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700888 mHardwareStatus = AUDIO_HW_IDLE;
889
890 return ret;
891}
892
893status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
894{
895 status_t status;
896
897 Mutex::Autolock _l(mLock);
898
899 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
900 if (playbackThread != NULL) {
901 return playbackThread->getRenderPosition(halFrames, dspFrames);
902 }
903
904 return BAD_VALUE;
905}
906
907void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
908{
909
910 Mutex::Autolock _l(mLock);
911
912 int pid = IPCThreadState::self()->getCallingPid();
913 if (mNotificationClients.indexOfKey(pid) < 0) {
914 sp<NotificationClient> notificationClient = new NotificationClient(this,
915 client,
916 pid);
Steve Block3856b092011-10-20 11:56:00 +0100917 ALOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700918
919 mNotificationClients.add(pid, notificationClient);
920
921 sp<IBinder> binder = client->asBinder();
922 binder->linkToDeath(notificationClient);
923
924 // the config change is always sent from playback or record threads to avoid deadlock
925 // with AudioSystem::gLock
926 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
927 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
928 }
929
930 for (size_t i = 0; i < mRecordThreads.size(); i++) {
931 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
932 }
933 }
934}
935
936void AudioFlinger::removeNotificationClient(pid_t pid)
937{
938 Mutex::Autolock _l(mLock);
939
940 int index = mNotificationClients.indexOfKey(pid);
941 if (index >= 0) {
942 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
Steve Block3856b092011-10-20 11:56:00 +0100943 ALOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700944 mNotificationClients.removeItem(pid);
945 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700946
Steve Block3856b092011-10-20 11:56:00 +0100947 ALOGV("%d died, releasing its sessions", pid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700948 int num = mAudioSessionRefs.size();
949 bool removed = false;
950 for (int i = 0; i< num; i++) {
951 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
Steve Block3856b092011-10-20 11:56:00 +0100952 ALOGV(" pid %d @ %d", ref->pid, i);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700953 if (ref->pid == pid) {
Steve Block3856b092011-10-20 11:56:00 +0100954 ALOGV(" removing entry for pid %d session %d", pid, ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -0700955 mAudioSessionRefs.removeAt(i);
956 delete ref;
957 removed = true;
958 i--;
959 num--;
960 }
961 }
962 if (removed) {
963 purgeStaleEffects_l();
964 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700965}
966
967// audioConfigChanged_l() must be called with AudioFlinger::mLock held
968void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
969{
970 size_t size = mNotificationClients.size();
971 for (size_t i = 0; i < size; i++) {
972 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
973 }
974}
975
976// removeClient_l() must be called with AudioFlinger::mLock held
977void AudioFlinger::removeClient_l(pid_t pid)
978{
Steve Block3856b092011-10-20 11:56:00 +0100979 ALOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -0700980 mClients.removeItem(pid);
981}
982
983
984// ----------------------------------------------------------------------------
985
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700986AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700987 : Thread(false),
988 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700989 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
990 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700991{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700992 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993}
994
995AudioFlinger::ThreadBase::~ThreadBase()
996{
997 mParamCond.broadcast();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700998 // do not lock the mutex in destructor
999 releaseWakeLock_l();
Eric Laurent9d18ec52011-09-27 12:07:15 -07001000 if (mPowerManager != 0) {
1001 sp<IBinder> binder = mPowerManager->asBinder();
1002 binder->unlinkToDeath(mDeathRecipient);
1003 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001004}
1005
1006void AudioFlinger::ThreadBase::exit()
1007{
Glenn Kasten362c4e62011-12-14 10:28:06 -08001008 // keep a strong ref on ourself so that we won't get
Mathias Agopian65ab4712010-07-14 17:59:35 -07001009 // destroyed in the middle of requestExitAndWait()
1010 sp <ThreadBase> strongMe = this;
1011
Steve Block3856b092011-10-20 11:56:00 +01001012 ALOGV("ThreadBase::exit");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001013 {
1014 AutoMutex lock(&mLock);
1015 mExiting = true;
1016 requestExit();
1017 mWaitWorkCV.signal();
1018 }
1019 requestExitAndWait();
1020}
1021
1022uint32_t AudioFlinger::ThreadBase::sampleRate() const
1023{
1024 return mSampleRate;
1025}
1026
1027int AudioFlinger::ThreadBase::channelCount() const
1028{
1029 return (int)mChannelCount;
1030}
1031
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001032uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -07001033{
1034 return mFormat;
1035}
1036
1037size_t AudioFlinger::ThreadBase::frameCount() const
1038{
1039 return mFrameCount;
1040}
1041
1042status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
1043{
1044 status_t status;
1045
Steve Block3856b092011-10-20 11:56:00 +01001046 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001047 Mutex::Autolock _l(mLock);
1048
1049 mNewParameters.add(keyValuePairs);
1050 mWaitWorkCV.signal();
1051 // wait condition with timeout in case the thread loop has exited
1052 // before the request could be processed
Glenn Kasten7dede872011-12-13 11:04:14 -08001053 if (mParamCond.waitRelative(mLock, kSetParametersTimeoutNs) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 status = mParamStatus;
1055 mWaitWorkCV.signal();
1056 } else {
1057 status = TIMED_OUT;
1058 }
1059 return status;
1060}
1061
1062void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
1063{
1064 Mutex::Autolock _l(mLock);
1065 sendConfigEvent_l(event, param);
1066}
1067
1068// sendConfigEvent_l() must be called with ThreadBase::mLock held
1069void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
1070{
Glenn Kastenf3990f22011-12-13 11:50:00 -08001071 ConfigEvent configEvent;
1072 configEvent.mEvent = event;
1073 configEvent.mParam = param;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001074 mConfigEvents.add(configEvent);
Steve Block3856b092011-10-20 11:56:00 +01001075 ALOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001076 mWaitWorkCV.signal();
1077}
1078
1079void AudioFlinger::ThreadBase::processConfigEvents()
1080{
1081 mLock.lock();
1082 while(!mConfigEvents.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001083 ALOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
Glenn Kastenf3990f22011-12-13 11:50:00 -08001084 ConfigEvent configEvent = mConfigEvents[0];
Mathias Agopian65ab4712010-07-14 17:59:35 -07001085 mConfigEvents.removeAt(0);
1086 // release mLock before locking AudioFlinger mLock: lock order is always
1087 // AudioFlinger then ThreadBase to avoid cross deadlock
1088 mLock.unlock();
1089 mAudioFlinger->mLock.lock();
Glenn Kastenf3990f22011-12-13 11:50:00 -08001090 audioConfigChanged_l(configEvent.mEvent, configEvent.mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001091 mAudioFlinger->mLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001092 mLock.lock();
1093 }
1094 mLock.unlock();
1095}
1096
1097status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
1098{
1099 const size_t SIZE = 256;
1100 char buffer[SIZE];
1101 String8 result;
1102
1103 bool locked = tryLock(mLock);
1104 if (!locked) {
1105 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1106 write(fd, buffer, strlen(buffer));
1107 }
1108
1109 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1110 result.append(buffer);
1111 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1112 result.append(buffer);
1113 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1114 result.append(buffer);
1115 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1116 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001117 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1118 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001119 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1120 result.append(buffer);
1121 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1122 result.append(buffer);
1123
1124 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1125 result.append(buffer);
1126 result.append(" Index Command");
1127 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1128 snprintf(buffer, SIZE, "\n %02d ", i);
1129 result.append(buffer);
1130 result.append(mNewParameters[i]);
1131 }
1132
1133 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1134 result.append(buffer);
1135 snprintf(buffer, SIZE, " Index event param\n");
1136 result.append(buffer);
1137 for (size_t i = 0; i < mConfigEvents.size(); i++) {
Glenn Kastenf3990f22011-12-13 11:50:00 -08001138 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i].mEvent, mConfigEvents[i].mParam);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001139 result.append(buffer);
1140 }
1141 result.append("\n");
1142
1143 write(fd, result.string(), result.size());
1144
1145 if (locked) {
1146 mLock.unlock();
1147 }
1148 return NO_ERROR;
1149}
1150
Eric Laurent1d2bff02011-07-24 17:49:51 -07001151status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1152{
1153 const size_t SIZE = 256;
1154 char buffer[SIZE];
1155 String8 result;
1156
1157 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1158 write(fd, buffer, strlen(buffer));
1159
1160 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1161 sp<EffectChain> chain = mEffectChains[i];
1162 if (chain != 0) {
1163 chain->dump(fd, args);
1164 }
1165 }
1166 return NO_ERROR;
1167}
1168
Eric Laurentfeb0db62011-07-22 09:04:31 -07001169void AudioFlinger::ThreadBase::acquireWakeLock()
1170{
1171 Mutex::Autolock _l(mLock);
1172 acquireWakeLock_l();
1173}
1174
1175void AudioFlinger::ThreadBase::acquireWakeLock_l()
1176{
1177 if (mPowerManager == 0) {
1178 // use checkService() to avoid blocking if power service is not up yet
1179 sp<IBinder> binder =
1180 defaultServiceManager()->checkService(String16("power"));
1181 if (binder == 0) {
1182 LOGW("Thread %s cannot connect to the power manager service", mName);
1183 } else {
1184 mPowerManager = interface_cast<IPowerManager>(binder);
1185 binder->linkToDeath(mDeathRecipient);
1186 }
1187 }
1188 if (mPowerManager != 0) {
1189 sp<IBinder> binder = new BBinder();
1190 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1191 binder,
1192 String16(mName));
1193 if (status == NO_ERROR) {
1194 mWakeLockToken = binder;
1195 }
Steve Block3856b092011-10-20 11:56:00 +01001196 ALOGV("acquireWakeLock_l() %s status %d", mName, status);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001197 }
1198}
1199
1200void AudioFlinger::ThreadBase::releaseWakeLock()
1201{
1202 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001203 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001204}
1205
1206void AudioFlinger::ThreadBase::releaseWakeLock_l()
1207{
1208 if (mWakeLockToken != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001209 ALOGV("releaseWakeLock_l() %s", mName);
Eric Laurentfeb0db62011-07-22 09:04:31 -07001210 if (mPowerManager != 0) {
1211 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1212 }
1213 mWakeLockToken.clear();
1214 }
1215}
1216
1217void AudioFlinger::ThreadBase::clearPowerManager()
1218{
1219 Mutex::Autolock _l(mLock);
1220 releaseWakeLock_l();
1221 mPowerManager.clear();
1222}
1223
1224void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1225{
1226 sp<ThreadBase> thread = mThread.promote();
1227 if (thread != 0) {
1228 thread->clearPowerManager();
1229 }
1230 LOGW("power manager service died !!!");
1231}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001232
Eric Laurent59255e42011-07-27 19:49:51 -07001233void AudioFlinger::ThreadBase::setEffectSuspended(
1234 const effect_uuid_t *type, bool suspend, int sessionId)
1235{
1236 Mutex::Autolock _l(mLock);
1237 setEffectSuspended_l(type, suspend, sessionId);
1238}
1239
1240void AudioFlinger::ThreadBase::setEffectSuspended_l(
1241 const effect_uuid_t *type, bool suspend, int sessionId)
1242{
1243 sp<EffectChain> chain;
1244 chain = getEffectChain_l(sessionId);
1245 if (chain != 0) {
1246 if (type != NULL) {
1247 chain->setEffectSuspended_l(type, suspend);
1248 } else {
1249 chain->setEffectSuspendedAll_l(suspend);
1250 }
1251 }
1252
1253 updateSuspendedSessions_l(type, suspend, sessionId);
1254}
1255
1256void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1257{
1258 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1259 if (index < 0) {
1260 return;
1261 }
1262
1263 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1264 mSuspendedSessions.editValueAt(index);
1265
1266 for (size_t i = 0; i < sessionEffects.size(); i++) {
1267 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1268 for (int j = 0; j < desc->mRefCount; j++) {
1269 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1270 chain->setEffectSuspendedAll_l(true);
1271 } else {
Steve Block3856b092011-10-20 11:56:00 +01001272 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07001273 desc->mType.timeLow);
1274 chain->setEffectSuspended_l(&desc->mType, true);
1275 }
1276 }
1277 }
1278}
1279
Eric Laurent59255e42011-07-27 19:49:51 -07001280void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1281 bool suspend,
1282 int sessionId)
1283{
1284 int index = mSuspendedSessions.indexOfKey(sessionId);
1285
1286 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1287
1288 if (suspend) {
1289 if (index >= 0) {
1290 sessionEffects = mSuspendedSessions.editValueAt(index);
1291 } else {
1292 mSuspendedSessions.add(sessionId, sessionEffects);
1293 }
1294 } else {
1295 if (index < 0) {
1296 return;
1297 }
1298 sessionEffects = mSuspendedSessions.editValueAt(index);
1299 }
1300
1301
1302 int key = EffectChain::kKeyForSuspendAll;
1303 if (type != NULL) {
1304 key = type->timeLow;
1305 }
1306 index = sessionEffects.indexOfKey(key);
1307
1308 sp <SuspendedSessionDesc> desc;
1309 if (suspend) {
1310 if (index >= 0) {
1311 desc = sessionEffects.valueAt(index);
1312 } else {
1313 desc = new SuspendedSessionDesc();
1314 if (type != NULL) {
1315 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1316 }
1317 sessionEffects.add(key, desc);
Steve Block3856b092011-10-20 11:56:00 +01001318 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001319 }
1320 desc->mRefCount++;
1321 } else {
1322 if (index < 0) {
1323 return;
1324 }
1325 desc = sessionEffects.valueAt(index);
1326 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01001327 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
Eric Laurent59255e42011-07-27 19:49:51 -07001328 sessionEffects.removeItemsAt(index);
1329 if (sessionEffects.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01001330 ALOGV("updateSuspendedSessions_l() restore removing session %d",
Eric Laurent59255e42011-07-27 19:49:51 -07001331 sessionId);
1332 mSuspendedSessions.removeItem(sessionId);
1333 }
1334 }
1335 }
1336 if (!sessionEffects.isEmpty()) {
1337 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1338 }
1339}
1340
1341void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1342 bool enabled,
1343 int sessionId)
1344{
1345 Mutex::Autolock _l(mLock);
Eric Laurenta85a74a2011-10-19 11:44:54 -07001346 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1347}
Eric Laurent59255e42011-07-27 19:49:51 -07001348
Eric Laurenta85a74a2011-10-19 11:44:54 -07001349void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1350 bool enabled,
1351 int sessionId)
1352{
Eric Laurentdb7c0792011-08-10 10:37:50 -07001353 if (mType != RECORD) {
1354 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1355 // another session. This gives the priority to well behaved effect control panels
1356 // and applications not using global effects.
1357 if (sessionId != AUDIO_SESSION_OUTPUT_MIX) {
1358 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1359 }
1360 }
Eric Laurent59255e42011-07-27 19:49:51 -07001361
1362 sp<EffectChain> chain = getEffectChain_l(sessionId);
1363 if (chain != 0) {
1364 chain->checkSuspendOnEffectEnabled(effect, enabled);
1365 }
1366}
1367
Mathias Agopian65ab4712010-07-14 17:59:35 -07001368// ----------------------------------------------------------------------------
1369
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001370AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1371 AudioStreamOut* output,
1372 int id,
1373 uint32_t device)
1374 : ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001375 mMixBuffer(NULL), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001376 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001377{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001378 snprintf(mName, kNameLength, "AudioOut_%d", id);
1379
Mathias Agopian65ab4712010-07-14 17:59:35 -07001380 readOutputParameters();
1381
1382 mMasterVolume = mAudioFlinger->masterVolume();
1383 mMasterMute = mAudioFlinger->masterMute();
1384
Dima Zavinfce7a472011-04-19 22:30:36 -07001385 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001386 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1387 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
Eric Laurent9f6530f2011-08-30 10:18:54 -07001388 mStreamTypes[stream].valid = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001389 }
1390}
1391
1392AudioFlinger::PlaybackThread::~PlaybackThread()
1393{
1394 delete [] mMixBuffer;
1395}
1396
1397status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1398{
1399 dumpInternals(fd, args);
1400 dumpTracks(fd, args);
1401 dumpEffectChains(fd, args);
1402 return NO_ERROR;
1403}
1404
1405status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1406{
1407 const size_t SIZE = 256;
1408 char buffer[SIZE];
1409 String8 result;
1410
1411 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1412 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001413 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 -07001414 for (size_t i = 0; i < mTracks.size(); ++i) {
1415 sp<Track> track = mTracks[i];
1416 if (track != 0) {
1417 track->dump(buffer, SIZE);
1418 result.append(buffer);
1419 }
1420 }
1421
1422 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1423 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001424 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 -07001425 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1426 wp<Track> wTrack = mActiveTracks[i];
1427 if (wTrack != 0) {
1428 sp<Track> track = wTrack.promote();
1429 if (track != 0) {
1430 track->dump(buffer, SIZE);
1431 result.append(buffer);
1432 }
1433 }
1434 }
1435 write(fd, result.string(), result.size());
1436 return NO_ERROR;
1437}
1438
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1440{
1441 const size_t SIZE = 256;
1442 char buffer[SIZE];
1443 String8 result;
1444
1445 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1446 result.append(buffer);
1447 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1448 result.append(buffer);
1449 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1450 result.append(buffer);
1451 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1452 result.append(buffer);
1453 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1454 result.append(buffer);
1455 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1456 result.append(buffer);
1457 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1458 result.append(buffer);
1459 write(fd, result.string(), result.size());
1460
1461 dumpBase(fd, args);
1462
1463 return NO_ERROR;
1464}
1465
1466// Thread virtuals
1467status_t AudioFlinger::PlaybackThread::readyToRun()
1468{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001469 status_t status = initCheck();
1470 if (status == NO_ERROR) {
1471 LOGI("AudioFlinger's thread %p ready to run", this);
1472 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001473 LOGE("No working audio driver found.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001474 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001475 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476}
1477
1478void AudioFlinger::PlaybackThread::onFirstRef()
1479{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001480 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001481}
1482
1483// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1484sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1485 const sp<AudioFlinger::Client>& client,
1486 int streamType,
1487 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001488 uint32_t format,
1489 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001490 int frameCount,
1491 const sp<IMemory>& sharedBuffer,
1492 int sessionId,
1493 status_t *status)
1494{
1495 sp<Track> track;
1496 status_t lStatus;
1497
1498 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001499 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1500 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1501 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1502 "for output %p with format %d",
1503 sampleRate, format, channelMask, mOutput, mFormat);
1504 lStatus = BAD_VALUE;
1505 goto Exit;
1506 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 }
1508 } else {
1509 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1510 if (sampleRate > mSampleRate*2) {
1511 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1512 lStatus = BAD_VALUE;
1513 goto Exit;
1514 }
1515 }
1516
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001517 lStatus = initCheck();
1518 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001519 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001520 goto Exit;
1521 }
1522
1523 { // scope for mLock
1524 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001525
1526 // all tracks in same audio session must share the same routing strategy otherwise
1527 // conflicts will happen when tracks are moved from one output to another by audio policy
1528 // manager
1529 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001530 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001531 for (size_t i = 0; i < mTracks.size(); ++i) {
1532 sp<Track> t = mTracks[i];
1533 if (t != 0) {
Glenn Kastend8796012011-10-28 10:31:42 -07001534 uint32_t actual = AudioSystem::getStrategyForStream((audio_stream_type_t)t->type());
1535 if (sessionId == t->sessionId() && strategy != actual) {
1536 LOGE("createTrack_l() mismatched strategy; expected %u but found %u",
1537 strategy, actual);
Eric Laurentde070132010-07-13 04:45:46 -07001538 lStatus = BAD_VALUE;
1539 goto Exit;
1540 }
1541 }
1542 }
1543
Mathias Agopian65ab4712010-07-14 17:59:35 -07001544 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001545 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001546 if (track->getCblk() == NULL || track->name() < 0) {
1547 lStatus = NO_MEMORY;
1548 goto Exit;
1549 }
1550 mTracks.add(track);
1551
1552 sp<EffectChain> chain = getEffectChain_l(sessionId);
1553 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001554 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001555 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001556 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001557 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001558 }
Eric Laurent9f6530f2011-08-30 10:18:54 -07001559
1560 // invalidate track immediately if the stream type was moved to another thread since
1561 // createTrack() was called by the client process.
1562 if (!mStreamTypes[streamType].valid) {
1563 LOGW("createTrack_l() on thread %p: invalidating track on stream %d",
1564 this, streamType);
1565 android_atomic_or(CBLK_INVALID_ON, &track->mCblk->flags);
1566 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567 }
1568 lStatus = NO_ERROR;
1569
1570Exit:
1571 if(status) {
1572 *status = lStatus;
1573 }
1574 return track;
1575}
1576
1577uint32_t AudioFlinger::PlaybackThread::latency() const
1578{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001579 Mutex::Autolock _l(mLock);
1580 if (initCheck() == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001581 return mOutput->stream->get_latency(mOutput->stream);
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001582 } else {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001583 return 0;
1584 }
1585}
1586
1587status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1588{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001589 mMasterVolume = value;
1590 return NO_ERROR;
1591}
1592
1593status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1594{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001595 mMasterMute = muted;
1596 return NO_ERROR;
1597}
1598
1599float AudioFlinger::PlaybackThread::masterVolume() const
1600{
1601 return mMasterVolume;
1602}
1603
1604bool AudioFlinger::PlaybackThread::masterMute() const
1605{
1606 return mMasterMute;
1607}
1608
1609status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1610{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001611 mStreamTypes[stream].volume = value;
1612 return NO_ERROR;
1613}
1614
1615status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1616{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001617 mStreamTypes[stream].mute = muted;
1618 return NO_ERROR;
1619}
1620
1621float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1622{
1623 return mStreamTypes[stream].volume;
1624}
1625
1626bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1627{
1628 return mStreamTypes[stream].mute;
1629}
1630
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631// addTrack_l() must be called with ThreadBase::mLock held
1632status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1633{
1634 status_t status = ALREADY_EXISTS;
1635
1636 // set retry count for buffer fill
1637 track->mRetryCount = kMaxTrackStartupRetries;
1638 if (mActiveTracks.indexOf(track) < 0) {
1639 // the track is newly added, make sure it fills up all its
1640 // buffers before playing. This is to ensure the client will
1641 // effectively get the latency it requested.
1642 track->mFillingUpStatus = Track::FS_FILLING;
1643 track->mResetDone = false;
1644 mActiveTracks.add(track);
1645 if (track->mainBuffer() != mMixBuffer) {
1646 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1647 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01001648 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001649 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 }
1651 }
1652
1653 status = NO_ERROR;
1654 }
1655
Steve Block3856b092011-10-20 11:56:00 +01001656 ALOGV("mWaitWorkCV.broadcast");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001657 mWaitWorkCV.broadcast();
1658
1659 return status;
1660}
1661
1662// destroyTrack_l() must be called with ThreadBase::mLock held
1663void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1664{
1665 track->mState = TrackBase::TERMINATED;
1666 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001667 removeTrack_l(track);
1668 }
1669}
1670
1671void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1672{
1673 mTracks.remove(track);
1674 deleteTrackName_l(track->name());
1675 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1676 if (chain != 0) {
1677 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 }
1679}
1680
1681String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1682{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001683 String8 out_s8 = String8("");
Dima Zavinfce7a472011-04-19 22:30:36 -07001684 char *s;
1685
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001686 Mutex::Autolock _l(mLock);
1687 if (initCheck() != NO_ERROR) {
1688 return out_s8;
1689 }
1690
Dima Zavin799a70e2011-04-18 16:57:27 -07001691 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001692 out_s8 = String8(s);
1693 free(s);
1694 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001695}
1696
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001697// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Mathias Agopian65ab4712010-07-14 17:59:35 -07001698void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1699 AudioSystem::OutputDescriptor desc;
1700 void *param2 = 0;
1701
Steve Block3856b092011-10-20 11:56:00 +01001702 ALOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001703
1704 switch (event) {
1705 case AudioSystem::OUTPUT_OPENED:
1706 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001707 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001708 desc.samplingRate = mSampleRate;
1709 desc.format = mFormat;
1710 desc.frameCount = mFrameCount;
1711 desc.latency = latency();
1712 param2 = &desc;
1713 break;
1714
1715 case AudioSystem::STREAM_CONFIG_CHANGED:
1716 param2 = &param;
1717 case AudioSystem::OUTPUT_CLOSED:
1718 default:
1719 break;
1720 }
1721 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1722}
1723
1724void AudioFlinger::PlaybackThread::readOutputParameters()
1725{
Dima Zavin799a70e2011-04-18 16:57:27 -07001726 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001727 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1728 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001729 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1730 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1731 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001732
1733 // FIXME - Current mixer implementation only supports stereo output: Always
1734 // Allocate a stereo buffer even if HW output is mono.
1735 if (mMixBuffer != NULL) delete[] mMixBuffer;
1736 mMixBuffer = new int16_t[mFrameCount * 2];
1737 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1738
Eric Laurentde070132010-07-13 04:45:46 -07001739 // force reconfiguration of effect chains and engines to take new buffer size and audio
1740 // parameters into account
1741 // Note that mLock is not held when readOutputParameters() is called from the constructor
1742 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1743 // matter.
1744 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1745 Vector< sp<EffectChain> > effectChains = mEffectChains;
1746 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001747 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001748 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749}
1750
1751status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1752{
1753 if (halFrames == 0 || dspFrames == 0) {
1754 return BAD_VALUE;
1755 }
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001756 Mutex::Autolock _l(mLock);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001757 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001758 return INVALID_OPERATION;
1759 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001760 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761
Dima Zavin799a70e2011-04-18 16:57:27 -07001762 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763}
1764
Eric Laurent39e94f82010-07-28 01:32:47 -07001765uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766{
1767 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001768 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001769 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001770 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 }
1772
1773 for (size_t i = 0; i < mTracks.size(); ++i) {
1774 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001775 if (sessionId == track->sessionId() &&
1776 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001777 result |= TRACK_SESSION;
1778 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 }
1780 }
1781
Eric Laurent39e94f82010-07-28 01:32:47 -07001782 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001783}
1784
Eric Laurentde070132010-07-13 04:45:46 -07001785uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1786{
Dima Zavinfce7a472011-04-19 22:30:36 -07001787 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001788 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001789 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1790 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001791 }
1792 for (size_t i = 0; i < mTracks.size(); i++) {
1793 sp<Track> track = mTracks[i];
1794 if (sessionId == track->sessionId() &&
1795 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001796 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001797 }
1798 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001799 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001800}
1801
Mathias Agopian65ab4712010-07-14 17:59:35 -07001802
Eric Laurentb8ba0a92011-08-07 16:32:26 -07001803AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::getOutput()
1804{
1805 Mutex::Autolock _l(mLock);
1806 return mOutput;
1807}
1808
1809AudioFlinger::AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
1810{
1811 Mutex::Autolock _l(mLock);
1812 AudioStreamOut *output = mOutput;
1813 mOutput = NULL;
1814 return output;
1815}
1816
1817// this method must always be called either with ThreadBase mLock held or inside the thread loop
1818audio_stream_t* AudioFlinger::PlaybackThread::stream()
1819{
1820 if (mOutput == NULL) {
1821 return NULL;
1822 }
1823 return &mOutput->stream->common;
1824}
1825
Eric Laurent162b40b2011-12-05 09:47:19 -08001826uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs()
1827{
1828 // A2DP output latency is not due only to buffering capacity. It also reflects encoding,
1829 // decoding and transfer time. So sleeping for half of the latency would likely cause
1830 // underruns
1831 if (audio_is_a2dp_device((audio_devices_t)mDevice)) {
1832 return (uint32_t)((uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000);
1833 } else {
1834 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
1835 }
1836}
1837
Mathias Agopian65ab4712010-07-14 17:59:35 -07001838// ----------------------------------------------------------------------------
1839
Dima Zavin799a70e2011-04-18 16:57:27 -07001840AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001841 : PlaybackThread(audioFlinger, output, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08001842 mAudioMixer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001843{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001844 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1846
1847 // FIXME - Current mixer implementation only supports stereo output
1848 if (mChannelCount == 1) {
1849 LOGE("Invalid audio hardware channel count");
1850 }
1851}
1852
1853AudioFlinger::MixerThread::~MixerThread()
1854{
1855 delete mAudioMixer;
1856}
1857
1858bool AudioFlinger::MixerThread::threadLoop()
1859{
1860 Vector< sp<Track> > tracksToRemove;
1861 uint32_t mixerStatus = MIXER_IDLE;
1862 nsecs_t standbyTime = systemTime();
1863 size_t mixBufferSize = mFrameCount * mFrameSize;
1864 // FIXME: Relaxed timing because of a certain device that can't meet latency
1865 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001866 // increase threshold again due to low power audio mode. The way this warning threshold is
1867 // calculated and its usefulness should be reconsidered anyway.
1868 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001869 nsecs_t lastWarning = 0;
1870 bool longStandbyExit = false;
1871 uint32_t activeSleepTime = activeSleepTimeUs();
1872 uint32_t idleSleepTime = idleSleepTimeUs();
1873 uint32_t sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001874 uint32_t sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001875 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001876#ifdef DEBUG_CPU_USAGE
1877 ThreadCpuUsage cpu;
1878 const CentralTendencyStatistics& stats = cpu.statistics();
1879#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880
Eric Laurentfeb0db62011-07-22 09:04:31 -07001881 acquireWakeLock();
1882
Mathias Agopian65ab4712010-07-14 17:59:35 -07001883 while (!exitPending())
1884 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001885#ifdef DEBUG_CPU_USAGE
1886 cpu.sampleAndEnable();
1887 unsigned n = stats.n();
1888 // cpu.elapsed() is expensive, so don't call it every loop
1889 if ((n & 127) == 1) {
1890 long long elapsed = cpu.elapsed();
1891 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1892 double perLoop = elapsed / (double) n;
1893 double perLoop100 = perLoop * 0.01;
1894 double mean = stats.mean();
1895 double stddev = stats.stddev();
1896 double minimum = stats.minimum();
1897 double maximum = stats.maximum();
1898 cpu.resetStatistics();
1899 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",
1900 elapsed * .000000001, n, perLoop * .000001,
1901 mean * .001,
1902 stddev * .001,
1903 minimum * .001,
1904 maximum * .001,
1905 mean / perLoop100,
1906 stddev / perLoop100,
1907 minimum / perLoop100,
1908 maximum / perLoop100);
1909 }
1910 }
1911#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001912 processConfigEvents();
1913
1914 mixerStatus = MIXER_IDLE;
1915 { // scope for mLock
1916
1917 Mutex::Autolock _l(mLock);
1918
1919 if (checkForNewParameters_l()) {
1920 mixBufferSize = mFrameCount * mFrameSize;
1921 // FIXME: Relaxed timing because of a certain device that can't meet latency
1922 // Should be reduced to 2x after the vendor fixes the driver issue
Eric Laurent5c4e8182011-10-18 15:42:27 -07001923 // increase threshold again due to low power audio mode. The way this warning
1924 // threshold is calculated and its usefulness should be reconsidered anyway.
1925 maxPeriod = seconds(mFrameCount) / mSampleRate * 15;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001926 activeSleepTime = activeSleepTimeUs();
1927 idleSleepTime = idleSleepTimeUs();
1928 }
1929
1930 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1931
1932 // put audio hardware into standby after short delay
1933 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1934 mSuspended) {
1935 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01001936 ALOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001937 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001938 mStandby = true;
1939 mBytesWritten = 0;
1940 }
1941
1942 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1943 // we're about to wait, flush the binder command buffer
1944 IPCThreadState::self()->flushCommands();
1945
1946 if (exitPending()) break;
1947
Eric Laurentfeb0db62011-07-22 09:04:31 -07001948 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001949 // wait until we have something to do...
Steve Block3856b092011-10-20 11:56:00 +01001950 ALOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001951 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01001952 ALOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001953 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001954
1955 if (mMasterMute == false) {
1956 char value[PROPERTY_VALUE_MAX];
1957 property_get("ro.audio.silent", value, "0");
1958 if (atoi(value)) {
1959 LOGD("Silence is golden");
1960 setMasterMute(true);
1961 }
1962 }
1963
1964 standbyTime = systemTime() + kStandbyTimeInNsecs;
1965 sleepTime = idleSleepTime;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001966 sleepTimeShift = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 continue;
1968 }
1969 }
1970
1971 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1972
1973 // prevent any changes in effect chain list and in each effect chain
1974 // during mixing and effect process as the audio buffers could be deleted
1975 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001976 lockEffectChains_l(effectChains);
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08001977 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978
1979 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1980 // mix buffers...
1981 mAudioMixer->process();
1982 sleepTime = 0;
Eric Laurent7cafbb32011-11-22 18:50:29 -08001983 // increase sleep time progressively when application underrun condition clears
1984 if (sleepTimeShift > 0) {
1985 sleepTimeShift--;
1986 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001987 standbyTime = systemTime() + kStandbyTimeInNsecs;
1988 //TODO: delay standby when effects have a tail
1989 } else {
1990 // If no tracks are ready, sleep once for the duration of an output
1991 // buffer size, then write 0s to the output
1992 if (sleepTime == 0) {
1993 if (mixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurent7cafbb32011-11-22 18:50:29 -08001994 sleepTime = activeSleepTime >> sleepTimeShift;
1995 if (sleepTime < kMinThreadSleepTimeUs) {
1996 sleepTime = kMinThreadSleepTimeUs;
1997 }
1998 // reduce sleep time in case of consecutive application underruns to avoid
1999 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
2000 // duration we would end up writing less data than needed by the audio HAL if
2001 // the condition persists.
2002 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
2003 sleepTimeShift++;
2004 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005 } else {
2006 sleepTime = idleSleepTime;
2007 }
2008 } else if (mBytesWritten != 0 ||
2009 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
2010 memset (mMixBuffer, 0, mixBufferSize);
2011 sleepTime = 0;
Steve Block3856b092011-10-20 11:56:00 +01002012 ALOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07002013 }
2014 // TODO add standby time extension fct of effect tail
2015 }
2016
2017 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002018 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002019 }
2020 // sleepTime == 0 means we must write to audio hardware
2021 if (sleepTime == 0) {
Glenn Kastenc5ac4cb2011-12-12 09:05:55 -08002022 for (size_t i = 0; i < effectChains.size(); i ++) {
2023 effectChains[i]->process_l();
2024 }
2025 // enable changes in effect chain
2026 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002027 mLastWriteTime = systemTime();
2028 mInWrite = true;
2029 mBytesWritten += mixBufferSize;
2030
Dima Zavin799a70e2011-04-18 16:57:27 -07002031 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2033 mNumWrites++;
2034 mInWrite = false;
2035 nsecs_t now = systemTime();
2036 nsecs_t delta = now - mLastWriteTime;
Eric Laurent5c4e8182011-10-18 15:42:27 -07002037 if (!mStandby && delta > maxPeriod) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002038 mNumDelayedWrites++;
Glenn Kasten7dede872011-12-13 11:04:14 -08002039 if ((now - lastWarning) > kWarningThrottleNs) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002040 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
2041 ns2ms(delta), mNumDelayedWrites, this);
2042 lastWarning = now;
2043 }
2044 if (mStandby) {
2045 longStandbyExit = true;
2046 }
2047 }
2048 mStandby = false;
2049 } else {
2050 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002051 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002052 usleep(sleepTime);
2053 }
2054
2055 // finally let go of all our tracks, without the lock held
2056 // since we can't guarantee the destructors won't acquire that
2057 // same lock.
2058 tracksToRemove.clear();
2059
2060 // Effect chains will be actually deleted here if they were removed from
2061 // mEffectChains list during mixing or effects processing
2062 effectChains.clear();
2063 }
2064
2065 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002066 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002067 }
2068
Eric Laurentfeb0db62011-07-22 09:04:31 -07002069 releaseWakeLock();
2070
Steve Block3856b092011-10-20 11:56:00 +01002071 ALOGV("MixerThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002072 return false;
2073}
2074
2075// prepareTracks_l() must be called with ThreadBase::mLock held
2076uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
2077{
2078
2079 uint32_t mixerStatus = MIXER_IDLE;
2080 // find out which tracks need to be processed
2081 size_t count = activeTracks.size();
2082 size_t mixedTracks = 0;
2083 size_t tracksWithEffect = 0;
2084
2085 float masterVolume = mMasterVolume;
2086 bool masterMute = mMasterMute;
2087
Eric Laurent571d49c2010-08-11 05:20:11 -07002088 if (masterMute) {
2089 masterVolume = 0;
2090 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07002091 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07002092 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002093 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07002094 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07002095 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002096 masterVolume = (float)((v + (1 << 23)) >> 24);
2097 chain.clear();
2098 }
2099
2100 for (size_t i=0 ; i<count ; i++) {
2101 sp<Track> t = activeTracks[i].promote();
2102 if (t == 0) continue;
2103
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002104 // this const just means the local variable doesn't change
Mathias Agopian65ab4712010-07-14 17:59:35 -07002105 Track* const track = t.get();
2106 audio_track_cblk_t* cblk = track->cblk();
2107
2108 // The first time a track is added we wait
2109 // for all its buffers to be filled before processing it
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002110 int name = track->name();
Eric Laurenta47b69c2011-11-08 18:10:16 -08002111 // make sure that we have enough frames to mix one full buffer.
2112 // enforce this condition only once to enable draining the buffer in case the client
2113 // app does not call stop() and relies on underrun to stop:
2114 // hence the test on (track->mRetryCount >= kMaxTrackRetries) meaning the track was mixed
2115 // during last round
Eric Laurent3dbe3202011-11-03 12:16:05 -07002116 uint32_t minFrames = 1;
Eric Laurenta47b69c2011-11-08 18:10:16 -08002117 if (!track->isStopped() && !track->isPausing() &&
2118 (track->mRetryCount >= kMaxTrackRetries)) {
Eric Laurent3dbe3202011-11-03 12:16:05 -07002119 if (t->sampleRate() == (int)mSampleRate) {
2120 minFrames = mFrameCount;
2121 } else {
2122 minFrames = (mFrameCount * t->sampleRate()) / mSampleRate + 1;
2123 }
2124 }
2125 if ((cblk->framesReady() >= minFrames) && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002126 !track->isPaused() && !track->isTerminated())
2127 {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002128 //ALOGV("track %d u=%08x, s=%08x [OK] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002129
2130 mixedTracks++;
2131
2132 // track->mainBuffer() != mMixBuffer means there is an effect chain
2133 // connected to the track
2134 chain.clear();
2135 if (track->mainBuffer() != mMixBuffer) {
2136 chain = getEffectChain_l(track->sessionId());
2137 // Delegate volume control to effect in track effect chain if needed
2138 if (chain != 0) {
2139 tracksWithEffect++;
2140 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002141 LOGW("prepareTracks_l(): track %d attached to effect but no chain found on session %d",
2142 name, track->sessionId());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002143 }
2144 }
2145
2146
2147 int param = AudioMixer::VOLUME;
2148 if (track->mFillingUpStatus == Track::FS_FILLED) {
2149 // no ramp for the first volume setting
2150 track->mFillingUpStatus = Track::FS_ACTIVE;
2151 if (track->mState == TrackBase::RESUMING) {
2152 track->mState = TrackBase::ACTIVE;
2153 param = AudioMixer::RAMP_VOLUME;
2154 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002155 mAudioMixer->setParameter(name, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002156 } else if (cblk->server != 0) {
2157 // If the track is stopped before the first frame was mixed,
2158 // do not apply ramp
2159 param = AudioMixer::RAMP_VOLUME;
2160 }
2161
2162 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07002163 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07002164 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07002165 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002166 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 if (track->isPausing()) {
2168 track->setPaused();
2169 }
2170 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002171
Mathias Agopian65ab4712010-07-14 17:59:35 -07002172 // read original volumes with volume control
2173 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002174 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07002175 vl = (uint32_t)(v * cblk->volume[0]) << 12;
2176 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002177
Eric Laurente0aed6d2010-09-10 17:44:44 -07002178 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002179 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07002180 // Delegate volume control to effect in track effect chain if needed
2181 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
2182 // Do not ramp volume if volume is controlled by effect
2183 param = AudioMixer::VOLUME;
2184 track->mHasVolumeController = true;
2185 } else {
2186 // force no volume ramp when volume controller was just disabled or removed
2187 // from effect chain to avoid volume spike
2188 if (track->mHasVolumeController) {
2189 param = AudioMixer::VOLUME;
2190 }
2191 track->mHasVolumeController = false;
2192 }
2193
2194 // Convert volumes from 8.24 to 4.12 format
2195 int16_t left, right, aux;
2196 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2197 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2198 left = int16_t(v_clamped);
2199 v_clamped = (vr + (1 << 11)) >> 12;
2200 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2201 right = int16_t(v_clamped);
2202
2203 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2204 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205
Mathias Agopian65ab4712010-07-14 17:59:35 -07002206 // XXX: these things DON'T need to be done each time
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002207 mAudioMixer->setBufferProvider(name, track);
2208 mAudioMixer->enable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002209
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002210 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME0, (void *)left);
2211 mAudioMixer->setParameter(name, param, AudioMixer::VOLUME1, (void *)right);
2212 mAudioMixer->setParameter(name, param, AudioMixer::AUXLEVEL, (void *)aux);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002213 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002214 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002215 AudioMixer::TRACK,
2216 AudioMixer::FORMAT, (void *)track->format());
2217 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002218 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002219 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002220 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002221 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002222 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002223 AudioMixer::RESAMPLE,
2224 AudioMixer::SAMPLE_RATE,
2225 (void *)(cblk->sampleRate));
2226 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002227 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002228 AudioMixer::TRACK,
2229 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2230 mAudioMixer->setParameter(
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002231 name,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002232 AudioMixer::TRACK,
2233 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2234
2235 // reset retry count
2236 track->mRetryCount = kMaxTrackRetries;
2237 mixerStatus = MIXER_TRACKS_READY;
2238 } else {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002239 //ALOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", name, cblk->user, cblk->server, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002240 if (track->isStopped()) {
2241 track->reset();
2242 }
2243 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2244 // We have consumed all the buffers of this track.
2245 // Remove it from the list of active tracks.
2246 tracksToRemove->add(track);
2247 } else {
2248 // No buffers for this track. Give it a few chances to
2249 // fill a buffer, then remove it from active list.
2250 if (--(track->mRetryCount) <= 0) {
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002251 ALOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", name, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002252 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002253 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002254 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002255 } else if (mixerStatus != MIXER_TRACKS_READY) {
2256 mixerStatus = MIXER_TRACKS_ENABLED;
2257 }
2258 }
Glenn Kasten9c56d4a2011-12-19 15:06:39 -08002259 mAudioMixer->disable(name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002260 }
2261 }
2262
2263 // remove all the tracks that need to be...
2264 count = tracksToRemove->size();
2265 if (UNLIKELY(count)) {
2266 for (size_t i=0 ; i<count ; i++) {
2267 const sp<Track>& track = tracksToRemove->itemAt(i);
2268 mActiveTracks.remove(track);
2269 if (track->mainBuffer() != mMixBuffer) {
2270 chain = getEffectChain_l(track->sessionId());
2271 if (chain != 0) {
Steve Block3856b092011-10-20 11:56:00 +01002272 ALOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002273 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002274 }
2275 }
2276 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002277 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002278 }
2279 }
2280 }
2281
2282 // mix buffer must be cleared if all tracks are connected to an
2283 // effect chain as in this case the mixer will not write to
2284 // mix buffer and track effects will accumulate into it
2285 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2286 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2287 }
2288
2289 return mixerStatus;
2290}
2291
2292void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2293{
Steve Block3856b092011-10-20 11:56:00 +01002294 ALOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
Eric Laurentde070132010-07-13 04:45:46 -07002295 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002296 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002297
Mathias Agopian65ab4712010-07-14 17:59:35 -07002298 size_t size = mTracks.size();
2299 for (size_t i = 0; i < size; i++) {
2300 sp<Track> t = mTracks[i];
2301 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002302 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002303 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304 }
2305 }
2306}
2307
Eric Laurent9f6530f2011-08-30 10:18:54 -07002308void AudioFlinger::PlaybackThread::setStreamValid(int streamType, bool valid)
2309{
Steve Block3856b092011-10-20 11:56:00 +01002310 ALOGV ("PlaybackThread::setStreamValid() thread %p, streamType %d, valid %d",
Eric Laurent9f6530f2011-08-30 10:18:54 -07002311 this, streamType, valid);
2312 Mutex::Autolock _l(mLock);
2313
2314 mStreamTypes[streamType].valid = valid;
2315}
Mathias Agopian65ab4712010-07-14 17:59:35 -07002316
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{
Steve Block3856b092011-10-20 11:56:00 +01002326 ALOGV("remove track (%d) and delete from mixer", name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002327 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
Glenn Kasten362c4e62011-12-14 10:28:06 -08002360 // size depends on frame count and correct behavior would not be guaranteed
Mathias Agopian65ab4712010-07-14 17:59:35 -07002361 // 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();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002429 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2430 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002431 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002432 }
2433 return reconfig;
2434}
2435
2436status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2437{
2438 const size_t SIZE = 256;
2439 char buffer[SIZE];
2440 String8 result;
2441
2442 PlaybackThread::dumpInternals(fd, args);
2443
2444 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2445 result.append(buffer);
2446 write(fd, result.string(), result.size());
2447 return NO_ERROR;
2448}
2449
Mathias Agopian65ab4712010-07-14 17:59:35 -07002450uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2451{
Eric Laurent60e18242010-07-29 06:50:24 -07002452 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002453}
2454
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002455uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2456{
2457 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2458}
2459
Mathias Agopian65ab4712010-07-14 17:59:35 -07002460// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002461AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002462 : PlaybackThread(audioFlinger, output, id, device)
2463{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002464 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002465}
2466
2467AudioFlinger::DirectOutputThread::~DirectOutputThread()
2468{
2469}
2470
Mathias Agopian65ab4712010-07-14 17:59:35 -07002471static inline
2472int32_t mul(int16_t in, int16_t v)
2473{
2474#if defined(__arm__) && !defined(__thumb__)
2475 int32_t out;
2476 asm( "smulbb %[out], %[in], %[v] \n"
2477 : [out]"=r"(out)
2478 : [in]"%r"(in), [v]"r"(v)
2479 : );
2480 return out;
2481#else
2482 return in * int32_t(v);
2483#endif
2484}
2485
2486void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2487{
2488 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002489 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002490 return;
2491 }
2492
2493 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002494 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002495 size_t count = mFrameCount * mChannelCount;
2496 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2497 int16_t *dst = mMixBuffer + count-1;
2498 while(count--) {
2499 *dst-- = (int16_t)(*src--^0x80) << 8;
2500 }
2501 }
2502
2503 size_t frameCount = mFrameCount;
2504 int16_t *out = mMixBuffer;
2505 if (ramp) {
2506 if (mChannelCount == 1) {
2507 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2508 int32_t vlInc = d / (int32_t)frameCount;
2509 int32_t vl = ((int32_t)mLeftVolShort << 16);
2510 do {
2511 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2512 out++;
2513 vl += vlInc;
2514 } while (--frameCount);
2515
2516 } else {
2517 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2518 int32_t vlInc = d / (int32_t)frameCount;
2519 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2520 int32_t vrInc = d / (int32_t)frameCount;
2521 int32_t vl = ((int32_t)mLeftVolShort << 16);
2522 int32_t vr = ((int32_t)mRightVolShort << 16);
2523 do {
2524 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2525 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2526 out += 2;
2527 vl += vlInc;
2528 vr += vrInc;
2529 } while (--frameCount);
2530 }
2531 } else {
2532 if (mChannelCount == 1) {
2533 do {
2534 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2535 out++;
2536 } while (--frameCount);
2537 } else {
2538 do {
2539 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2540 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2541 out += 2;
2542 } while (--frameCount);
2543 }
2544 }
2545
2546 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002547 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002548 size_t count = mFrameCount * mChannelCount;
2549 int16_t *src = mMixBuffer;
2550 uint8_t *dst = (uint8_t *)mMixBuffer;
2551 while(count--) {
2552 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2553 }
2554 }
2555
2556 mLeftVolShort = leftVol;
2557 mRightVolShort = rightVol;
2558}
2559
2560bool AudioFlinger::DirectOutputThread::threadLoop()
2561{
2562 uint32_t mixerStatus = MIXER_IDLE;
2563 sp<Track> trackToRemove;
2564 sp<Track> activeTrack;
2565 nsecs_t standbyTime = systemTime();
2566 int8_t *curBuf;
2567 size_t mixBufferSize = mFrameCount*mFrameSize;
2568 uint32_t activeSleepTime = activeSleepTimeUs();
2569 uint32_t idleSleepTime = idleSleepTimeUs();
2570 uint32_t sleepTime = idleSleepTime;
2571 // use shorter standby delay as on normal output to release
2572 // hardware resources as soon as possible
2573 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2574
Eric Laurentfeb0db62011-07-22 09:04:31 -07002575 acquireWakeLock();
2576
Mathias Agopian65ab4712010-07-14 17:59:35 -07002577 while (!exitPending())
2578 {
2579 bool rampVolume;
2580 uint16_t leftVol;
2581 uint16_t rightVol;
2582 Vector< sp<EffectChain> > effectChains;
2583
2584 processConfigEvents();
2585
2586 mixerStatus = MIXER_IDLE;
2587
2588 { // scope for the mLock
2589
2590 Mutex::Autolock _l(mLock);
2591
2592 if (checkForNewParameters_l()) {
2593 mixBufferSize = mFrameCount*mFrameSize;
2594 activeSleepTime = activeSleepTimeUs();
2595 idleSleepTime = idleSleepTimeUs();
2596 standbyDelay = microseconds(activeSleepTime*2);
2597 }
2598
2599 // put audio hardware into standby after short delay
2600 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2601 mSuspended) {
2602 // wait until we have something to do...
2603 if (!mStandby) {
Steve Block3856b092011-10-20 11:56:00 +01002604 ALOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002605 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002606 mStandby = true;
2607 mBytesWritten = 0;
2608 }
2609
2610 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2611 // we're about to wait, flush the binder command buffer
2612 IPCThreadState::self()->flushCommands();
2613
2614 if (exitPending()) break;
2615
Eric Laurentfeb0db62011-07-22 09:04:31 -07002616 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01002617 ALOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002618 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01002619 ALOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002620 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002621
2622 if (mMasterMute == false) {
2623 char value[PROPERTY_VALUE_MAX];
2624 property_get("ro.audio.silent", value, "0");
2625 if (atoi(value)) {
2626 LOGD("Silence is golden");
2627 setMasterMute(true);
2628 }
2629 }
2630
2631 standbyTime = systemTime() + standbyDelay;
2632 sleepTime = idleSleepTime;
2633 continue;
2634 }
2635 }
2636
2637 effectChains = mEffectChains;
2638
2639 // find out which tracks need to be processed
2640 if (mActiveTracks.size() != 0) {
2641 sp<Track> t = mActiveTracks[0].promote();
2642 if (t == 0) continue;
2643
2644 Track* const track = t.get();
2645 audio_track_cblk_t* cblk = track->cblk();
2646
2647 // The first time a track is added we wait
2648 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002649 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 !track->isPaused() && !track->isTerminated())
2651 {
Steve Block3856b092011-10-20 11:56:00 +01002652 //ALOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002653
2654 if (track->mFillingUpStatus == Track::FS_FILLED) {
2655 track->mFillingUpStatus = Track::FS_ACTIVE;
2656 mLeftVolFloat = mRightVolFloat = 0;
2657 mLeftVolShort = mRightVolShort = 0;
2658 if (track->mState == TrackBase::RESUMING) {
2659 track->mState = TrackBase::ACTIVE;
2660 rampVolume = true;
2661 }
2662 } else if (cblk->server != 0) {
2663 // If the track is stopped before the first frame was mixed,
2664 // do not apply ramp
2665 rampVolume = true;
2666 }
2667 // compute volume for this track
2668 float left, right;
2669 if (track->isMuted() || mMasterMute || track->isPausing() ||
2670 mStreamTypes[track->type()].mute) {
2671 left = right = 0;
2672 if (track->isPausing()) {
2673 track->setPaused();
2674 }
2675 } else {
2676 float typeVolume = mStreamTypes[track->type()].volume;
2677 float v = mMasterVolume * typeVolume;
2678 float v_clamped = v * cblk->volume[0];
2679 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2680 left = v_clamped/MAX_GAIN;
2681 v_clamped = v * cblk->volume[1];
2682 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2683 right = v_clamped/MAX_GAIN;
2684 }
2685
2686 if (left != mLeftVolFloat || right != mRightVolFloat) {
2687 mLeftVolFloat = left;
2688 mRightVolFloat = right;
2689
2690 // If audio HAL implements volume control,
2691 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002692 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002693 left = 1.0f;
2694 right = 1.0f;
2695 }
2696
2697 // Convert volumes from float to 8.24
2698 uint32_t vl = (uint32_t)(left * (1 << 24));
2699 uint32_t vr = (uint32_t)(right * (1 << 24));
2700
2701 // Delegate volume control to effect in track effect chain if needed
2702 // only one effect chain can be present on DirectOutputThread, so if
2703 // there is one, the track is connected to it
2704 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002705 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002706 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002707 rampVolume = false;
2708 }
2709 }
2710
2711 // Convert volumes from 8.24 to 4.12 format
2712 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2713 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2714 leftVol = (uint16_t)v_clamped;
2715 v_clamped = (vr + (1 << 11)) >> 12;
2716 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2717 rightVol = (uint16_t)v_clamped;
2718 } else {
2719 leftVol = mLeftVolShort;
2720 rightVol = mRightVolShort;
2721 rampVolume = false;
2722 }
2723
2724 // reset retry count
2725 track->mRetryCount = kMaxTrackRetriesDirect;
2726 activeTrack = t;
2727 mixerStatus = MIXER_TRACKS_READY;
2728 } else {
Steve Block3856b092011-10-20 11:56:00 +01002729 //ALOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002730 if (track->isStopped()) {
2731 track->reset();
2732 }
2733 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2734 // We have consumed all the buffers of this track.
2735 // Remove it from the list of active tracks.
2736 trackToRemove = track;
2737 } else {
2738 // No buffers for this track. Give it a few chances to
2739 // fill a buffer, then remove it from active list.
2740 if (--(track->mRetryCount) <= 0) {
Steve Block3856b092011-10-20 11:56:00 +01002741 ALOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002742 trackToRemove = track;
2743 } else {
2744 mixerStatus = MIXER_TRACKS_ENABLED;
2745 }
2746 }
2747 }
2748 }
2749
2750 // remove all the tracks that need to be...
2751 if (UNLIKELY(trackToRemove != 0)) {
2752 mActiveTracks.remove(trackToRemove);
2753 if (!effectChains.isEmpty()) {
Steve Block3856b092011-10-20 11:56:00 +01002754 ALOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
Eric Laurentde070132010-07-13 04:45:46 -07002755 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002756 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002757 }
2758 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002759 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002760 }
2761 }
2762
Eric Laurentde070132010-07-13 04:45:46 -07002763 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002764 }
2765
2766 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2767 AudioBufferProvider::Buffer buffer;
2768 size_t frameCount = mFrameCount;
2769 curBuf = (int8_t *)mMixBuffer;
2770 // output audio to hardware
2771 while (frameCount) {
2772 buffer.frameCount = frameCount;
2773 activeTrack->getNextBuffer(&buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08002774 if (UNLIKELY(buffer.raw == NULL)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002775 memset(curBuf, 0, frameCount * mFrameSize);
2776 break;
2777 }
2778 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2779 frameCount -= buffer.frameCount;
2780 curBuf += buffer.frameCount * mFrameSize;
2781 activeTrack->releaseBuffer(&buffer);
2782 }
2783 sleepTime = 0;
2784 standbyTime = systemTime() + standbyDelay;
2785 } else {
2786 if (sleepTime == 0) {
2787 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2788 sleepTime = activeSleepTime;
2789 } else {
2790 sleepTime = idleSleepTime;
2791 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002792 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002793 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2794 sleepTime = 0;
2795 }
2796 }
2797
2798 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002799 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002800 }
2801 // sleepTime == 0 means we must write to audio hardware
2802 if (sleepTime == 0) {
2803 if (mixerStatus == MIXER_TRACKS_READY) {
2804 applyVolume(leftVol, rightVol, rampVolume);
2805 }
2806 for (size_t i = 0; i < effectChains.size(); i ++) {
2807 effectChains[i]->process_l();
2808 }
Eric Laurentde070132010-07-13 04:45:46 -07002809 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002810
2811 mLastWriteTime = systemTime();
2812 mInWrite = true;
2813 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002814 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002815 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2816 mNumWrites++;
2817 mInWrite = false;
2818 mStandby = false;
2819 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002820 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002821 usleep(sleepTime);
2822 }
2823
2824 // finally let go of removed track, without the lock held
2825 // since we can't guarantee the destructors won't acquire that
2826 // same lock.
2827 trackToRemove.clear();
2828 activeTrack.clear();
2829
2830 // Effect chains will be actually deleted here if they were removed from
2831 // mEffectChains list during mixing or effects processing
2832 effectChains.clear();
2833 }
2834
2835 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002836 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002837 }
2838
Eric Laurentfeb0db62011-07-22 09:04:31 -07002839 releaseWakeLock();
2840
Steve Block3856b092011-10-20 11:56:00 +01002841 ALOGV("DirectOutputThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002842 return false;
2843}
2844
2845// getTrackName_l() must be called with ThreadBase::mLock held
2846int AudioFlinger::DirectOutputThread::getTrackName_l()
2847{
2848 return 0;
2849}
2850
2851// deleteTrackName_l() must be called with ThreadBase::mLock held
2852void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2853{
2854}
2855
2856// checkForNewParameters_l() must be called with ThreadBase::mLock held
2857bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2858{
2859 bool reconfig = false;
2860
2861 while (!mNewParameters.isEmpty()) {
2862 status_t status = NO_ERROR;
2863 String8 keyValuePair = mNewParameters[0];
2864 AudioParameter param = AudioParameter(keyValuePair);
2865 int value;
2866
2867 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2868 // do not accept frame count changes if tracks are open as the track buffer
2869 // size depends on frame count and correct behavior would not be garantied
2870 // if frame count is changed after track creation
2871 if (!mTracks.isEmpty()) {
2872 status = INVALID_OPERATION;
2873 } else {
2874 reconfig = true;
2875 }
2876 }
2877 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002878 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002879 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002880 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002881 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002882 mStandby = true;
2883 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002884 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002885 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002886 }
2887 if (status == NO_ERROR && reconfig) {
2888 readOutputParameters();
2889 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2890 }
2891 }
2892
2893 mNewParameters.removeAt(0);
2894
2895 mParamStatus = status;
2896 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07002897 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
2898 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08002899 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002900 }
2901 return reconfig;
2902}
2903
2904uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2905{
2906 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002907 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent162b40b2011-12-05 09:47:19 -08002908 time = PlaybackThread::activeSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002909 } else {
2910 time = 10000;
2911 }
2912 return time;
2913}
2914
2915uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2916{
2917 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002918 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002919 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002920 } else {
2921 time = 10000;
2922 }
2923 return time;
2924}
2925
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002926uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2927{
2928 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002929 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002930 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2931 } else {
2932 time = 10000;
2933 }
2934 return time;
2935}
2936
2937
Mathias Agopian65ab4712010-07-14 17:59:35 -07002938// ----------------------------------------------------------------------------
2939
2940AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2941 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2942{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002943 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002944 addOutputTrack(mainThread);
2945}
2946
2947AudioFlinger::DuplicatingThread::~DuplicatingThread()
2948{
2949 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2950 mOutputTracks[i]->destroy();
2951 }
2952 mOutputTracks.clear();
2953}
2954
2955bool AudioFlinger::DuplicatingThread::threadLoop()
2956{
2957 Vector< sp<Track> > tracksToRemove;
2958 uint32_t mixerStatus = MIXER_IDLE;
2959 nsecs_t standbyTime = systemTime();
2960 size_t mixBufferSize = mFrameCount*mFrameSize;
2961 SortedVector< sp<OutputTrack> > outputTracks;
2962 uint32_t writeFrames = 0;
2963 uint32_t activeSleepTime = activeSleepTimeUs();
2964 uint32_t idleSleepTime = idleSleepTimeUs();
2965 uint32_t sleepTime = idleSleepTime;
2966 Vector< sp<EffectChain> > effectChains;
2967
Eric Laurentfeb0db62011-07-22 09:04:31 -07002968 acquireWakeLock();
2969
Mathias Agopian65ab4712010-07-14 17:59:35 -07002970 while (!exitPending())
2971 {
2972 processConfigEvents();
2973
2974 mixerStatus = MIXER_IDLE;
2975 { // scope for the mLock
2976
2977 Mutex::Autolock _l(mLock);
2978
2979 if (checkForNewParameters_l()) {
2980 mixBufferSize = mFrameCount*mFrameSize;
2981 updateWaitTime();
2982 activeSleepTime = activeSleepTimeUs();
2983 idleSleepTime = idleSleepTimeUs();
2984 }
2985
2986 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2987
2988 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2989 outputTracks.add(mOutputTracks[i]);
2990 }
2991
2992 // put audio hardware into standby after short delay
2993 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2994 mSuspended) {
2995 if (!mStandby) {
2996 for (size_t i = 0; i < outputTracks.size(); i++) {
2997 outputTracks[i]->stop();
2998 }
2999 mStandby = true;
3000 mBytesWritten = 0;
3001 }
3002
3003 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
3004 // we're about to wait, flush the binder command buffer
3005 IPCThreadState::self()->flushCommands();
3006 outputTracks.clear();
3007
3008 if (exitPending()) break;
3009
Eric Laurentfeb0db62011-07-22 09:04:31 -07003010 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01003011 ALOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003012 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01003013 ALOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07003014 acquireWakeLock_l();
3015
Mathias Agopian65ab4712010-07-14 17:59:35 -07003016 if (mMasterMute == false) {
3017 char value[PROPERTY_VALUE_MAX];
3018 property_get("ro.audio.silent", value, "0");
3019 if (atoi(value)) {
3020 LOGD("Silence is golden");
3021 setMasterMute(true);
3022 }
3023 }
3024
3025 standbyTime = systemTime() + kStandbyTimeInNsecs;
3026 sleepTime = idleSleepTime;
3027 continue;
3028 }
3029 }
3030
3031 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
3032
3033 // prevent any changes in effect chain list and in each effect chain
3034 // during mixing and effect process as the audio buffers could be deleted
3035 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07003036 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003037 }
3038
3039 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
3040 // mix buffers...
3041 if (outputsReady(outputTracks)) {
3042 mAudioMixer->process();
3043 } else {
3044 memset(mMixBuffer, 0, mixBufferSize);
3045 }
3046 sleepTime = 0;
3047 writeFrames = mFrameCount;
3048 } else {
3049 if (sleepTime == 0) {
3050 if (mixerStatus == MIXER_TRACKS_ENABLED) {
3051 sleepTime = activeSleepTime;
3052 } else {
3053 sleepTime = idleSleepTime;
3054 }
3055 } else if (mBytesWritten != 0) {
3056 // flush remaining overflow buffers in output tracks
3057 for (size_t i = 0; i < outputTracks.size(); i++) {
3058 if (outputTracks[i]->isActive()) {
3059 sleepTime = 0;
3060 writeFrames = 0;
3061 memset(mMixBuffer, 0, mixBufferSize);
3062 break;
3063 }
3064 }
3065 }
3066 }
3067
3068 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07003069 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003070 }
3071 // sleepTime == 0 means we must write to audio hardware
3072 if (sleepTime == 0) {
3073 for (size_t i = 0; i < effectChains.size(); i ++) {
3074 effectChains[i]->process_l();
3075 }
3076 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003077 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003078
3079 standbyTime = systemTime() + kStandbyTimeInNsecs;
3080 for (size_t i = 0; i < outputTracks.size(); i++) {
3081 outputTracks[i]->write(mMixBuffer, writeFrames);
3082 }
3083 mStandby = false;
3084 mBytesWritten += mixBufferSize;
3085 } else {
3086 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07003087 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003088 usleep(sleepTime);
3089 }
3090
3091 // finally let go of all our tracks, without the lock held
3092 // since we can't guarantee the destructors won't acquire that
3093 // same lock.
3094 tracksToRemove.clear();
3095 outputTracks.clear();
3096
3097 // Effect chains will be actually deleted here if they were removed from
3098 // mEffectChains list during mixing or effects processing
3099 effectChains.clear();
3100 }
3101
Eric Laurentfeb0db62011-07-22 09:04:31 -07003102 releaseWakeLock();
3103
Mathias Agopian65ab4712010-07-14 17:59:35 -07003104 return false;
3105}
3106
3107void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
3108{
3109 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
3110 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
3111 this,
3112 mSampleRate,
3113 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003114 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003115 frameCount);
3116 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07003117 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003118 mOutputTracks.add(outputTrack);
Steve Block3856b092011-10-20 11:56:00 +01003119 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003120 updateWaitTime();
3121 }
3122}
3123
3124void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
3125{
3126 Mutex::Autolock _l(mLock);
3127 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3128 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
3129 mOutputTracks[i]->destroy();
3130 mOutputTracks.removeAt(i);
3131 updateWaitTime();
3132 return;
3133 }
3134 }
Steve Block3856b092011-10-20 11:56:00 +01003135 ALOGV("removeOutputTrack(): unkonwn thread: %p", thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003136}
3137
3138void AudioFlinger::DuplicatingThread::updateWaitTime()
3139{
3140 mWaitTimeMs = UINT_MAX;
3141 for (size_t i = 0; i < mOutputTracks.size(); i++) {
3142 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
3143 if (strong != NULL) {
3144 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
3145 if (waitTimeMs < mWaitTimeMs) {
3146 mWaitTimeMs = waitTimeMs;
3147 }
3148 }
3149 }
3150}
3151
3152
3153bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
3154{
3155 for (size_t i = 0; i < outputTracks.size(); i++) {
3156 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
3157 if (thread == 0) {
3158 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
3159 return false;
3160 }
3161 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3162 if (playbackThread->standby() && !playbackThread->isSuspended()) {
Steve Block3856b092011-10-20 11:56:00 +01003163 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003164 return false;
3165 }
3166 }
3167 return true;
3168}
3169
3170uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
3171{
3172 return (mWaitTimeMs * 1000) / 2;
3173}
3174
3175// ----------------------------------------------------------------------------
3176
3177// TrackBase constructor must be called with AudioFlinger::mLock held
3178AudioFlinger::ThreadBase::TrackBase::TrackBase(
3179 const wp<ThreadBase>& thread,
3180 const sp<Client>& client,
3181 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003182 uint32_t format,
3183 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003184 int frameCount,
3185 uint32_t flags,
3186 const sp<IMemory>& sharedBuffer,
3187 int sessionId)
3188 : RefBase(),
3189 mThread(thread),
3190 mClient(client),
3191 mCblk(0),
3192 mFrameCount(0),
3193 mState(IDLE),
3194 mClientTid(-1),
3195 mFormat(format),
3196 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3197 mSessionId(sessionId)
3198{
Steve Block3856b092011-10-20 11:56:00 +01003199 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003200
3201 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3202 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003203 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003204 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3205 if (sharedBuffer == 0) {
3206 size += bufferSize;
3207 }
3208
3209 if (client != NULL) {
3210 mCblkMemory = client->heap()->allocate(size);
3211 if (mCblkMemory != 0) {
3212 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3213 if (mCblk) { // construct the shared structure in-place.
3214 new(mCblk) audio_track_cblk_t();
3215 // clear all buffers
3216 mCblk->frameCount = frameCount;
3217 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003218 mChannelCount = channelCount;
3219 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003220 if (sharedBuffer == 0) {
3221 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3222 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3223 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003224 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003225 mCblk->flags = CBLK_UNDERRUN_ON;
3226 } else {
3227 mBuffer = sharedBuffer->pointer();
3228 }
3229 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3230 }
3231 } else {
3232 LOGE("not enough memory for AudioTrack size=%u", size);
3233 client->heap()->dump("AudioTrack");
3234 return;
3235 }
3236 } else {
3237 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3238 if (mCblk) { // construct the shared structure in-place.
3239 new(mCblk) audio_track_cblk_t();
3240 // clear all buffers
3241 mCblk->frameCount = frameCount;
3242 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003243 mChannelCount = channelCount;
3244 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003245 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3246 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3247 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003248 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 mCblk->flags = CBLK_UNDERRUN_ON;
3250 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3251 }
3252 }
3253}
3254
3255AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3256{
3257 if (mCblk) {
3258 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3259 if (mClient == NULL) {
3260 delete mCblk;
3261 }
3262 }
3263 mCblkMemory.clear(); // and free the shared memory
3264 if (mClient != NULL) {
3265 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3266 mClient.clear();
3267 }
3268}
3269
3270void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3271{
Glenn Kastene0feee32011-12-13 11:53:26 -08003272 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003273 mFrameCount = buffer->frameCount;
3274 step();
3275 buffer->frameCount = 0;
3276}
3277
3278bool AudioFlinger::ThreadBase::TrackBase::step() {
3279 bool result;
3280 audio_track_cblk_t* cblk = this->cblk();
3281
3282 result = cblk->stepServer(mFrameCount);
3283 if (!result) {
Steve Block3856b092011-10-20 11:56:00 +01003284 ALOGV("stepServer failed acquiring cblk mutex");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003285 mFlags |= STEPSERVER_FAILED;
3286 }
3287 return result;
3288}
3289
3290void AudioFlinger::ThreadBase::TrackBase::reset() {
3291 audio_track_cblk_t* cblk = this->cblk();
3292
3293 cblk->user = 0;
3294 cblk->server = 0;
3295 cblk->userBase = 0;
3296 cblk->serverBase = 0;
3297 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
Steve Block3856b092011-10-20 11:56:00 +01003298 ALOGV("TrackBase::reset");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003299}
3300
3301sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3302{
3303 return mCblkMemory;
3304}
3305
3306int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3307 return (int)mCblk->sampleRate;
3308}
3309
3310int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003311 return (const int)mChannelCount;
3312}
3313
3314uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3315 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003316}
3317
3318void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3319 audio_track_cblk_t* cblk = this->cblk();
3320 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3321 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3322
3323 // Check validity of returned pointer in case the track control block would have been corrupted.
3324 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3325 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3326 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 -07003327 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003328 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003329 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330 return 0;
3331 }
3332
3333 return bufferStart;
3334}
3335
3336// ----------------------------------------------------------------------------
3337
3338// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3339AudioFlinger::PlaybackThread::Track::Track(
3340 const wp<ThreadBase>& thread,
3341 const sp<Client>& client,
3342 int streamType,
3343 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003344 uint32_t format,
3345 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003346 int frameCount,
3347 const sp<IMemory>& sharedBuffer,
3348 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003349 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003350 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3351 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003352{
3353 if (mCblk != NULL) {
3354 sp<ThreadBase> baseThread = thread.promote();
3355 if (baseThread != 0) {
3356 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3357 mName = playbackThread->getTrackName_l();
3358 mMainBuffer = playbackThread->mixBuffer();
3359 }
Steve Block3856b092011-10-20 11:56:00 +01003360 ALOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 if (mName < 0) {
3362 LOGE("no more track names available");
3363 }
3364 mVolume[0] = 1.0f;
3365 mVolume[1] = 1.0f;
3366 mStreamType = streamType;
3367 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3368 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003369 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003370 }
3371}
3372
3373AudioFlinger::PlaybackThread::Track::~Track()
3374{
Steve Block3856b092011-10-20 11:56:00 +01003375 ALOGV("PlaybackThread::Track destructor");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003376 sp<ThreadBase> thread = mThread.promote();
3377 if (thread != 0) {
3378 Mutex::Autolock _l(thread->mLock);
3379 mState = TERMINATED;
3380 }
3381}
3382
3383void AudioFlinger::PlaybackThread::Track::destroy()
3384{
3385 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3386 // by removing it from mTracks vector, so there is a risk that this Tracks's
3387 // desctructor is called. As the destructor needs to lock mLock,
3388 // we must acquire a strong reference on this Track before locking mLock
3389 // here so that the destructor is called only when exiting this function.
3390 // On the other hand, as long as Track::destroy() is only called by
3391 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3392 // this Track with its member mTrack.
3393 sp<Track> keep(this);
3394 { // scope for mLock
3395 sp<ThreadBase> thread = mThread.promote();
3396 if (thread != 0) {
3397 if (!isOutputTrack()) {
3398 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003399 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003400 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003401 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003402
3403 // to track the speaker usage
3404 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003405 }
3406 AudioSystem::releaseOutput(thread->id());
3407 }
3408 Mutex::Autolock _l(thread->mLock);
3409 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3410 playbackThread->destroyTrack_l(this);
3411 }
3412 }
3413}
3414
3415void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3416{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003417 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 -07003418 mName - AudioMixer::TRACK0,
3419 (mClient == NULL) ? getpid() : mClient->pid(),
3420 mStreamType,
3421 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003422 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003423 mSessionId,
3424 mFrameCount,
3425 mState,
3426 mMute,
3427 mFillingUpStatus,
3428 mCblk->sampleRate,
3429 mCblk->volume[0],
3430 mCblk->volume[1],
3431 mCblk->server,
3432 mCblk->user,
3433 (int)mMainBuffer,
3434 (int)mAuxBuffer);
3435}
3436
3437status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3438{
3439 audio_track_cblk_t* cblk = this->cblk();
3440 uint32_t framesReady;
3441 uint32_t framesReq = buffer->frameCount;
3442
3443 // Check if last stepServer failed, try to step now
3444 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3445 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003446 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003447 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3448 }
3449
3450 framesReady = cblk->framesReady();
3451
3452 if (LIKELY(framesReady)) {
3453 uint32_t s = cblk->server;
3454 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3455
3456 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3457 if (framesReq > framesReady) {
3458 framesReq = framesReady;
3459 }
3460 if (s + framesReq > bufferEnd) {
3461 framesReq = bufferEnd - s;
3462 }
3463
3464 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003465 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466
3467 buffer->frameCount = framesReq;
3468 return NO_ERROR;
3469 }
3470
3471getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003472 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003473 buffer->frameCount = 0;
Steve Block3856b092011-10-20 11:56:00 +01003474 ALOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003475 return NOT_ENOUGH_DATA;
3476}
3477
3478bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003479 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003480
3481 if (mCblk->framesReady() >= mCblk->frameCount ||
3482 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3483 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003484 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003485 return true;
3486 }
3487 return false;
3488}
3489
3490status_t AudioFlinger::PlaybackThread::Track::start()
3491{
3492 status_t status = NO_ERROR;
Steve Block3856b092011-10-20 11:56:00 +01003493 ALOGV("start(%d), calling thread %d session %d",
Eric Laurentf997cab2010-07-19 06:24:46 -07003494 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003495 sp<ThreadBase> thread = mThread.promote();
3496 if (thread != 0) {
3497 Mutex::Autolock _l(thread->mLock);
3498 int state = mState;
3499 // here the track could be either new, or restarted
3500 // in both cases "unstop" the track
3501 if (mState == PAUSED) {
3502 mState = TrackBase::RESUMING;
Steve Block3856b092011-10-20 11:56:00 +01003503 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003504 } else {
3505 mState = TrackBase::ACTIVE;
Steve Block3856b092011-10-20 11:56:00 +01003506 ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003507 }
3508
3509 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3510 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003511 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003512 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003513 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003514 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003515
3516 // to track the speaker usage
3517 if (status == NO_ERROR) {
3518 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 }
3521 if (status == NO_ERROR) {
3522 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3523 playbackThread->addTrack_l(this);
3524 } else {
3525 mState = state;
3526 }
3527 } else {
3528 status = BAD_VALUE;
3529 }
3530 return status;
3531}
3532
3533void AudioFlinger::PlaybackThread::Track::stop()
3534{
Steve Block3856b092011-10-20 11:56:00 +01003535 ALOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003536 sp<ThreadBase> thread = mThread.promote();
3537 if (thread != 0) {
3538 Mutex::Autolock _l(thread->mLock);
3539 int state = mState;
3540 if (mState > STOPPED) {
3541 mState = STOPPED;
3542 // If the track is not active (PAUSED and buffers full), flush buffers
3543 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3544 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3545 reset();
3546 }
Steve Block3856b092011-10-20 11:56:00 +01003547 ALOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003548 }
3549 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3550 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003551 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003552 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003553 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003554 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003555
3556 // to track the speaker usage
3557 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003558 }
3559 }
3560}
3561
3562void AudioFlinger::PlaybackThread::Track::pause()
3563{
Steve Block3856b092011-10-20 11:56:00 +01003564 ALOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003565 sp<ThreadBase> thread = mThread.promote();
3566 if (thread != 0) {
3567 Mutex::Autolock _l(thread->mLock);
3568 if (mState == ACTIVE || mState == RESUMING) {
3569 mState = PAUSING;
Steve Block3856b092011-10-20 11:56:00 +01003570 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571 if (!isOutputTrack()) {
3572 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003573 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003574 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003575 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003577
3578 // to track the speaker usage
3579 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003580 }
3581 }
3582 }
3583}
3584
3585void AudioFlinger::PlaybackThread::Track::flush()
3586{
Steve Block3856b092011-10-20 11:56:00 +01003587 ALOGV("flush(%d)", mName);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003588 sp<ThreadBase> thread = mThread.promote();
3589 if (thread != 0) {
3590 Mutex::Autolock _l(thread->mLock);
3591 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3592 return;
3593 }
3594 // No point remaining in PAUSED state after a flush => go to
3595 // STOPPED state
3596 mState = STOPPED;
3597
Eric Laurent38ccae22011-03-28 18:37:07 -07003598 // do not reset the track if it is still in the process of being stopped or paused.
3599 // this will be done by prepareTracks_l() when the track is stopped.
3600 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3601 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3602 reset();
3603 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003604 }
3605}
3606
3607void AudioFlinger::PlaybackThread::Track::reset()
3608{
3609 // Do not reset twice to avoid discarding data written just after a flush and before
3610 // the audioflinger thread detects the track is stopped.
3611 if (!mResetDone) {
3612 TrackBase::reset();
3613 // Force underrun condition to avoid false underrun callback until first data is
3614 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003615 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3616 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003617 mFillingUpStatus = FS_FILLING;
3618 mResetDone = true;
3619 }
3620}
3621
3622void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3623{
3624 mMute = muted;
3625}
3626
3627void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3628{
3629 mVolume[0] = left;
3630 mVolume[1] = right;
3631}
3632
3633status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3634{
3635 status_t status = DEAD_OBJECT;
3636 sp<ThreadBase> thread = mThread.promote();
3637 if (thread != 0) {
3638 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3639 status = playbackThread->attachAuxEffect(this, EffectId);
3640 }
3641 return status;
3642}
3643
3644void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3645{
3646 mAuxEffectId = EffectId;
3647 mAuxBuffer = buffer;
3648}
3649
3650// ----------------------------------------------------------------------------
3651
3652// RecordTrack constructor must be called with AudioFlinger::mLock held
3653AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3654 const wp<ThreadBase>& thread,
3655 const sp<Client>& client,
3656 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003657 uint32_t format,
3658 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659 int frameCount,
3660 uint32_t flags,
3661 int sessionId)
3662 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003663 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003664 mOverflow(false)
3665{
3666 if (mCblk != NULL) {
Steve Block3856b092011-10-20 11:56:00 +01003667 ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003668 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003669 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003670 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003671 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003672 } else {
3673 mCblk->frameSize = sizeof(int8_t);
3674 }
3675 }
3676}
3677
3678AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3679{
3680 sp<ThreadBase> thread = mThread.promote();
3681 if (thread != 0) {
3682 AudioSystem::releaseInput(thread->id());
3683 }
3684}
3685
3686status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3687{
3688 audio_track_cblk_t* cblk = this->cblk();
3689 uint32_t framesAvail;
3690 uint32_t framesReq = buffer->frameCount;
3691
3692 // Check if last stepServer failed, try to step now
3693 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3694 if (!step()) goto getNextBuffer_exit;
Steve Block3856b092011-10-20 11:56:00 +01003695 ALOGV("stepServer recovered");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003696 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3697 }
3698
3699 framesAvail = cblk->framesAvailable_l();
3700
3701 if (LIKELY(framesAvail)) {
3702 uint32_t s = cblk->server;
3703 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3704
3705 if (framesReq > framesAvail) {
3706 framesReq = framesAvail;
3707 }
3708 if (s + framesReq > bufferEnd) {
3709 framesReq = bufferEnd - s;
3710 }
3711
3712 buffer->raw = getBuffer(s, framesReq);
Glenn Kastene0feee32011-12-13 11:53:26 -08003713 if (buffer->raw == NULL) goto getNextBuffer_exit;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003714
3715 buffer->frameCount = framesReq;
3716 return NO_ERROR;
3717 }
3718
3719getNextBuffer_exit:
Glenn Kastene0feee32011-12-13 11:53:26 -08003720 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003721 buffer->frameCount = 0;
3722 return NOT_ENOUGH_DATA;
3723}
3724
3725status_t AudioFlinger::RecordThread::RecordTrack::start()
3726{
3727 sp<ThreadBase> thread = mThread.promote();
3728 if (thread != 0) {
3729 RecordThread *recordThread = (RecordThread *)thread.get();
3730 return recordThread->start(this);
3731 } else {
3732 return BAD_VALUE;
3733 }
3734}
3735
3736void AudioFlinger::RecordThread::RecordTrack::stop()
3737{
3738 sp<ThreadBase> thread = mThread.promote();
3739 if (thread != 0) {
3740 RecordThread *recordThread = (RecordThread *)thread.get();
3741 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003742 TrackBase::reset();
3743 // Force overerrun condition to avoid false overrun callback until first data is
3744 // read from buffer
3745 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003746 }
3747}
3748
3749void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3750{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003751 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003752 (mClient == NULL) ? getpid() : mClient->pid(),
3753 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003754 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003755 mSessionId,
3756 mFrameCount,
3757 mState,
3758 mCblk->sampleRate,
3759 mCblk->server,
3760 mCblk->user);
3761}
3762
3763
3764// ----------------------------------------------------------------------------
3765
3766AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3767 const wp<ThreadBase>& thread,
3768 DuplicatingThread *sourceThread,
3769 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003770 uint32_t format,
3771 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003772 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003773 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003774 mActive(false), mSourceThread(sourceThread)
3775{
3776
3777 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3778 if (mCblk != NULL) {
3779 mCblk->flags |= CBLK_DIRECTION_OUT;
3780 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3781 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3782 mOutBuffer.frameCount = 0;
3783 playbackThread->mTracks.add(this);
Steve Block3856b092011-10-20 11:56:00 +01003784 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003785 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3786 mCblk, mBuffer, mCblk->buffers,
3787 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003788 } else {
3789 LOGW("Error creating output track on thread %p", playbackThread);
3790 }
3791}
3792
3793AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3794{
3795 clearBufferQueue();
3796}
3797
3798status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3799{
3800 status_t status = Track::start();
3801 if (status != NO_ERROR) {
3802 return status;
3803 }
3804
3805 mActive = true;
3806 mRetryCount = 127;
3807 return status;
3808}
3809
3810void AudioFlinger::PlaybackThread::OutputTrack::stop()
3811{
3812 Track::stop();
3813 clearBufferQueue();
3814 mOutBuffer.frameCount = 0;
3815 mActive = false;
3816}
3817
3818bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3819{
3820 Buffer *pInBuffer;
3821 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003822 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823 bool outputBufferFull = false;
3824 inBuffer.frameCount = frames;
3825 inBuffer.i16 = data;
3826
3827 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3828
3829 if (!mActive && frames != 0) {
3830 start();
3831 sp<ThreadBase> thread = mThread.promote();
3832 if (thread != 0) {
3833 MixerThread *mixerThread = (MixerThread *)thread.get();
3834 if (mCblk->frameCount > frames){
3835 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3836 uint32_t startFrames = (mCblk->frameCount - frames);
3837 pInBuffer = new Buffer;
3838 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3839 pInBuffer->frameCount = startFrames;
3840 pInBuffer->i16 = pInBuffer->mBuffer;
3841 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3842 mBufferQueue.add(pInBuffer);
3843 } else {
3844 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3845 }
3846 }
3847 }
3848 }
3849
3850 while (waitTimeLeftMs) {
3851 // First write pending buffers, then new data
3852 if (mBufferQueue.size()) {
3853 pInBuffer = mBufferQueue.itemAt(0);
3854 } else {
3855 pInBuffer = &inBuffer;
3856 }
3857
3858 if (pInBuffer->frameCount == 0) {
3859 break;
3860 }
3861
3862 if (mOutBuffer.frameCount == 0) {
3863 mOutBuffer.frameCount = pInBuffer->frameCount;
3864 nsecs_t startTime = systemTime();
3865 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Steve Block3856b092011-10-20 11:56:00 +01003866 ALOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003867 outputBufferFull = true;
3868 break;
3869 }
3870 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3871 if (waitTimeLeftMs >= waitTimeMs) {
3872 waitTimeLeftMs -= waitTimeMs;
3873 } else {
3874 waitTimeLeftMs = 0;
3875 }
3876 }
3877
3878 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3879 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3880 mCblk->stepUser(outFrames);
3881 pInBuffer->frameCount -= outFrames;
3882 pInBuffer->i16 += outFrames * channelCount;
3883 mOutBuffer.frameCount -= outFrames;
3884 mOutBuffer.i16 += outFrames * channelCount;
3885
3886 if (pInBuffer->frameCount == 0) {
3887 if (mBufferQueue.size()) {
3888 mBufferQueue.removeAt(0);
3889 delete [] pInBuffer->mBuffer;
3890 delete pInBuffer;
Steve Block3856b092011-10-20 11:56:00 +01003891 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 } else {
3893 break;
3894 }
3895 }
3896 }
3897
3898 // If we could not write all frames, allocate a buffer and queue it for next time.
3899 if (inBuffer.frameCount) {
3900 sp<ThreadBase> thread = mThread.promote();
3901 if (thread != 0 && !thread->standby()) {
3902 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3903 pInBuffer = new Buffer;
3904 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3905 pInBuffer->frameCount = inBuffer.frameCount;
3906 pInBuffer->i16 = pInBuffer->mBuffer;
3907 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3908 mBufferQueue.add(pInBuffer);
Steve Block3856b092011-10-20 11:56:00 +01003909 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07003910 } else {
3911 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3912 }
3913 }
3914 }
3915
3916 // Calling write() with a 0 length buffer, means that no more data will be written:
3917 // If no more buffers are pending, fill output track buffer to make sure it is started
3918 // by output mixer.
3919 if (frames == 0 && mBufferQueue.size() == 0) {
3920 if (mCblk->user < mCblk->frameCount) {
3921 frames = mCblk->frameCount - mCblk->user;
3922 pInBuffer = new Buffer;
3923 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3924 pInBuffer->frameCount = frames;
3925 pInBuffer->i16 = pInBuffer->mBuffer;
3926 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3927 mBufferQueue.add(pInBuffer);
3928 } else if (mActive) {
3929 stop();
3930 }
3931 }
3932
3933 return outputBufferFull;
3934}
3935
3936status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3937{
3938 int active;
3939 status_t result;
3940 audio_track_cblk_t* cblk = mCblk;
3941 uint32_t framesReq = buffer->frameCount;
3942
Steve Block3856b092011-10-20 11:56:00 +01003943// ALOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944 buffer->frameCount = 0;
3945
3946 uint32_t framesAvail = cblk->framesAvailable();
3947
3948
3949 if (framesAvail == 0) {
3950 Mutex::Autolock _l(cblk->lock);
3951 goto start_loop_here;
3952 while (framesAvail == 0) {
3953 active = mActive;
3954 if (UNLIKELY(!active)) {
Steve Block3856b092011-10-20 11:56:00 +01003955 ALOGV("Not active and NO_MORE_BUFFERS");
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 return AudioTrack::NO_MORE_BUFFERS;
3957 }
3958 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3959 if (result != NO_ERROR) {
3960 return AudioTrack::NO_MORE_BUFFERS;
3961 }
3962 // read the server count again
3963 start_loop_here:
3964 framesAvail = cblk->framesAvailable_l();
3965 }
3966 }
3967
3968// if (framesAvail < framesReq) {
3969// return AudioTrack::NO_MORE_BUFFERS;
3970// }
3971
3972 if (framesReq > framesAvail) {
3973 framesReq = framesAvail;
3974 }
3975
3976 uint32_t u = cblk->user;
3977 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3978
3979 if (u + framesReq > bufferEnd) {
3980 framesReq = bufferEnd - u;
3981 }
3982
3983 buffer->frameCount = framesReq;
3984 buffer->raw = (void *)cblk->buffer(u);
3985 return NO_ERROR;
3986}
3987
3988
3989void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3990{
3991 size_t size = mBufferQueue.size();
3992 Buffer *pBuffer;
3993
3994 for (size_t i = 0; i < size; i++) {
3995 pBuffer = mBufferQueue.itemAt(i);
3996 delete [] pBuffer->mBuffer;
3997 delete pBuffer;
3998 }
3999 mBufferQueue.clear();
4000}
4001
4002// ----------------------------------------------------------------------------
4003
4004AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
4005 : RefBase(),
4006 mAudioFlinger(audioFlinger),
4007 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
4008 mPid(pid)
4009{
4010 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
4011}
4012
4013// Client destructor must be called with AudioFlinger::mLock held
4014AudioFlinger::Client::~Client()
4015{
4016 mAudioFlinger->removeClient_l(mPid);
4017}
4018
4019const sp<MemoryDealer>& AudioFlinger::Client::heap() const
4020{
4021 return mMemoryDealer;
4022}
4023
4024// ----------------------------------------------------------------------------
4025
4026AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
4027 const sp<IAudioFlingerClient>& client,
4028 pid_t pid)
4029 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
4030{
4031}
4032
4033AudioFlinger::NotificationClient::~NotificationClient()
4034{
4035 mClient.clear();
4036}
4037
4038void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
4039{
4040 sp<NotificationClient> keep(this);
4041 {
4042 mAudioFlinger->removeNotificationClient(mPid);
4043 }
4044}
4045
4046// ----------------------------------------------------------------------------
4047
4048AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
4049 : BnAudioTrack(),
4050 mTrack(track)
4051{
4052}
4053
4054AudioFlinger::TrackHandle::~TrackHandle() {
4055 // just stop the track on deletion, associated resources
4056 // will be freed from the main thread once all pending buffers have
4057 // been played. Unless it's not in the active track list, in which
4058 // case we free everything now...
4059 mTrack->destroy();
4060}
4061
4062status_t AudioFlinger::TrackHandle::start() {
4063 return mTrack->start();
4064}
4065
4066void AudioFlinger::TrackHandle::stop() {
4067 mTrack->stop();
4068}
4069
4070void AudioFlinger::TrackHandle::flush() {
4071 mTrack->flush();
4072}
4073
4074void AudioFlinger::TrackHandle::mute(bool e) {
4075 mTrack->mute(e);
4076}
4077
4078void AudioFlinger::TrackHandle::pause() {
4079 mTrack->pause();
4080}
4081
4082void AudioFlinger::TrackHandle::setVolume(float left, float right) {
4083 mTrack->setVolume(left, right);
4084}
4085
4086sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
4087 return mTrack->getCblk();
4088}
4089
4090status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
4091{
4092 return mTrack->attachAuxEffect(EffectId);
4093}
4094
4095status_t AudioFlinger::TrackHandle::onTransact(
4096 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4097{
4098 return BnAudioTrack::onTransact(code, data, reply, flags);
4099}
4100
4101// ----------------------------------------------------------------------------
4102
4103sp<IAudioRecord> AudioFlinger::openRecord(
4104 pid_t pid,
4105 int input,
4106 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004107 uint32_t format,
4108 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004109 int frameCount,
4110 uint32_t flags,
4111 int *sessionId,
4112 status_t *status)
4113{
4114 sp<RecordThread::RecordTrack> recordTrack;
4115 sp<RecordHandle> recordHandle;
4116 sp<Client> client;
4117 wp<Client> wclient;
4118 status_t lStatus;
4119 RecordThread *thread;
4120 size_t inFrameCount;
4121 int lSessionId;
4122
4123 // check calling permissions
4124 if (!recordingAllowed()) {
4125 lStatus = PERMISSION_DENIED;
4126 goto Exit;
4127 }
4128
4129 // add client to list
4130 { // scope for mLock
4131 Mutex::Autolock _l(mLock);
4132 thread = checkRecordThread_l(input);
4133 if (thread == NULL) {
4134 lStatus = BAD_VALUE;
4135 goto Exit;
4136 }
4137
4138 wclient = mClients.valueFor(pid);
4139 if (wclient != NULL) {
4140 client = wclient.promote();
4141 } else {
4142 client = new Client(this, pid);
4143 mClients.add(pid, client);
4144 }
4145
4146 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07004147 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004148 lSessionId = *sessionId;
4149 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004150 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004151 if (sessionId != NULL) {
4152 *sessionId = lSessionId;
4153 }
4154 }
4155 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004156 recordTrack = thread->createRecordTrack_l(client,
4157 sampleRate,
4158 format,
4159 channelMask,
4160 frameCount,
4161 flags,
4162 lSessionId,
4163 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004165 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166 // remove local strong reference to Client before deleting the RecordTrack so that the Client
4167 // destructor is called by the TrackBase destructor with mLock held
4168 client.clear();
4169 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170 goto Exit;
4171 }
4172
4173 // return to handle to client
4174 recordHandle = new RecordHandle(recordTrack);
4175 lStatus = NO_ERROR;
4176
4177Exit:
4178 if (status) {
4179 *status = lStatus;
4180 }
4181 return recordHandle;
4182}
4183
4184// ----------------------------------------------------------------------------
4185
4186AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
4187 : BnAudioRecord(),
4188 mRecordTrack(recordTrack)
4189{
4190}
4191
4192AudioFlinger::RecordHandle::~RecordHandle() {
4193 stop();
4194}
4195
4196status_t AudioFlinger::RecordHandle::start() {
Steve Block3856b092011-10-20 11:56:00 +01004197 ALOGV("RecordHandle::start()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004198 return mRecordTrack->start();
4199}
4200
4201void AudioFlinger::RecordHandle::stop() {
Steve Block3856b092011-10-20 11:56:00 +01004202 ALOGV("RecordHandle::stop()");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004203 mRecordTrack->stop();
4204}
4205
4206sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4207 return mRecordTrack->getCblk();
4208}
4209
4210status_t AudioFlinger::RecordHandle::onTransact(
4211 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4212{
4213 return BnAudioRecord::onTransact(code, data, reply, flags);
4214}
4215
4216// ----------------------------------------------------------------------------
4217
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004218AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4219 AudioStreamIn *input,
4220 uint32_t sampleRate,
4221 uint32_t channels,
4222 int id,
4223 uint32_t device) :
4224 ThreadBase(audioFlinger, id, device),
Glenn Kastene0feee32011-12-13 11:53:26 -08004225 mInput(input), mTrack(NULL), mResampler(NULL), mRsmpOutBuffer(NULL), mRsmpInBuffer(NULL)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004226{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004227 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004228
4229 snprintf(mName, kNameLength, "AudioIn_%d", id);
4230
Dima Zavinfce7a472011-04-19 22:30:36 -07004231 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004232 mReqSampleRate = sampleRate;
4233 readInputParameters();
4234}
4235
4236
4237AudioFlinger::RecordThread::~RecordThread()
4238{
4239 delete[] mRsmpInBuffer;
Glenn Kastene0feee32011-12-13 11:53:26 -08004240 if (mResampler != NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004241 delete mResampler;
4242 delete[] mRsmpOutBuffer;
4243 }
4244}
4245
4246void AudioFlinger::RecordThread::onFirstRef()
4247{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004248 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249}
4250
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004251status_t AudioFlinger::RecordThread::readyToRun()
4252{
4253 status_t status = initCheck();
4254 LOGW_IF(status != NO_ERROR,"RecordThread %p could not initialize", this);
4255 return status;
4256}
4257
Mathias Agopian65ab4712010-07-14 17:59:35 -07004258bool AudioFlinger::RecordThread::threadLoop()
4259{
4260 AudioBufferProvider::Buffer buffer;
4261 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004262 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004263
Eric Laurent44d98482010-09-30 16:12:31 -07004264 nsecs_t lastWarning = 0;
4265
Eric Laurentfeb0db62011-07-22 09:04:31 -07004266 acquireWakeLock();
4267
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268 // start recording
4269 while (!exitPending()) {
4270
4271 processConfigEvents();
4272
4273 { // scope for mLock
4274 Mutex::Autolock _l(mLock);
4275 checkForNewParameters_l();
4276 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4277 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004278 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004279 mStandby = true;
4280 }
4281
4282 if (exitPending()) break;
4283
Eric Laurentfeb0db62011-07-22 09:04:31 -07004284 releaseWakeLock_l();
Steve Block3856b092011-10-20 11:56:00 +01004285 ALOGV("RecordThread: loop stopping");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004286 // go to sleep
4287 mWaitWorkCV.wait(mLock);
Steve Block3856b092011-10-20 11:56:00 +01004288 ALOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004289 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004290 continue;
4291 }
4292 if (mActiveTrack != 0) {
4293 if (mActiveTrack->mState == TrackBase::PAUSING) {
4294 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004295 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004296 mStandby = true;
4297 }
4298 mActiveTrack.clear();
4299 mStartStopCond.broadcast();
4300 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4301 if (mReqChannelCount != mActiveTrack->channelCount()) {
4302 mActiveTrack.clear();
4303 mStartStopCond.broadcast();
4304 } else if (mBytesRead != 0) {
4305 // record start succeeds only if first read from audio input
4306 // succeeds
4307 if (mBytesRead > 0) {
4308 mActiveTrack->mState = TrackBase::ACTIVE;
4309 } else {
4310 mActiveTrack.clear();
4311 }
4312 mStartStopCond.broadcast();
4313 }
4314 mStandby = false;
4315 }
4316 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004317 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004318 }
4319
4320 if (mActiveTrack != 0) {
4321 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4322 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004323 unlockEffectChains(effectChains);
4324 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004325 continue;
4326 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004327 for (size_t i = 0; i < effectChains.size(); i ++) {
4328 effectChains[i]->process_l();
4329 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004330
Mathias Agopian65ab4712010-07-14 17:59:35 -07004331 buffer.frameCount = mFrameCount;
4332 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4333 size_t framesOut = buffer.frameCount;
Glenn Kastene0feee32011-12-13 11:53:26 -08004334 if (mResampler == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004335 // no resampling
4336 while (framesOut) {
4337 size_t framesIn = mFrameCount - mRsmpInIndex;
4338 if (framesIn) {
4339 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4340 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4341 if (framesIn > framesOut)
4342 framesIn = framesOut;
4343 mRsmpInIndex += framesIn;
4344 framesOut -= framesIn;
4345 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004346 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004347 memcpy(dst, src, framesIn * mFrameSize);
4348 } else {
4349 int16_t *src16 = (int16_t *)src;
4350 int16_t *dst16 = (int16_t *)dst;
4351 if (mChannelCount == 1) {
4352 while (framesIn--) {
4353 *dst16++ = *src16;
4354 *dst16++ = *src16++;
4355 }
4356 } else {
4357 while (framesIn--) {
4358 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4359 src16 += 2;
4360 }
4361 }
4362 }
4363 }
4364 if (framesOut && mFrameCount == mRsmpInIndex) {
4365 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004366 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004367 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004368 framesOut = 0;
4369 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004370 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004371 mRsmpInIndex = 0;
4372 }
4373 if (mBytesRead < 0) {
4374 LOGE("Error reading audio input");
4375 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4376 // Force input into standby so that it tries to
4377 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004378 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004379 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004380 }
4381 mRsmpInIndex = mFrameCount;
4382 framesOut = 0;
4383 buffer.frameCount = 0;
4384 }
4385 }
4386 }
4387 } else {
4388 // resampling
4389
4390 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4391 // alter output frame count as if we were expecting stereo samples
4392 if (mChannelCount == 1 && mReqChannelCount == 1) {
4393 framesOut >>= 1;
4394 }
4395 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4396 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4397 // are 32 bit aligned which should be always true.
4398 if (mChannelCount == 2 && mReqChannelCount == 1) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004399 ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004400 // the resampler always outputs stereo samples: do post stereo to mono conversion
4401 int16_t *src = (int16_t *)mRsmpOutBuffer;
4402 int16_t *dst = buffer.i16;
4403 while (framesOut--) {
4404 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4405 src += 2;
4406 }
4407 } else {
Glenn Kasten3b21c502011-12-15 09:52:39 -08004408 ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004409 }
4410
4411 }
4412 mActiveTrack->releaseBuffer(&buffer);
4413 mActiveTrack->overflow();
4414 }
4415 // client isn't retrieving buffers fast enough
4416 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004417 if (!mActiveTrack->setOverflow()) {
4418 nsecs_t now = systemTime();
Glenn Kasten7dede872011-12-13 11:04:14 -08004419 if ((now - lastWarning) > kWarningThrottleNs) {
Eric Laurent44d98482010-09-30 16:12:31 -07004420 LOGW("RecordThread: buffer overflow");
4421 lastWarning = now;
4422 }
4423 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004424 // Release the processor for a while before asking for a new buffer.
4425 // This will give the application more chance to read from the buffer and
4426 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004427 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428 }
4429 }
Eric Laurentec437d82011-07-26 20:54:46 -07004430 // enable changes in effect chain
4431 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004432 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433 }
4434
4435 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004436 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004437 }
4438 mActiveTrack.clear();
4439
4440 mStartStopCond.broadcast();
4441
Eric Laurentfeb0db62011-07-22 09:04:31 -07004442 releaseWakeLock();
4443
Steve Block3856b092011-10-20 11:56:00 +01004444 ALOGV("RecordThread %p exiting", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004445 return false;
4446}
4447
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004448
4449sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4450 const sp<AudioFlinger::Client>& client,
4451 uint32_t sampleRate,
4452 int format,
4453 int channelMask,
4454 int frameCount,
4455 uint32_t flags,
4456 int sessionId,
4457 status_t *status)
4458{
4459 sp<RecordTrack> track;
4460 status_t lStatus;
4461
4462 lStatus = initCheck();
4463 if (lStatus != NO_ERROR) {
4464 LOGE("Audio driver not initialized.");
4465 goto Exit;
4466 }
4467
4468 { // scope for mLock
4469 Mutex::Autolock _l(mLock);
4470
4471 track = new RecordTrack(this, client, sampleRate,
4472 format, channelMask, frameCount, flags, sessionId);
4473
4474 if (track->getCblk() == NULL) {
4475 lStatus = NO_MEMORY;
4476 goto Exit;
4477 }
4478
4479 mTrack = track.get();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004480 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4481 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004482 (audio_devices_t)(mDevice & AUDIO_DEVICE_IN_ALL)) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004483 setEffectSuspended_l(FX_IID_AEC, suspend, sessionId);
4484 setEffectSuspended_l(FX_IID_NS, suspend, sessionId);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004485 }
4486 lStatus = NO_ERROR;
4487
4488Exit:
4489 if (status) {
4490 *status = lStatus;
4491 }
4492 return track;
4493}
4494
Mathias Agopian65ab4712010-07-14 17:59:35 -07004495status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4496{
Steve Block3856b092011-10-20 11:56:00 +01004497 ALOGV("RecordThread::start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498 sp <ThreadBase> strongMe = this;
4499 status_t status = NO_ERROR;
4500 {
4501 AutoMutex lock(&mLock);
4502 if (mActiveTrack != 0) {
4503 if (recordTrack != mActiveTrack.get()) {
4504 status = -EBUSY;
4505 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4506 mActiveTrack->mState = TrackBase::ACTIVE;
4507 }
4508 return status;
4509 }
4510
4511 recordTrack->mState = TrackBase::IDLE;
4512 mActiveTrack = recordTrack;
4513 mLock.unlock();
4514 status_t status = AudioSystem::startInput(mId);
4515 mLock.lock();
4516 if (status != NO_ERROR) {
4517 mActiveTrack.clear();
4518 return status;
4519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004520 mRsmpInIndex = mFrameCount;
4521 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004522 if (mResampler != NULL) {
4523 mResampler->reset();
4524 }
4525 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004526 // signal thread to start
Steve Block3856b092011-10-20 11:56:00 +01004527 ALOGV("Signal record thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004528 mWaitWorkCV.signal();
4529 // do not wait for mStartStopCond if exiting
4530 if (mExiting) {
4531 mActiveTrack.clear();
4532 status = INVALID_OPERATION;
4533 goto startError;
4534 }
4535 mStartStopCond.wait(mLock);
4536 if (mActiveTrack == 0) {
Steve Block3856b092011-10-20 11:56:00 +01004537 ALOGV("Record failed to start");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004538 status = BAD_VALUE;
4539 goto startError;
4540 }
Steve Block3856b092011-10-20 11:56:00 +01004541 ALOGV("Record started OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004542 return status;
4543 }
4544startError:
4545 AudioSystem::stopInput(mId);
4546 return status;
4547}
4548
4549void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Steve Block3856b092011-10-20 11:56:00 +01004550 ALOGV("RecordThread::stop");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004551 sp <ThreadBase> strongMe = this;
4552 {
4553 AutoMutex lock(&mLock);
4554 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4555 mActiveTrack->mState = TrackBase::PAUSING;
4556 // do not wait for mStartStopCond if exiting
4557 if (mExiting) {
4558 return;
4559 }
4560 mStartStopCond.wait(mLock);
4561 // if we have been restarted, recordTrack == mActiveTrack.get() here
4562 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4563 mLock.unlock();
4564 AudioSystem::stopInput(mId);
4565 mLock.lock();
Steve Block3856b092011-10-20 11:56:00 +01004566 ALOGV("Record stopped OK");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004567 }
4568 }
4569 }
4570}
4571
4572status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4573{
4574 const size_t SIZE = 256;
4575 char buffer[SIZE];
4576 String8 result;
4577 pid_t pid = 0;
4578
4579 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4580 result.append(buffer);
4581
4582 if (mActiveTrack != 0) {
4583 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004584 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004585 mActiveTrack->dump(buffer, SIZE);
4586 result.append(buffer);
4587
4588 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4589 result.append(buffer);
4590 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4591 result.append(buffer);
Glenn Kastene0feee32011-12-13 11:53:26 -08004592 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != NULL));
Mathias Agopian65ab4712010-07-14 17:59:35 -07004593 result.append(buffer);
4594 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4595 result.append(buffer);
4596 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4597 result.append(buffer);
4598
4599
4600 } else {
4601 result.append("No record client\n");
4602 }
4603 write(fd, result.string(), result.size());
4604
4605 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004606 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004607
4608 return NO_ERROR;
4609}
4610
4611status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4612{
4613 size_t framesReq = buffer->frameCount;
4614 size_t framesReady = mFrameCount - mRsmpInIndex;
4615 int channelCount;
4616
4617 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004618 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004619 if (mBytesRead < 0) {
4620 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4621 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4622 // Force input into standby so that it tries to
4623 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004624 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004625 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004626 }
Glenn Kastene0feee32011-12-13 11:53:26 -08004627 buffer->raw = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004628 buffer->frameCount = 0;
4629 return NOT_ENOUGH_DATA;
4630 }
4631 mRsmpInIndex = 0;
4632 framesReady = mFrameCount;
4633 }
4634
4635 if (framesReq > framesReady) {
4636 framesReq = framesReady;
4637 }
4638
4639 if (mChannelCount == 1 && mReqChannelCount == 2) {
4640 channelCount = 1;
4641 } else {
4642 channelCount = 2;
4643 }
4644 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4645 buffer->frameCount = framesReq;
4646 return NO_ERROR;
4647}
4648
4649void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4650{
4651 mRsmpInIndex += buffer->frameCount;
4652 buffer->frameCount = 0;
4653}
4654
4655bool AudioFlinger::RecordThread::checkForNewParameters_l()
4656{
4657 bool reconfig = false;
4658
4659 while (!mNewParameters.isEmpty()) {
4660 status_t status = NO_ERROR;
4661 String8 keyValuePair = mNewParameters[0];
4662 AudioParameter param = AudioParameter(keyValuePair);
4663 int value;
4664 int reqFormat = mFormat;
4665 int reqSamplingRate = mReqSampleRate;
4666 int reqChannelCount = mReqChannelCount;
4667
4668 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4669 reqSamplingRate = value;
4670 reconfig = true;
4671 }
4672 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4673 reqFormat = value;
4674 reconfig = true;
4675 }
4676 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004677 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004678 reconfig = true;
4679 }
4680 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4681 // do not accept frame count changes if tracks are open as the track buffer
4682 // size depends on frame count and correct behavior would not be garantied
4683 // if frame count is changed after track creation
4684 if (mActiveTrack != 0) {
4685 status = INVALID_OPERATION;
4686 } else {
4687 reconfig = true;
4688 }
4689 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004690 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4691 // forward device change to effects that have requested to be
4692 // aware of attached audio device.
4693 for (size_t i = 0; i < mEffectChains.size(); i++) {
4694 mEffectChains[i]->setDevice_l(value);
4695 }
4696 // store input device and output device but do not forward output device to audio HAL.
4697 // Note that status is ignored by the caller for output device
4698 // (see AudioFlinger::setParameters()
4699 if (value & AUDIO_DEVICE_OUT_ALL) {
4700 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4701 status = BAD_VALUE;
4702 } else {
4703 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
Eric Laurent59bd0da2011-08-01 09:52:20 -07004704 // disable AEC and NS if the device is a BT SCO headset supporting those pre processings
4705 if (mTrack != NULL) {
4706 bool suspend = audio_is_bluetooth_sco_device(
Eric Laurentbee53372011-08-29 12:42:48 -07004707 (audio_devices_t)value) && mAudioFlinger->btNrecIsOff();
Eric Laurent59bd0da2011-08-01 09:52:20 -07004708 setEffectSuspended_l(FX_IID_AEC, suspend, mTrack->sessionId());
4709 setEffectSuspended_l(FX_IID_NS, suspend, mTrack->sessionId());
4710 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004711 }
4712 mDevice |= (uint32_t)value;
4713 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004714 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004715 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004716 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004717 mInput->stream->common.standby(&mInput->stream->common);
4718 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004719 }
4720 if (reconfig) {
4721 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004722 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004723 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004724 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4725 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004726 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004727 status = NO_ERROR;
4728 }
4729 if (status == NO_ERROR) {
4730 readInputParameters();
4731 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4732 }
4733 }
4734 }
4735
4736 mNewParameters.removeAt(0);
4737
4738 mParamStatus = status;
4739 mParamCond.signal();
Eric Laurent60cd0a02011-09-13 11:40:21 -07004740 // wait for condition with time out in case the thread calling ThreadBase::setParameters()
4741 // already timed out waiting for the status and will never signal the condition.
Glenn Kasten7dede872011-12-13 11:04:14 -08004742 mWaitWorkCV.waitRelative(mLock, kSetParametersTimeoutNs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004743 }
4744 return reconfig;
4745}
4746
4747String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4748{
Dima Zavinfce7a472011-04-19 22:30:36 -07004749 char *s;
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004750 String8 out_s8 = String8();
4751
4752 Mutex::Autolock _l(mLock);
4753 if (initCheck() != NO_ERROR) {
4754 return out_s8;
4755 }
Dima Zavinfce7a472011-04-19 22:30:36 -07004756
Dima Zavin799a70e2011-04-18 16:57:27 -07004757 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004758 out_s8 = String8(s);
4759 free(s);
4760 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004761}
4762
4763void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4764 AudioSystem::OutputDescriptor desc;
4765 void *param2 = 0;
4766
4767 switch (event) {
4768 case AudioSystem::INPUT_OPENED:
4769 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004770 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004771 desc.samplingRate = mSampleRate;
4772 desc.format = mFormat;
4773 desc.frameCount = mFrameCount;
4774 desc.latency = 0;
4775 param2 = &desc;
4776 break;
4777
4778 case AudioSystem::INPUT_CLOSED:
4779 default:
4780 break;
4781 }
4782 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4783}
4784
4785void AudioFlinger::RecordThread::readInputParameters()
4786{
4787 if (mRsmpInBuffer) delete mRsmpInBuffer;
4788 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4789 if (mResampler) delete mResampler;
Glenn Kastene0feee32011-12-13 11:53:26 -08004790 mResampler = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004791
Dima Zavin799a70e2011-04-18 16:57:27 -07004792 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004793 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4794 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004795 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4796 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4797 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004798 mFrameCount = mInputBytes / mFrameSize;
4799 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4800
4801 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4802 {
4803 int channelCount;
4804 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4805 // stereo to mono post process as the resampler always outputs stereo.
4806 if (mChannelCount == 1 && mReqChannelCount == 2) {
4807 channelCount = 1;
4808 } else {
4809 channelCount = 2;
4810 }
4811 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4812 mResampler->setSampleRate(mSampleRate);
4813 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4814 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4815
4816 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4817 if (mChannelCount == 1 && mReqChannelCount == 1) {
4818 mFrameCount >>= 1;
4819 }
4820
4821 }
4822 mRsmpInIndex = mFrameCount;
4823}
4824
4825unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4826{
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004827 Mutex::Autolock _l(mLock);
4828 if (initCheck() != NO_ERROR) {
4829 return 0;
4830 }
4831
Dima Zavin799a70e2011-04-18 16:57:27 -07004832 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004833}
4834
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004835uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4836{
4837 Mutex::Autolock _l(mLock);
4838 uint32_t result = 0;
4839 if (getEffectChain_l(sessionId) != 0) {
4840 result = EFFECT_SESSION;
4841 }
4842
4843 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4844 result |= TRACK_SESSION;
4845 }
4846
4847 return result;
4848}
4849
Eric Laurent59bd0da2011-08-01 09:52:20 -07004850AudioFlinger::RecordThread::RecordTrack* AudioFlinger::RecordThread::track()
4851{
4852 Mutex::Autolock _l(mLock);
4853 return mTrack;
4854}
4855
Eric Laurentb8ba0a92011-08-07 16:32:26 -07004856AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::getInput()
4857{
4858 Mutex::Autolock _l(mLock);
4859 return mInput;
4860}
4861
4862AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
4863{
4864 Mutex::Autolock _l(mLock);
4865 AudioStreamIn *input = mInput;
4866 mInput = NULL;
4867 return input;
4868}
4869
4870// this method must always be called either with ThreadBase mLock held or inside the thread loop
4871audio_stream_t* AudioFlinger::RecordThread::stream()
4872{
4873 if (mInput == NULL) {
4874 return NULL;
4875 }
4876 return &mInput->stream->common;
4877}
4878
4879
Mathias Agopian65ab4712010-07-14 17:59:35 -07004880// ----------------------------------------------------------------------------
4881
4882int AudioFlinger::openOutput(uint32_t *pDevices,
4883 uint32_t *pSamplingRate,
4884 uint32_t *pFormat,
4885 uint32_t *pChannels,
4886 uint32_t *pLatencyMs,
4887 uint32_t flags)
4888{
4889 status_t status;
4890 PlaybackThread *thread = NULL;
4891 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4892 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4893 uint32_t format = pFormat ? *pFormat : 0;
4894 uint32_t channels = pChannels ? *pChannels : 0;
4895 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004896 audio_stream_out_t *outStream;
4897 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004898
Steve Block3856b092011-10-20 11:56:00 +01004899 ALOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
Mathias Agopian65ab4712010-07-14 17:59:35 -07004900 pDevices ? *pDevices : 0,
4901 samplingRate,
4902 format,
4903 channels,
4904 flags);
4905
4906 if (pDevices == NULL || *pDevices == 0) {
4907 return 0;
4908 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004909
Mathias Agopian65ab4712010-07-14 17:59:35 -07004910 Mutex::Autolock _l(mLock);
4911
Dima Zavin799a70e2011-04-18 16:57:27 -07004912 outHwDev = findSuitableHwDev_l(*pDevices);
4913 if (outHwDev == NULL)
4914 return 0;
4915
4916 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4917 &channels, &samplingRate, &outStream);
Steve Block3856b092011-10-20 11:56:00 +01004918 ALOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004919 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004920 samplingRate,
4921 format,
4922 channels,
4923 status);
4924
4925 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004926 if (outStream != NULL) {
4927 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004928 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004929
Dima Zavinfce7a472011-04-19 22:30:36 -07004930 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4931 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4932 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004933 thread = new DirectOutputThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004934 ALOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004935 } else {
4936 thread = new MixerThread(this, output, id, *pDevices);
Steve Block3856b092011-10-20 11:56:00 +01004937 ALOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004938 }
4939 mPlaybackThreads.add(id, thread);
4940
4941 if (pSamplingRate) *pSamplingRate = samplingRate;
4942 if (pFormat) *pFormat = format;
4943 if (pChannels) *pChannels = channels;
4944 if (pLatencyMs) *pLatencyMs = thread->latency();
4945
4946 // notify client processes of the new output creation
4947 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4948 return id;
4949 }
4950
4951 return 0;
4952}
4953
4954int AudioFlinger::openDuplicateOutput(int output1, int output2)
4955{
4956 Mutex::Autolock _l(mLock);
4957 MixerThread *thread1 = checkMixerThread_l(output1);
4958 MixerThread *thread2 = checkMixerThread_l(output2);
4959
4960 if (thread1 == NULL || thread2 == NULL) {
4961 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4962 return 0;
4963 }
4964
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004965 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004966 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4967 thread->addOutputTrack(thread2);
4968 mPlaybackThreads.add(id, thread);
4969 // notify client processes of the new output creation
4970 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4971 return id;
4972}
4973
4974status_t AudioFlinger::closeOutput(int output)
4975{
4976 // keep strong reference on the playback thread so that
4977 // it is not destroyed while exit() is executed
4978 sp <PlaybackThread> thread;
4979 {
4980 Mutex::Autolock _l(mLock);
4981 thread = checkPlaybackThread_l(output);
4982 if (thread == NULL) {
4983 return BAD_VALUE;
4984 }
4985
Steve Block3856b092011-10-20 11:56:00 +01004986 ALOGV("closeOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004988 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004989 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004990 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004991 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4992 dupThread->removeOutputTrack((MixerThread *)thread.get());
4993 }
4994 }
4995 }
4996 void *param2 = 0;
4997 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4998 mPlaybackThreads.removeItem(output);
4999 }
5000 thread->exit();
5001
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005002 if (thread->type() != ThreadBase::DUPLICATING) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005003 AudioStreamOut *out = thread->clearOutput();
5004 // from now on thread->mOutput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005005 out->hwDev->close_output_stream(out->hwDev, out->stream);
5006 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005007 }
5008 return NO_ERROR;
5009}
5010
5011status_t AudioFlinger::suspendOutput(int output)
5012{
5013 Mutex::Autolock _l(mLock);
5014 PlaybackThread *thread = checkPlaybackThread_l(output);
5015
5016 if (thread == NULL) {
5017 return BAD_VALUE;
5018 }
5019
Steve Block3856b092011-10-20 11:56:00 +01005020 ALOGV("suspendOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005021 thread->suspend();
5022
5023 return NO_ERROR;
5024}
5025
5026status_t AudioFlinger::restoreOutput(int output)
5027{
5028 Mutex::Autolock _l(mLock);
5029 PlaybackThread *thread = checkPlaybackThread_l(output);
5030
5031 if (thread == NULL) {
5032 return BAD_VALUE;
5033 }
5034
Steve Block3856b092011-10-20 11:56:00 +01005035 ALOGV("restoreOutput() %d", output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005036
5037 thread->restore();
5038
5039 return NO_ERROR;
5040}
5041
5042int AudioFlinger::openInput(uint32_t *pDevices,
5043 uint32_t *pSamplingRate,
5044 uint32_t *pFormat,
5045 uint32_t *pChannels,
5046 uint32_t acoustics)
5047{
5048 status_t status;
5049 RecordThread *thread = NULL;
5050 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
5051 uint32_t format = pFormat ? *pFormat : 0;
5052 uint32_t channels = pChannels ? *pChannels : 0;
5053 uint32_t reqSamplingRate = samplingRate;
5054 uint32_t reqFormat = format;
5055 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07005056 audio_stream_in_t *inStream;
5057 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005058
5059 if (pDevices == NULL || *pDevices == 0) {
5060 return 0;
5061 }
Dima Zavin799a70e2011-04-18 16:57:27 -07005062
Mathias Agopian65ab4712010-07-14 17:59:35 -07005063 Mutex::Autolock _l(mLock);
5064
Dima Zavin799a70e2011-04-18 16:57:27 -07005065 inHwDev = findSuitableHwDev_l(*pDevices);
5066 if (inHwDev == NULL)
5067 return 0;
5068
5069 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5070 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005071 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005072 &inStream);
Steve Block3856b092011-10-20 11:56:00 +01005073 ALOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07005074 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005075 samplingRate,
5076 format,
5077 channels,
5078 acoustics,
5079 status);
5080
5081 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
5082 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
5083 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07005084 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005085 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005086 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07005087 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Steve Block3856b092011-10-20 11:56:00 +01005088 ALOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07005089 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
5090 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07005091 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07005092 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005093 }
5094
Dima Zavin799a70e2011-04-18 16:57:27 -07005095 if (inStream != NULL) {
5096 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
5097
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005098 int id = nextUniqueId();
5099 // Start record thread
5100 // RecorThread require both input and output device indication to forward to audio
5101 // pre processing modules
5102 uint32_t device = (*pDevices) | primaryOutputDevice_l();
5103 thread = new RecordThread(this,
5104 input,
5105 reqSamplingRate,
5106 reqChannels,
5107 id,
5108 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005109 mRecordThreads.add(id, thread);
Steve Block3856b092011-10-20 11:56:00 +01005110 ALOGV("openInput() created record thread: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005111 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
5112 if (pFormat) *pFormat = format;
5113 if (pChannels) *pChannels = reqChannels;
5114
Dima Zavin799a70e2011-04-18 16:57:27 -07005115 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116
5117 // notify client processes of the new input creation
5118 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
5119 return id;
5120 }
5121
5122 return 0;
5123}
5124
5125status_t AudioFlinger::closeInput(int input)
5126{
5127 // keep strong reference on the record thread so that
5128 // it is not destroyed while exit() is executed
5129 sp <RecordThread> thread;
5130 {
5131 Mutex::Autolock _l(mLock);
5132 thread = checkRecordThread_l(input);
5133 if (thread == NULL) {
5134 return BAD_VALUE;
5135 }
5136
Steve Block3856b092011-10-20 11:56:00 +01005137 ALOGV("closeInput() %d", input);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 void *param2 = 0;
5139 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
5140 mRecordThreads.removeItem(input);
5141 }
5142 thread->exit();
5143
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005144 AudioStreamIn *in = thread->clearInput();
5145 // from now on thread->mInput is NULL
Dima Zavin799a70e2011-04-18 16:57:27 -07005146 in->hwDev->close_input_stream(in->hwDev, in->stream);
5147 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148
5149 return NO_ERROR;
5150}
5151
5152status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
5153{
5154 Mutex::Autolock _l(mLock);
5155 MixerThread *dstThread = checkMixerThread_l(output);
5156 if (dstThread == NULL) {
5157 LOGW("setStreamOutput() bad output id %d", output);
5158 return BAD_VALUE;
5159 }
5160
Steve Block3856b092011-10-20 11:56:00 +01005161 ALOGV("setStreamOutput() stream %d to output %d", stream, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
5163
Eric Laurent9f6530f2011-08-30 10:18:54 -07005164 dstThread->setStreamValid(stream, true);
5165
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5167 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
5168 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005169 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005170 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurent9f6530f2011-08-30 10:18:54 -07005171 srcThread->setStreamValid(stream, false);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005172 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173 }
Eric Laurentde070132010-07-13 04:45:46 -07005174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175
5176 return NO_ERROR;
5177}
5178
5179
5180int AudioFlinger::newAudioSessionId()
5181{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005182 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005183}
5184
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005185void AudioFlinger::acquireAudioSessionId(int audioSession)
5186{
5187 Mutex::Autolock _l(mLock);
5188 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005189 ALOGV("acquiring %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005190 int num = mAudioSessionRefs.size();
5191 for (int i = 0; i< num; i++) {
5192 AudioSessionRef *ref = mAudioSessionRefs.editItemAt(i);
5193 if (ref->sessionid == audioSession && ref->pid == caller) {
5194 ref->cnt++;
Steve Block3856b092011-10-20 11:56:00 +01005195 ALOGV(" incremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005196 return;
5197 }
5198 }
5199 AudioSessionRef *ref = new AudioSessionRef();
5200 ref->sessionid = audioSession;
5201 ref->pid = caller;
5202 ref->cnt = 1;
5203 mAudioSessionRefs.push(ref);
Steve Block3856b092011-10-20 11:56:00 +01005204 ALOGV(" added new entry for %d", ref->sessionid);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005205}
5206
5207void AudioFlinger::releaseAudioSessionId(int audioSession)
5208{
5209 Mutex::Autolock _l(mLock);
5210 int caller = IPCThreadState::self()->getCallingPid();
Steve Block3856b092011-10-20 11:56:00 +01005211 ALOGV("releasing %d from %d", audioSession, caller);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005212 int num = mAudioSessionRefs.size();
5213 for (int i = 0; i< num; i++) {
5214 AudioSessionRef *ref = mAudioSessionRefs.itemAt(i);
5215 if (ref->sessionid == audioSession && ref->pid == caller) {
5216 ref->cnt--;
Steve Block3856b092011-10-20 11:56:00 +01005217 ALOGV(" decremented refcount to %d", ref->cnt);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005218 if (ref->cnt == 0) {
5219 mAudioSessionRefs.removeAt(i);
5220 delete ref;
5221 purgeStaleEffects_l();
5222 }
5223 return;
5224 }
5225 }
5226 LOGW("session id %d not found for pid %d", audioSession, caller);
5227}
5228
5229void AudioFlinger::purgeStaleEffects_l() {
5230
Steve Block3856b092011-10-20 11:56:00 +01005231 ALOGV("purging stale effects");
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005232
5233 Vector< sp<EffectChain> > chains;
5234
5235 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5236 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
5237 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5238 sp<EffectChain> ec = t->mEffectChains[j];
Marco Nelissen0270b182011-08-12 14:14:39 -07005239 if (ec->sessionId() > AUDIO_SESSION_OUTPUT_MIX) {
5240 chains.push(ec);
5241 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005242 }
5243 }
5244 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5245 sp<RecordThread> t = mRecordThreads.valueAt(i);
5246 for (size_t j = 0; j < t->mEffectChains.size(); j++) {
5247 sp<EffectChain> ec = t->mEffectChains[j];
5248 chains.push(ec);
5249 }
5250 }
5251
5252 for (size_t i = 0; i < chains.size(); i++) {
5253 sp<EffectChain> ec = chains[i];
5254 int sessionid = ec->sessionId();
5255 sp<ThreadBase> t = ec->mThread.promote();
5256 if (t == 0) {
5257 continue;
5258 }
5259 size_t numsessionrefs = mAudioSessionRefs.size();
5260 bool found = false;
5261 for (size_t k = 0; k < numsessionrefs; k++) {
5262 AudioSessionRef *ref = mAudioSessionRefs.itemAt(k);
5263 if (ref->sessionid == sessionid) {
Steve Block3856b092011-10-20 11:56:00 +01005264 ALOGV(" session %d still exists for %d with %d refs",
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005265 sessionid, ref->pid, ref->cnt);
5266 found = true;
5267 break;
5268 }
5269 }
5270 if (!found) {
5271 // remove all effects from the chain
5272 while (ec->mEffects.size()) {
5273 sp<EffectModule> effect = ec->mEffects[0];
5274 effect->unPin();
5275 Mutex::Autolock _l (t->mLock);
5276 t->removeEffect_l(effect);
5277 for (size_t j = 0; j < effect->mHandles.size(); j++) {
5278 sp<EffectHandle> handle = effect->mHandles[j].promote();
5279 if (handle != 0) {
5280 handle->mEffect.clear();
Eric Laurenta85a74a2011-10-19 11:44:54 -07005281 if (handle->mHasControl && handle->mEnabled) {
5282 t->checkSuspendOnEffectEnabled_l(effect, false, effect->sessionId());
5283 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005284 }
5285 }
5286 AudioSystem::unregisterEffect(effect->id());
5287 }
5288 }
5289 }
5290 return;
5291}
5292
Mathias Agopian65ab4712010-07-14 17:59:35 -07005293// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
5294AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
5295{
5296 PlaybackThread *thread = NULL;
5297 if (mPlaybackThreads.indexOfKey(output) >= 0) {
5298 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
5299 }
5300 return thread;
5301}
5302
5303// checkMixerThread_l() must be called with AudioFlinger::mLock held
5304AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
5305{
5306 PlaybackThread *thread = checkPlaybackThread_l(output);
5307 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005308 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005309 thread = NULL;
5310 }
5311 }
5312 return (MixerThread *)thread;
5313}
5314
5315// checkRecordThread_l() must be called with AudioFlinger::mLock held
5316AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
5317{
5318 RecordThread *thread = NULL;
5319 if (mRecordThreads.indexOfKey(input) >= 0) {
5320 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
5321 }
5322 return thread;
5323}
5324
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005325uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07005326{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005327 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328}
5329
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005330AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
5331{
5332 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5333 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurentb8ba0a92011-08-07 16:32:26 -07005334 AudioStreamOut *output = thread->getOutput();
5335 if (output != NULL && output->hwDev == mPrimaryHardwareDev) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005336 return thread;
5337 }
5338 }
5339 return NULL;
5340}
5341
5342uint32_t AudioFlinger::primaryOutputDevice_l()
5343{
5344 PlaybackThread *thread = primaryPlaybackThread_l();
5345
5346 if (thread == NULL) {
5347 return 0;
5348 }
5349
5350 return thread->device();
5351}
5352
5353
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354// ----------------------------------------------------------------------------
5355// Effect management
5356// ----------------------------------------------------------------------------
5357
5358
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
5360{
5361 Mutex::Autolock _l(mLock);
5362 return EffectQueryNumberEffects(numEffects);
5363}
5364
5365status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
5366{
5367 Mutex::Autolock _l(mLock);
5368 return EffectQueryEffect(index, descriptor);
5369}
5370
5371status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5372{
5373 Mutex::Autolock _l(mLock);
5374 return EffectGetDescriptor(pUuid, descriptor);
5375}
5376
5377
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5379 effect_descriptor_t *pDesc,
5380 const sp<IEffectClient>& effectClient,
5381 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005382 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 int sessionId,
5384 status_t *status,
5385 int *id,
5386 int *enabled)
5387{
5388 status_t lStatus = NO_ERROR;
5389 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005390 effect_descriptor_t desc;
5391 sp<Client> client;
5392 wp<Client> wclient;
5393
Steve Block3856b092011-10-20 11:56:00 +01005394 ALOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005395 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005396
5397 if (pDesc == NULL) {
5398 lStatus = BAD_VALUE;
5399 goto Exit;
5400 }
5401
Eric Laurent84e9a102010-09-23 16:10:16 -07005402 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005403 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005404 lStatus = PERMISSION_DENIED;
5405 goto Exit;
5406 }
5407
Dima Zavinfce7a472011-04-19 22:30:36 -07005408 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005409 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005410 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005411 lStatus = PERMISSION_DENIED;
5412 goto Exit;
5413 }
5414
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005415 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005416 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005417 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005418 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005419 lStatus = BAD_VALUE;
5420 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005421 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005422 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005423 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005424 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005425 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005426 }
5427 }
5428
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 {
5430 Mutex::Autolock _l(mLock);
5431
Mathias Agopian65ab4712010-07-14 17:59:35 -07005432
5433 if (!EffectIsNullUuid(&pDesc->uuid)) {
5434 // if uuid is specified, request effect descriptor
5435 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5436 if (lStatus < 0) {
5437 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5438 goto Exit;
5439 }
5440 } else {
5441 // if uuid is not specified, look for an available implementation
5442 // of the required type in effect factory
5443 if (EffectIsNullUuid(&pDesc->type)) {
5444 LOGW("createEffect() no effect type");
5445 lStatus = BAD_VALUE;
5446 goto Exit;
5447 }
5448 uint32_t numEffects = 0;
5449 effect_descriptor_t d;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005450 d.flags = 0; // prevent compiler warning
Mathias Agopian65ab4712010-07-14 17:59:35 -07005451 bool found = false;
5452
5453 lStatus = EffectQueryNumberEffects(&numEffects);
5454 if (lStatus < 0) {
5455 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5456 goto Exit;
5457 }
5458 for (uint32_t i = 0; i < numEffects; i++) {
5459 lStatus = EffectQueryEffect(i, &desc);
5460 if (lStatus < 0) {
5461 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5462 continue;
5463 }
5464 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5465 // If matching type found save effect descriptor. If the session is
5466 // 0 and the effect is not auxiliary, continue enumeration in case
5467 // an auxiliary version of this effect type is available
5468 found = true;
5469 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005470 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005471 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5472 break;
5473 }
5474 }
5475 }
5476 if (!found) {
5477 lStatus = BAD_VALUE;
5478 LOGW("createEffect() effect not found");
5479 goto Exit;
5480 }
5481 // For same effect type, chose auxiliary version over insert version if
5482 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005483 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005484 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5485 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5486 }
5487 }
5488
5489 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005490 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005491 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5492 lStatus = INVALID_OPERATION;
5493 goto Exit;
5494 }
5495
Eric Laurent59255e42011-07-27 19:49:51 -07005496 // check recording permission for visualizer
5497 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5498 !recordingAllowed()) {
5499 lStatus = PERMISSION_DENIED;
5500 goto Exit;
5501 }
5502
Mathias Agopian65ab4712010-07-14 17:59:35 -07005503 // return effect descriptor
5504 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5505
5506 // If output is not specified try to find a matching audio session ID in one of the
5507 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005508 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5509 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005510 // Note: io is never 0 when creating an effect on an input
5511 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005512 // look for the thread where the specified audio session is present
5513 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5514 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005515 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005516 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005517 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005519 if (io == 0) {
5520 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5521 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5522 io = mRecordThreads.keyAt(i);
5523 break;
5524 }
5525 }
5526 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005527 // If no output thread contains the requested session ID, default to
5528 // first output. The effect chain will be moved to the correct output
5529 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005530 if (io == 0 && mPlaybackThreads.size()) {
5531 io = mPlaybackThreads.keyAt(0);
5532 }
Steve Block3856b092011-10-20 11:56:00 +01005533 ALOGV("createEffect() got io %d for effect %s", io, desc.name);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005534 }
5535 ThreadBase *thread = checkRecordThread_l(io);
5536 if (thread == NULL) {
5537 thread = checkPlaybackThread_l(io);
5538 if (thread == NULL) {
5539 LOGE("createEffect() unknown output thread");
5540 lStatus = BAD_VALUE;
5541 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005542 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005543 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005544
Mathias Agopian65ab4712010-07-14 17:59:35 -07005545 wclient = mClients.valueFor(pid);
5546
5547 if (wclient != NULL) {
5548 client = wclient.promote();
5549 } else {
5550 client = new Client(this, pid);
5551 mClients.add(pid, client);
5552 }
5553
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005554 // create effect on selected output thread
Eric Laurentde070132010-07-13 04:45:46 -07005555 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5556 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005557 if (handle != 0 && id != NULL) {
5558 *id = handle->id();
5559 }
5560 }
5561
5562Exit:
5563 if(status) {
5564 *status = lStatus;
5565 }
5566 return handle;
5567}
5568
Eric Laurent59255e42011-07-27 19:49:51 -07005569status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005570{
Steve Block3856b092011-10-20 11:56:00 +01005571 ALOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005572 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005573 Mutex::Autolock _l(mLock);
5574 if (srcOutput == dstOutput) {
5575 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5576 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005577 }
Eric Laurentde070132010-07-13 04:45:46 -07005578 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5579 if (srcThread == NULL) {
5580 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5581 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005582 }
Eric Laurentde070132010-07-13 04:45:46 -07005583 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5584 if (dstThread == NULL) {
5585 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5586 return BAD_VALUE;
5587 }
5588
5589 Mutex::Autolock _dl(dstThread->mLock);
5590 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005591 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005592
Mathias Agopian65ab4712010-07-14 17:59:35 -07005593 return NO_ERROR;
5594}
5595
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005596// moveEffectChain_l must be called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005597status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005598 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005599 AudioFlinger::PlaybackThread *dstThread,
5600 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005601{
Steve Block3856b092011-10-20 11:56:00 +01005602 ALOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005603 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005604
Eric Laurent59255e42011-07-27 19:49:51 -07005605 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005606 if (chain == 0) {
5607 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005608 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005609 return INVALID_OPERATION;
5610 }
5611
Eric Laurent39e94f82010-07-28 01:32:47 -07005612 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005613 // so that a new chain is created with correct parameters when first effect is added. This is
Eric Laurentec35a142011-10-05 17:42:25 -07005614 // otherwise unnecessary as removeEffect_l() will remove the chain when last effect is
Eric Laurentde070132010-07-13 04:45:46 -07005615 // removed.
5616 srcThread->removeEffectChain_l(chain);
5617
5618 // transfer all effects one by one so that new effect chain is created on new thread with
5619 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005620 int dstOutput = dstThread->id();
5621 sp<EffectChain> dstChain;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005622 uint32_t strategy = 0; // prevent compiler warning
Eric Laurentde070132010-07-13 04:45:46 -07005623 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5624 while (effect != 0) {
5625 srcThread->removeEffect_l(effect);
5626 dstThread->addEffect_l(effect);
Eric Laurentec35a142011-10-05 17:42:25 -07005627 // removeEffect_l() has stopped the effect if it was active so it must be restarted
5628 if (effect->state() == EffectModule::ACTIVE ||
5629 effect->state() == EffectModule::STOPPING) {
5630 effect->start();
5631 }
Eric Laurent39e94f82010-07-28 01:32:47 -07005632 // if the move request is not received from audio policy manager, the effect must be
5633 // re-registered with the new strategy and output
5634 if (dstChain == 0) {
5635 dstChain = effect->chain().promote();
5636 if (dstChain == 0) {
5637 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5638 srcThread->addEffect_l(effect);
5639 return NO_INIT;
5640 }
5641 strategy = dstChain->strategy();
5642 }
5643 if (reRegister) {
5644 AudioSystem::unregisterEffect(effect->id());
5645 AudioSystem::registerEffect(&effect->desc(),
5646 dstOutput,
5647 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005648 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005649 effect->id());
5650 }
Eric Laurentde070132010-07-13 04:45:46 -07005651 effect = chain->getEffectFromId_l(0);
5652 }
5653
5654 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005655}
5656
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005657
Mathias Agopian65ab4712010-07-14 17:59:35 -07005658// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005659sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005660 const sp<AudioFlinger::Client>& client,
5661 const sp<IEffectClient>& effectClient,
5662 int32_t priority,
5663 int sessionId,
5664 effect_descriptor_t *desc,
5665 int *enabled,
5666 status_t *status
5667 )
5668{
5669 sp<EffectModule> effect;
5670 sp<EffectHandle> handle;
5671 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005672 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005673 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005674 bool effectCreated = false;
5675 bool effectRegistered = false;
5676
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005677 lStatus = initCheck();
5678 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005679 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005680 goto Exit;
5681 }
5682
5683 // Do not allow effects with session ID 0 on direct output or duplicating threads
5684 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005685 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005686 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5687 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005688 lStatus = BAD_VALUE;
5689 goto Exit;
5690 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005691 // Only Pre processor effects are allowed on input threads and only on input threads
5692 if ((mType == RECORD &&
5693 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5694 (mType != RECORD &&
5695 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5696 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5697 desc->name, desc->flags, mType);
5698 lStatus = BAD_VALUE;
5699 goto Exit;
5700 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005701
Steve Block3856b092011-10-20 11:56:00 +01005702 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005703
5704 { // scope for mLock
5705 Mutex::Autolock _l(mLock);
5706
5707 // check for existing effect chain with the requested audio session
5708 chain = getEffectChain_l(sessionId);
5709 if (chain == 0) {
5710 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005711 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005712 chain = new EffectChain(this, sessionId);
5713 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005714 chain->setStrategy(getStrategyForSession_l(sessionId));
5715 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005717 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005718 }
5719
Steve Block3856b092011-10-20 11:56:00 +01005720 ALOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721
5722 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005723 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005724 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005725 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005726 if (lStatus != NO_ERROR) {
5727 goto Exit;
5728 }
5729 effectRegistered = true;
5730 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005731 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005732 lStatus = effect->status();
5733 if (lStatus != NO_ERROR) {
5734 goto Exit;
5735 }
Eric Laurentcab11242010-07-15 12:50:15 -07005736 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 if (lStatus != NO_ERROR) {
5738 goto Exit;
5739 }
5740 effectCreated = true;
5741
5742 effect->setDevice(mDevice);
5743 effect->setMode(mAudioFlinger->getMode());
5744 }
5745 // create effect handle and connect it to effect module
5746 handle = new EffectHandle(effect, client, effectClient, priority);
5747 lStatus = effect->addHandle(handle);
5748 if (enabled) {
5749 *enabled = (int)effect->isEnabled();
5750 }
5751 }
5752
5753Exit:
5754 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005755 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005756 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005757 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005758 }
5759 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005760 AudioSystem::unregisterEffect(effect->id());
5761 }
5762 if (chainCreated) {
5763 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005764 }
5765 handle.clear();
5766 }
5767
5768 if(status) {
5769 *status = lStatus;
5770 }
5771 return handle;
5772}
5773
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005774sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5775{
5776 sp<EffectModule> effect;
5777
5778 sp<EffectChain> chain = getEffectChain_l(sessionId);
5779 if (chain != 0) {
5780 effect = chain->getEffectFromId_l(effectId);
5781 }
5782 return effect;
5783}
5784
Eric Laurentde070132010-07-13 04:45:46 -07005785// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5786// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005787status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005788{
5789 // check for existing effect chain with the requested audio session
5790 int sessionId = effect->sessionId();
5791 sp<EffectChain> chain = getEffectChain_l(sessionId);
5792 bool chainCreated = false;
5793
5794 if (chain == 0) {
5795 // create a new chain for this session
Steve Block3856b092011-10-20 11:56:00 +01005796 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005797 chain = new EffectChain(this, sessionId);
5798 addEffectChain_l(chain);
5799 chain->setStrategy(getStrategyForSession_l(sessionId));
5800 chainCreated = true;
5801 }
Steve Block3856b092011-10-20 11:56:00 +01005802 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
Eric Laurentde070132010-07-13 04:45:46 -07005803
5804 if (chain->getEffectFromId_l(effect->id()) != 0) {
5805 LOGW("addEffect_l() %p effect %s already present in chain %p",
5806 this, effect->desc().name, chain.get());
5807 return BAD_VALUE;
5808 }
5809
5810 status_t status = chain->addEffect_l(effect);
5811 if (status != NO_ERROR) {
5812 if (chainCreated) {
5813 removeEffectChain_l(chain);
5814 }
5815 return status;
5816 }
5817
5818 effect->setDevice(mDevice);
5819 effect->setMode(mAudioFlinger->getMode());
5820 return NO_ERROR;
5821}
5822
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005823void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005824
Steve Block3856b092011-10-20 11:56:00 +01005825 ALOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005826 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005827 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5828 detachAuxEffect_l(effect->id());
5829 }
5830
5831 sp<EffectChain> chain = effect->chain().promote();
5832 if (chain != 0) {
5833 // remove effect chain if removing last effect
5834 if (chain->removeEffect_l(effect) == 0) {
5835 removeEffectChain_l(chain);
5836 }
5837 } else {
5838 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5839 }
5840}
5841
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005842void AudioFlinger::ThreadBase::lockEffectChains_l(
5843 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5844{
5845 effectChains = mEffectChains;
5846 for (size_t i = 0; i < mEffectChains.size(); i++) {
5847 mEffectChains[i]->lock();
5848 }
5849}
5850
5851void AudioFlinger::ThreadBase::unlockEffectChains(
5852 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5853{
5854 for (size_t i = 0; i < effectChains.size(); i++) {
5855 effectChains[i]->unlock();
5856 }
5857}
5858
5859sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5860{
5861 Mutex::Autolock _l(mLock);
5862 return getEffectChain_l(sessionId);
5863}
5864
5865sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5866{
5867 sp<EffectChain> chain;
5868
5869 size_t size = mEffectChains.size();
5870 for (size_t i = 0; i < size; i++) {
5871 if (mEffectChains[i]->sessionId() == sessionId) {
5872 chain = mEffectChains[i];
5873 break;
5874 }
5875 }
5876 return chain;
5877}
5878
5879void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5880{
5881 Mutex::Autolock _l(mLock);
5882 size_t size = mEffectChains.size();
5883 for (size_t i = 0; i < size; i++) {
5884 mEffectChains[i]->setMode_l(mode);
5885 }
5886}
5887
5888void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005889 const wp<EffectHandle>& handle,
5890 bool unpiniflast) {
Eric Laurent59255e42011-07-27 19:49:51 -07005891
Mathias Agopian65ab4712010-07-14 17:59:35 -07005892 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01005893 ALOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005894 // delete the effect module if removing last handle on it
5895 if (effect->removeHandle(handle) == 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07005896 if (!effect->isPinned() || unpiniflast) {
5897 removeEffect_l(effect);
5898 AudioSystem::unregisterEffect(effect->id());
5899 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005900 }
5901}
5902
5903status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5904{
5905 int session = chain->sessionId();
5906 int16_t *buffer = mMixBuffer;
5907 bool ownsBuffer = false;
5908
Steve Block3856b092011-10-20 11:56:00 +01005909 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005910 if (session > 0) {
5911 // Only one effect chain can be present in direct output thread and it uses
5912 // the mix buffer as input
5913 if (mType != DIRECT) {
5914 size_t numSamples = mFrameCount * mChannelCount;
5915 buffer = new int16_t[numSamples];
5916 memset(buffer, 0, numSamples * sizeof(int16_t));
Steve Block3856b092011-10-20 11:56:00 +01005917 ALOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005918 ownsBuffer = true;
5919 }
5920
5921 // Attach all tracks with same session ID to this chain.
5922 for (size_t i = 0; i < mTracks.size(); ++i) {
5923 sp<Track> track = mTracks[i];
5924 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005925 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005926 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005927 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005928 }
5929 }
5930
5931 // indicate all active tracks in the chain
5932 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5933 sp<Track> track = mActiveTracks[i].promote();
5934 if (track == 0) continue;
5935 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005936 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005937 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005938 }
5939 }
5940 }
5941
5942 chain->setInBuffer(buffer, ownsBuffer);
5943 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005944 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005945 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005946 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5947 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005948 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005949 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5950 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005951 // Effect chain for other sessions are inserted at beginning of effect
5952 // chains list to be processed before output mix effects. Relative order between other
5953 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005954 size_t size = mEffectChains.size();
5955 size_t i = 0;
5956 for (i = 0; i < size; i++) {
5957 if (mEffectChains[i]->sessionId() < session) break;
5958 }
5959 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005960 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005961
5962 return NO_ERROR;
5963}
5964
5965size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5966{
5967 int session = chain->sessionId();
5968
Steve Block3856b092011-10-20 11:56:00 +01005969 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005970
5971 for (size_t i = 0; i < mEffectChains.size(); i++) {
5972 if (chain == mEffectChains[i]) {
5973 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005974 // detach all active tracks from the chain
5975 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5976 sp<Track> track = mActiveTracks[i].promote();
5977 if (track == 0) continue;
5978 if (session == track->sessionId()) {
Steve Block3856b092011-10-20 11:56:00 +01005979 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
Eric Laurentb469b942011-05-09 12:09:06 -07005980 chain.get(), session);
5981 chain->decActiveTrackCnt();
5982 }
5983 }
5984
Mathias Agopian65ab4712010-07-14 17:59:35 -07005985 // detach all tracks with same session ID from this chain
5986 for (size_t i = 0; i < mTracks.size(); ++i) {
5987 sp<Track> track = mTracks[i];
5988 if (session == track->sessionId()) {
5989 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005990 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005991 }
5992 }
Eric Laurentde070132010-07-13 04:45:46 -07005993 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005994 }
5995 }
5996 return mEffectChains.size();
5997}
5998
Eric Laurentde070132010-07-13 04:45:46 -07005999status_t AudioFlinger::PlaybackThread::attachAuxEffect(
6000 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006001{
6002 Mutex::Autolock _l(mLock);
6003 return attachAuxEffect_l(track, EffectId);
6004}
6005
Eric Laurentde070132010-07-13 04:45:46 -07006006status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
6007 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006008{
6009 status_t status = NO_ERROR;
6010
6011 if (EffectId == 0) {
6012 track->setAuxBuffer(0, NULL);
6013 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07006014 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
6015 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006016 if (effect != 0) {
6017 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6018 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
6019 } else {
6020 status = INVALID_OPERATION;
6021 }
6022 } else {
6023 status = BAD_VALUE;
6024 }
6025 }
6026 return status;
6027}
6028
6029void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
6030{
6031 for (size_t i = 0; i < mTracks.size(); ++i) {
6032 sp<Track> track = mTracks[i];
6033 if (track->auxEffectId() == effectId) {
6034 attachAuxEffect_l(track, 0);
6035 }
6036 }
6037}
6038
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006039status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
6040{
6041 // only one chain per input thread
6042 if (mEffectChains.size() != 0) {
6043 return INVALID_OPERATION;
6044 }
Steve Block3856b092011-10-20 11:56:00 +01006045 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006046
6047 chain->setInBuffer(NULL);
6048 chain->setOutBuffer(NULL);
6049
Eric Laurent59255e42011-07-27 19:49:51 -07006050 checkSuspendOnAddEffectChain_l(chain);
6051
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006052 mEffectChains.add(chain);
6053
6054 return NO_ERROR;
6055}
6056
6057size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
6058{
Steve Block3856b092011-10-20 11:56:00 +01006059 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006060 LOGW_IF(mEffectChains.size() != 1,
6061 "removeEffectChain_l() %p invalid chain size %d on thread %p",
6062 chain.get(), mEffectChains.size(), this);
6063 if (mEffectChains.size() == 1) {
6064 mEffectChains.removeAt(0);
6065 }
6066 return 0;
6067}
6068
Mathias Agopian65ab4712010-07-14 17:59:35 -07006069// ----------------------------------------------------------------------------
6070// EffectModule implementation
6071// ----------------------------------------------------------------------------
6072
6073#undef LOG_TAG
6074#define LOG_TAG "AudioFlinger::EffectModule"
6075
6076AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
6077 const wp<AudioFlinger::EffectChain>& chain,
6078 effect_descriptor_t *desc,
6079 int id,
6080 int sessionId)
6081 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006082 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006083{
Steve Block3856b092011-10-20 11:56:00 +01006084 ALOGV("Constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006085 int lStatus;
6086 sp<ThreadBase> thread = mThread.promote();
6087 if (thread == 0) {
6088 return;
6089 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006090
6091 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
6092
6093 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006094 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095
6096 if (mStatus != NO_ERROR) {
6097 return;
6098 }
6099 lStatus = init();
6100 if (lStatus < 0) {
6101 mStatus = lStatus;
6102 goto Error;
6103 }
6104
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006105 if (mSessionId > AUDIO_SESSION_OUTPUT_MIX) {
6106 mPinned = true;
6107 }
Steve Block3856b092011-10-20 11:56:00 +01006108 ALOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006109 return;
6110Error:
6111 EffectRelease(mEffectInterface);
6112 mEffectInterface = NULL;
Steve Block3856b092011-10-20 11:56:00 +01006113 ALOGV("Constructor Error %d", mStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006114}
6115
6116AudioFlinger::EffectModule::~EffectModule()
6117{
Steve Block3856b092011-10-20 11:56:00 +01006118 ALOGV("Destructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006120 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6121 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
6122 sp<ThreadBase> thread = mThread.promote();
6123 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006124 audio_stream_t *stream = thread->stream();
6125 if (stream != NULL) {
6126 stream->remove_audio_effect(stream, mEffectInterface);
6127 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006128 }
6129 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006130 // release effect engine
6131 EffectRelease(mEffectInterface);
6132 }
6133}
6134
6135status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
6136{
6137 status_t status;
6138
6139 Mutex::Autolock _l(mLock);
6140 // First handle in mHandles has highest priority and controls the effect module
6141 int priority = handle->priority();
6142 size_t size = mHandles.size();
6143 sp<EffectHandle> h;
6144 size_t i;
6145 for (i = 0; i < size; i++) {
6146 h = mHandles[i].promote();
6147 if (h == 0) continue;
6148 if (h->priority() <= priority) break;
6149 }
6150 // if inserted in first place, move effect control from previous owner to this handle
6151 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006152 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006154 enabled = h->enabled();
6155 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006156 }
Eric Laurent59255e42011-07-27 19:49:51 -07006157 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006158 status = NO_ERROR;
6159 } else {
6160 status = ALREADY_EXISTS;
6161 }
Steve Block3856b092011-10-20 11:56:00 +01006162 ALOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006163 mHandles.insertAt(handle, i);
6164 return status;
6165}
6166
6167size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
6168{
6169 Mutex::Autolock _l(mLock);
6170 size_t size = mHandles.size();
6171 size_t i;
6172 for (i = 0; i < size; i++) {
6173 if (mHandles[i] == handle) break;
6174 }
6175 if (i == size) {
6176 return size;
6177 }
Steve Block3856b092011-10-20 11:56:00 +01006178 ALOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
Eric Laurent59255e42011-07-27 19:49:51 -07006179
6180 bool enabled = false;
6181 EffectHandle *hdl = handle.unsafe_get();
6182 if (hdl) {
Steve Block3856b092011-10-20 11:56:00 +01006183 ALOGV("removeHandle() unsafe_get OK");
Eric Laurent59255e42011-07-27 19:49:51 -07006184 enabled = hdl->enabled();
6185 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006186 mHandles.removeAt(i);
6187 size = mHandles.size();
6188 // if removed from first place, move effect control from this handle to next in line
6189 if (i == 0 && size != 0) {
6190 sp<EffectHandle> h = mHandles[0].promote();
6191 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07006192 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006193 }
6194 }
6195
Eric Laurentec437d82011-07-26 20:54:46 -07006196 // Prevent calls to process() and other functions on effect interface from now on.
6197 // The effect engine will be released by the destructor when the last strong reference on
6198 // this object is released which can happen after next process is called.
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006199 if (size == 0 && !mPinned) {
Eric Laurentec437d82011-07-26 20:54:46 -07006200 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07006201 }
6202
Mathias Agopian65ab4712010-07-14 17:59:35 -07006203 return size;
6204}
6205
Eric Laurent59255e42011-07-27 19:49:51 -07006206sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
6207{
6208 Mutex::Autolock _l(mLock);
6209 sp<EffectHandle> handle;
6210 if (mHandles.size() != 0) {
6211 handle = mHandles[0].promote();
6212 }
6213 return handle;
6214}
6215
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006216void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle, bool unpiniflast)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006217{
Steve Block3856b092011-10-20 11:56:00 +01006218 ALOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006219 // keep a strong reference on this EffectModule to avoid calling the
6220 // destructor before we exit
6221 sp<EffectModule> keep(this);
6222 {
6223 sp<ThreadBase> thread = mThread.promote();
6224 if (thread != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006225 thread->disconnectEffect(keep, handle, unpiniflast);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006226 }
6227 }
6228}
6229
6230void AudioFlinger::EffectModule::updateState() {
6231 Mutex::Autolock _l(mLock);
6232
6233 switch (mState) {
6234 case RESTART:
6235 reset_l();
6236 // FALL THROUGH
6237
6238 case STARTING:
6239 // clear auxiliary effect input buffer for next accumulation
6240 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6241 memset(mConfig.inputCfg.buffer.raw,
6242 0,
6243 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
6244 }
6245 start_l();
6246 mState = ACTIVE;
6247 break;
6248 case STOPPING:
6249 stop_l();
6250 mDisableWaitCnt = mMaxDisableWaitCnt;
6251 mState = STOPPED;
6252 break;
6253 case STOPPED:
6254 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
6255 // turn off sequence.
6256 if (--mDisableWaitCnt == 0) {
6257 reset_l();
6258 mState = IDLE;
6259 }
6260 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006261 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07006262 break;
6263 }
6264}
6265
6266void AudioFlinger::EffectModule::process()
6267{
6268 Mutex::Autolock _l(mLock);
6269
Eric Laurentec437d82011-07-26 20:54:46 -07006270 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07006271 mConfig.inputCfg.buffer.raw == NULL ||
6272 mConfig.outputCfg.buffer.raw == NULL) {
6273 return;
6274 }
6275
Eric Laurent8f45bd72010-08-31 13:50:07 -07006276 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006277 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
6278 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Glenn Kasten3b21c502011-12-15 09:52:39 -08006279 ditherAndClamp(mConfig.inputCfg.buffer.s32,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006280 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07006281 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006282 }
6283
6284 // do the actual processing in the effect engine
6285 int ret = (*mEffectInterface)->process(mEffectInterface,
6286 &mConfig.inputCfg.buffer,
6287 &mConfig.outputCfg.buffer);
6288
6289 // force transition to IDLE state when engine is ready
6290 if (mState == STOPPED && ret == -ENODATA) {
6291 mDisableWaitCnt = 1;
6292 }
6293
6294 // clear auxiliary effect input buffer for next accumulation
6295 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08006296 memset(mConfig.inputCfg.buffer.raw, 0,
6297 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07006298 }
6299 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08006300 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6301 // If an insert effect is idle and input buffer is different from output buffer,
6302 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07006303 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07006304 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08006305 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
6306 int16_t *in = mConfig.inputCfg.buffer.s16;
6307 int16_t *out = mConfig.outputCfg.buffer.s16;
6308 for (size_t i = 0; i < frameCnt; i++) {
6309 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006310 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006311 }
6312 }
6313}
6314
6315void AudioFlinger::EffectModule::reset_l()
6316{
6317 if (mEffectInterface == NULL) {
6318 return;
6319 }
6320 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
6321}
6322
6323status_t AudioFlinger::EffectModule::configure()
6324{
6325 uint32_t channels;
6326 if (mEffectInterface == NULL) {
6327 return NO_INIT;
6328 }
6329
6330 sp<ThreadBase> thread = mThread.promote();
6331 if (thread == 0) {
6332 return DEAD_OBJECT;
6333 }
6334
6335 // TODO: handle configuration of effects replacing track process
6336 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006337 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006338 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07006339 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006340 }
6341
6342 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07006343 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 } else {
6345 mConfig.inputCfg.channels = channels;
6346 }
6347 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07006348 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
6349 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006350 mConfig.inputCfg.samplingRate = thread->sampleRate();
6351 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
6352 mConfig.inputCfg.bufferProvider.cookie = NULL;
6353 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
6354 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
6355 mConfig.outputCfg.bufferProvider.cookie = NULL;
6356 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
6357 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
6358 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
6359 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07006360 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07006361 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07006362 // - in other sessions:
6363 // last effect in the chain accumulates in output buffer: input buffer != output buffer
6364 // other effect: overwrites output buffer: input buffer == output buffer
6365 // Auxiliary effect:
6366 // accumulates in output buffer: input buffer != output buffer
6367 // Therefore: accumulate <=> input buffer != output buffer
6368 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
6369 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
6370 } else {
6371 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
6372 }
6373 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
6374 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
6375 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
6376 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
6377
Steve Block3856b092011-10-20 11:56:00 +01006378 ALOGV("configure() %p thread %p buffer %p framecount %d",
Eric Laurentde070132010-07-13 04:45:46 -07006379 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6380
Mathias Agopian65ab4712010-07-14 17:59:35 -07006381 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006382 uint32_t size = sizeof(int);
6383 status_t status = (*mEffectInterface)->command(mEffectInterface,
Eric Laurent3d5188b2011-12-16 15:30:36 -08006384 EFFECT_CMD_SET_CONFIG,
Eric Laurent25f43952010-07-28 05:40:18 -07006385 sizeof(effect_config_t),
6386 &mConfig,
6387 &size,
6388 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389 if (status == 0) {
6390 status = cmdStatus;
6391 }
6392
6393 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6394 (1000 * mConfig.outputCfg.buffer.frameCount);
6395
6396 return status;
6397}
6398
6399status_t AudioFlinger::EffectModule::init()
6400{
6401 Mutex::Autolock _l(mLock);
6402 if (mEffectInterface == NULL) {
6403 return NO_INIT;
6404 }
6405 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006406 uint32_t size = sizeof(status_t);
6407 status_t status = (*mEffectInterface)->command(mEffectInterface,
6408 EFFECT_CMD_INIT,
6409 0,
6410 NULL,
6411 &size,
6412 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006413 if (status == 0) {
6414 status = cmdStatus;
6415 }
6416 return status;
6417}
6418
Eric Laurentec35a142011-10-05 17:42:25 -07006419status_t AudioFlinger::EffectModule::start()
6420{
6421 Mutex::Autolock _l(mLock);
6422 return start_l();
6423}
6424
Mathias Agopian65ab4712010-07-14 17:59:35 -07006425status_t AudioFlinger::EffectModule::start_l()
6426{
6427 if (mEffectInterface == NULL) {
6428 return NO_INIT;
6429 }
6430 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006431 uint32_t size = sizeof(status_t);
6432 status_t status = (*mEffectInterface)->command(mEffectInterface,
6433 EFFECT_CMD_ENABLE,
6434 0,
6435 NULL,
6436 &size,
6437 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438 if (status == 0) {
6439 status = cmdStatus;
6440 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006441 if (status == 0 &&
6442 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6443 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6444 sp<ThreadBase> thread = mThread.promote();
6445 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006446 audio_stream_t *stream = thread->stream();
6447 if (stream != NULL) {
6448 stream->add_audio_effect(stream, mEffectInterface);
6449 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006450 }
6451 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006452 return status;
6453}
6454
Eric Laurentec437d82011-07-26 20:54:46 -07006455status_t AudioFlinger::EffectModule::stop()
6456{
6457 Mutex::Autolock _l(mLock);
6458 return stop_l();
6459}
6460
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461status_t AudioFlinger::EffectModule::stop_l()
6462{
6463 if (mEffectInterface == NULL) {
6464 return NO_INIT;
6465 }
6466 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006467 uint32_t size = sizeof(status_t);
6468 status_t status = (*mEffectInterface)->command(mEffectInterface,
6469 EFFECT_CMD_DISABLE,
6470 0,
6471 NULL,
6472 &size,
6473 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006474 if (status == 0) {
6475 status = cmdStatus;
6476 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006477 if (status == 0 &&
6478 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6479 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6480 sp<ThreadBase> thread = mThread.promote();
6481 if (thread != 0) {
Eric Laurentb8ba0a92011-08-07 16:32:26 -07006482 audio_stream_t *stream = thread->stream();
6483 if (stream != NULL) {
6484 stream->remove_audio_effect(stream, mEffectInterface);
6485 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006486 }
6487 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006488 return status;
6489}
6490
Eric Laurent25f43952010-07-28 05:40:18 -07006491status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6492 uint32_t cmdSize,
6493 void *pCmdData,
6494 uint32_t *replySize,
6495 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006496{
6497 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006498// ALOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006499
Eric Laurentec437d82011-07-26 20:54:46 -07006500 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006501 return NO_INIT;
6502 }
Eric Laurent25f43952010-07-28 05:40:18 -07006503 status_t status = (*mEffectInterface)->command(mEffectInterface,
6504 cmdCode,
6505 cmdSize,
6506 pCmdData,
6507 replySize,
6508 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006510 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006511 for (size_t i = 1; i < mHandles.size(); i++) {
6512 sp<EffectHandle> h = mHandles[i].promote();
6513 if (h != 0) {
6514 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6515 }
6516 }
6517 }
6518 return status;
6519}
6520
6521status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6522{
Eric Laurentdb7c0792011-08-10 10:37:50 -07006523
Mathias Agopian65ab4712010-07-14 17:59:35 -07006524 Mutex::Autolock _l(mLock);
Steve Block3856b092011-10-20 11:56:00 +01006525 ALOGV("setEnabled %p enabled %d", this, enabled);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006526
6527 if (enabled != isEnabled()) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006528 status_t status = AudioSystem::setEffectEnabled(mId, enabled);
6529 if (enabled && status != NO_ERROR) {
6530 return status;
6531 }
6532
Mathias Agopian65ab4712010-07-14 17:59:35 -07006533 switch (mState) {
6534 // going from disabled to enabled
6535 case IDLE:
6536 mState = STARTING;
6537 break;
6538 case STOPPED:
6539 mState = RESTART;
6540 break;
6541 case STOPPING:
6542 mState = ACTIVE;
6543 break;
6544
6545 // going from enabled to disabled
6546 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006547 mState = STOPPED;
6548 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006549 case STARTING:
6550 mState = IDLE;
6551 break;
6552 case ACTIVE:
6553 mState = STOPPING;
6554 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006555 case DESTROYED:
6556 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006557 }
6558 for (size_t i = 1; i < mHandles.size(); i++) {
6559 sp<EffectHandle> h = mHandles[i].promote();
6560 if (h != 0) {
6561 h->setEnabled(enabled);
6562 }
6563 }
6564 }
6565 return NO_ERROR;
6566}
6567
6568bool AudioFlinger::EffectModule::isEnabled()
6569{
6570 switch (mState) {
6571 case RESTART:
6572 case STARTING:
6573 case ACTIVE:
6574 return true;
6575 case IDLE:
6576 case STOPPING:
6577 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006578 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006579 default:
6580 return false;
6581 }
6582}
6583
Eric Laurent8f45bd72010-08-31 13:50:07 -07006584bool AudioFlinger::EffectModule::isProcessEnabled()
6585{
6586 switch (mState) {
6587 case RESTART:
6588 case ACTIVE:
6589 case STOPPING:
6590 case STOPPED:
6591 return true;
6592 case IDLE:
6593 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006594 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006595 default:
6596 return false;
6597 }
6598}
6599
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6601{
6602 Mutex::Autolock _l(mLock);
6603 status_t status = NO_ERROR;
6604
6605 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6606 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006607 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006608 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6609 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006610 status_t cmdStatus;
6611 uint32_t volume[2];
6612 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006613 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006614 volume[0] = *left;
6615 volume[1] = *right;
6616 if (controller) {
6617 pVolume = volume;
6618 }
Eric Laurent25f43952010-07-28 05:40:18 -07006619 status = (*mEffectInterface)->command(mEffectInterface,
6620 EFFECT_CMD_SET_VOLUME,
6621 size,
6622 volume,
6623 &size,
6624 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006625 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6626 *left = volume[0];
6627 *right = volume[1];
6628 }
6629 }
6630 return status;
6631}
6632
6633status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6634{
6635 Mutex::Autolock _l(mLock);
6636 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006637 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6638 // audio pre processing modules on RecordThread can receive both output and
6639 // input device indication in the same call
6640 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6641 if (dev) {
6642 status_t cmdStatus;
6643 uint32_t size = sizeof(status_t);
6644
6645 status = (*mEffectInterface)->command(mEffectInterface,
6646 EFFECT_CMD_SET_DEVICE,
6647 sizeof(uint32_t),
6648 &dev,
6649 &size,
6650 &cmdStatus);
6651 if (status == NO_ERROR) {
6652 status = cmdStatus;
6653 }
6654 }
6655 dev = device & AUDIO_DEVICE_IN_ALL;
6656 if (dev) {
6657 status_t cmdStatus;
6658 uint32_t size = sizeof(status_t);
6659
6660 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6661 EFFECT_CMD_SET_INPUT_DEVICE,
6662 sizeof(uint32_t),
6663 &dev,
6664 &size,
6665 &cmdStatus);
6666 if (status2 == NO_ERROR) {
6667 status2 = cmdStatus;
6668 }
6669 if (status == NO_ERROR) {
6670 status = status2;
6671 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006672 }
6673 }
6674 return status;
6675}
6676
6677status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6678{
6679 Mutex::Autolock _l(mLock);
6680 status_t status = NO_ERROR;
6681 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006682 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006683 uint32_t size = sizeof(status_t);
6684 status = (*mEffectInterface)->command(mEffectInterface,
6685 EFFECT_CMD_SET_AUDIO_MODE,
6686 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006687 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006688 &size,
6689 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006690 if (status == NO_ERROR) {
6691 status = cmdStatus;
6692 }
6693 }
6694 return status;
6695}
6696
Eric Laurent59255e42011-07-27 19:49:51 -07006697void AudioFlinger::EffectModule::setSuspended(bool suspended)
6698{
6699 Mutex::Autolock _l(mLock);
6700 mSuspended = suspended;
6701}
6702bool AudioFlinger::EffectModule::suspended()
6703{
6704 Mutex::Autolock _l(mLock);
6705 return mSuspended;
6706}
6707
Mathias Agopian65ab4712010-07-14 17:59:35 -07006708status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6709{
6710 const size_t SIZE = 256;
6711 char buffer[SIZE];
6712 String8 result;
6713
6714 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6715 result.append(buffer);
6716
6717 bool locked = tryLock(mLock);
6718 // failed to lock - AudioFlinger is probably deadlocked
6719 if (!locked) {
6720 result.append("\t\tCould not lock Fx mutex:\n");
6721 }
6722
6723 result.append("\t\tSession Status State Engine:\n");
6724 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6725 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6726 result.append(buffer);
6727
6728 result.append("\t\tDescriptor:\n");
6729 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6730 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6731 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6732 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6733 result.append(buffer);
6734 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6735 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6736 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6737 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6738 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006739 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740 mDescriptor.apiVersion,
6741 mDescriptor.flags);
6742 result.append(buffer);
6743 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6744 mDescriptor.name);
6745 result.append(buffer);
6746 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6747 mDescriptor.implementor);
6748 result.append(buffer);
6749
6750 result.append("\t\t- Input configuration:\n");
6751 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6752 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6753 (uint32_t)mConfig.inputCfg.buffer.raw,
6754 mConfig.inputCfg.buffer.frameCount,
6755 mConfig.inputCfg.samplingRate,
6756 mConfig.inputCfg.channels,
6757 mConfig.inputCfg.format);
6758 result.append(buffer);
6759
6760 result.append("\t\t- Output configuration:\n");
6761 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6762 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6763 (uint32_t)mConfig.outputCfg.buffer.raw,
6764 mConfig.outputCfg.buffer.frameCount,
6765 mConfig.outputCfg.samplingRate,
6766 mConfig.outputCfg.channels,
6767 mConfig.outputCfg.format);
6768 result.append(buffer);
6769
6770 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6771 result.append(buffer);
6772 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6773 for (size_t i = 0; i < mHandles.size(); ++i) {
6774 sp<EffectHandle> handle = mHandles[i].promote();
6775 if (handle != 0) {
6776 handle->dump(buffer, SIZE);
6777 result.append(buffer);
6778 }
6779 }
6780
6781 result.append("\n");
6782
6783 write(fd, result.string(), result.length());
6784
6785 if (locked) {
6786 mLock.unlock();
6787 }
6788
6789 return NO_ERROR;
6790}
6791
6792// ----------------------------------------------------------------------------
6793// EffectHandle implementation
6794// ----------------------------------------------------------------------------
6795
6796#undef LOG_TAG
6797#define LOG_TAG "AudioFlinger::EffectHandle"
6798
6799AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6800 const sp<AudioFlinger::Client>& client,
6801 const sp<IEffectClient>& effectClient,
6802 int32_t priority)
6803 : BnEffect(),
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006804 mEffect(effect), mEffectClient(effectClient), mClient(client), mCblk(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07006805 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006806{
Steve Block3856b092011-10-20 11:56:00 +01006807 ALOGV("constructor %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006808
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006809 if (client == 0) {
6810 return;
6811 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006812 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6813 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6814 if (mCblkMemory != 0) {
6815 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6816
6817 if (mCblk) {
6818 new(mCblk) effect_param_cblk_t();
6819 mBuffer = (uint8_t *)mCblk + bufOffset;
6820 }
6821 } else {
6822 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6823 return;
6824 }
6825}
6826
6827AudioFlinger::EffectHandle::~EffectHandle()
6828{
Steve Block3856b092011-10-20 11:56:00 +01006829 ALOGV("Destructor %p", this);
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006830 disconnect(false);
Steve Block3856b092011-10-20 11:56:00 +01006831 ALOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006832}
6833
6834status_t AudioFlinger::EffectHandle::enable()
6835{
Steve Block3856b092011-10-20 11:56:00 +01006836 ALOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006837 if (!mHasControl) return INVALID_OPERATION;
6838 if (mEffect == 0) return DEAD_OBJECT;
6839
Eric Laurentdb7c0792011-08-10 10:37:50 -07006840 if (mEnabled) {
6841 return NO_ERROR;
6842 }
6843
Eric Laurent59255e42011-07-27 19:49:51 -07006844 mEnabled = true;
6845
6846 sp<ThreadBase> thread = mEffect->thread().promote();
6847 if (thread != 0) {
6848 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6849 }
6850
6851 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6852 if (mEffect->suspended()) {
6853 return NO_ERROR;
6854 }
6855
Eric Laurentdb7c0792011-08-10 10:37:50 -07006856 status_t status = mEffect->setEnabled(true);
6857 if (status != NO_ERROR) {
6858 if (thread != 0) {
6859 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6860 }
6861 mEnabled = false;
6862 }
6863 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006864}
6865
6866status_t AudioFlinger::EffectHandle::disable()
6867{
Steve Block3856b092011-10-20 11:56:00 +01006868 ALOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006869 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006870 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006871
Eric Laurentdb7c0792011-08-10 10:37:50 -07006872 if (!mEnabled) {
6873 return NO_ERROR;
6874 }
Eric Laurent59255e42011-07-27 19:49:51 -07006875 mEnabled = false;
6876
6877 if (mEffect->suspended()) {
6878 return NO_ERROR;
6879 }
6880
6881 status_t status = mEffect->setEnabled(false);
6882
6883 sp<ThreadBase> thread = mEffect->thread().promote();
6884 if (thread != 0) {
6885 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6886 }
6887
6888 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889}
6890
6891void AudioFlinger::EffectHandle::disconnect()
6892{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006893 disconnect(true);
6894}
6895
6896void AudioFlinger::EffectHandle::disconnect(bool unpiniflast)
6897{
Steve Block3856b092011-10-20 11:56:00 +01006898 ALOGV("disconnect(%s)", unpiniflast ? "true" : "false");
Mathias Agopian65ab4712010-07-14 17:59:35 -07006899 if (mEffect == 0) {
6900 return;
6901 }
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006902 mEffect->disconnect(this, unpiniflast);
Eric Laurent59255e42011-07-27 19:49:51 -07006903
Eric Laurenta85a74a2011-10-19 11:44:54 -07006904 if (mHasControl && mEnabled) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07006905 sp<ThreadBase> thread = mEffect->thread().promote();
6906 if (thread != 0) {
6907 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6908 }
Eric Laurent59255e42011-07-27 19:49:51 -07006909 }
6910
Mathias Agopian65ab4712010-07-14 17:59:35 -07006911 // release sp on module => module destructor can be called now
6912 mEffect.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913 if (mClient != 0) {
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006914 if (mCblk) {
6915 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6916 }
6917 mCblkMemory.clear(); // and free the shared memory
Mathias Agopian65ab4712010-07-14 17:59:35 -07006918 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6919 mClient.clear();
6920 }
6921}
6922
Eric Laurent25f43952010-07-28 05:40:18 -07006923status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6924 uint32_t cmdSize,
6925 void *pCmdData,
6926 uint32_t *replySize,
6927 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006928{
Steve Block3856b092011-10-20 11:56:00 +01006929// ALOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
Eric Laurent25f43952010-07-28 05:40:18 -07006930// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006931
6932 // only get parameter command is permitted for applications not controlling the effect
6933 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6934 return INVALID_OPERATION;
6935 }
6936 if (mEffect == 0) return DEAD_OBJECT;
Marco Nelissen3a34bef2011-08-02 13:33:41 -07006937 if (mClient == 0) return INVALID_OPERATION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006938
6939 // handle commands that are not forwarded transparently to effect engine
6940 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6941 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6942 // no risk to block the whole media server process or mixer threads is we are stuck here
6943 Mutex::Autolock _l(mCblk->lock);
6944 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6945 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6946 mCblk->serverIndex = 0;
6947 mCblk->clientIndex = 0;
6948 return BAD_VALUE;
6949 }
6950 status_t status = NO_ERROR;
6951 while (mCblk->serverIndex < mCblk->clientIndex) {
6952 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006953 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006954 int *p = (int *)(mBuffer + mCblk->serverIndex);
6955 int size = *p++;
6956 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6957 LOGW("command(): invalid parameter block size");
6958 break;
6959 }
6960 effect_param_t *param = (effect_param_t *)p;
6961 if (param->psize == 0 || param->vsize == 0) {
6962 LOGW("command(): null parameter or value size");
6963 mCblk->serverIndex += size;
6964 continue;
6965 }
Eric Laurent25f43952010-07-28 05:40:18 -07006966 uint32_t psize = sizeof(effect_param_t) +
6967 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6968 param->vsize;
6969 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6970 psize,
6971 p,
6972 &rsize,
6973 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006974 // stop at first error encountered
6975 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006976 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006977 *(int *)pReplyData = reply;
6978 break;
6979 } else if (reply != NO_ERROR) {
6980 *(int *)pReplyData = reply;
6981 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006982 }
6983 mCblk->serverIndex += size;
6984 }
6985 mCblk->serverIndex = 0;
6986 mCblk->clientIndex = 0;
6987 return status;
6988 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006989 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006990 return enable();
6991 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006992 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006993 return disable();
6994 }
6995
6996 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6997}
6998
6999sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
7000 return mCblkMemory;
7001}
7002
Eric Laurent59255e42011-07-27 19:49:51 -07007003void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007004{
Steve Block3856b092011-10-20 11:56:00 +01007005 ALOGV("setControl %p control %d", this, hasControl);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007006
7007 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07007008 mEnabled = enabled;
7009
Mathias Agopian65ab4712010-07-14 17:59:35 -07007010 if (signal && mEffectClient != 0) {
7011 mEffectClient->controlStatusChanged(hasControl);
7012 }
7013}
7014
Eric Laurent25f43952010-07-28 05:40:18 -07007015void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
7016 uint32_t cmdSize,
7017 void *pCmdData,
7018 uint32_t replySize,
7019 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007020{
7021 if (mEffectClient != 0) {
7022 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
7023 }
7024}
7025
7026
7027
7028void AudioFlinger::EffectHandle::setEnabled(bool enabled)
7029{
7030 if (mEffectClient != 0) {
7031 mEffectClient->enableStatusChanged(enabled);
7032 }
7033}
7034
7035status_t AudioFlinger::EffectHandle::onTransact(
7036 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7037{
7038 return BnEffect::onTransact(code, data, reply, flags);
7039}
7040
7041
7042void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
7043{
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007044 bool locked = mCblk ? tryLock(mCblk->lock) : false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007045
7046 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
7047 (mClient == NULL) ? getpid() : mClient->pid(),
7048 mPriority,
7049 mHasControl,
7050 !locked,
Marco Nelissen3a34bef2011-08-02 13:33:41 -07007051 mCblk ? mCblk->clientIndex : 0,
7052 mCblk ? mCblk->serverIndex : 0
Mathias Agopian65ab4712010-07-14 17:59:35 -07007053 );
7054
7055 if (locked) {
7056 mCblk->lock.unlock();
7057 }
7058}
7059
7060#undef LOG_TAG
7061#define LOG_TAG "AudioFlinger::EffectChain"
7062
7063AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
7064 int sessionId)
Eric Laurent544fe9b2011-11-11 15:42:52 -08007065 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0), mTailBufferCount(0),
Eric Laurentb469b942011-05-09 12:09:06 -07007066 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
7067 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007068{
Dima Zavinfce7a472011-04-19 22:30:36 -07007069 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007070 sp<ThreadBase> thread = mThread.promote();
7071 if (thread == 0) {
7072 return;
7073 }
7074 mMaxTailBuffers = ((kProcessTailDurationMs * thread->sampleRate()) / 1000) /
7075 thread->frameCount();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007076}
7077
7078AudioFlinger::EffectChain::~EffectChain()
7079{
7080 if (mOwnInBuffer) {
7081 delete mInBuffer;
7082 }
7083
7084}
7085
Eric Laurent59255e42011-07-27 19:49:51 -07007086// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007087sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007088{
7089 sp<EffectModule> effect;
7090 size_t size = mEffects.size();
7091
7092 for (size_t i = 0; i < size; i++) {
7093 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
7094 effect = mEffects[i];
7095 break;
7096 }
7097 }
7098 return effect;
7099}
7100
Eric Laurent59255e42011-07-27 19:49:51 -07007101// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07007102sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007103{
7104 sp<EffectModule> effect;
7105 size_t size = mEffects.size();
7106
7107 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07007108 // by convention, return first effect if id provided is 0 (0 is never a valid id)
7109 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007110 effect = mEffects[i];
7111 break;
7112 }
7113 }
7114 return effect;
7115}
7116
Eric Laurent59255e42011-07-27 19:49:51 -07007117// getEffectFromType_l() must be called with ThreadBase::mLock held
7118sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
7119 const effect_uuid_t *type)
7120{
7121 sp<EffectModule> effect;
7122 size_t size = mEffects.size();
7123
7124 for (size_t i = 0; i < size; i++) {
7125 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
7126 effect = mEffects[i];
7127 break;
7128 }
7129 }
7130 return effect;
7131}
7132
Mathias Agopian65ab4712010-07-14 17:59:35 -07007133// Must be called with EffectChain::mLock locked
7134void AudioFlinger::EffectChain::process_l()
7135{
Eric Laurentdac69112010-09-28 14:09:57 -07007136 sp<ThreadBase> thread = mThread.promote();
7137 if (thread == 0) {
7138 LOGW("process_l(): cannot promote mixer thread");
7139 return;
7140 }
Dima Zavinfce7a472011-04-19 22:30:36 -07007141 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
7142 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurent544fe9b2011-11-11 15:42:52 -08007143 // always process effects unless no more tracks are on the session and the effect tail
7144 // has been rendered
7145 bool doProcess = true;
Eric Laurentdac69112010-09-28 14:09:57 -07007146 if (!isGlobalSession) {
Eric Laurent544fe9b2011-11-11 15:42:52 -08007147 bool tracksOnSession = (trackCnt() != 0);
Eric Laurentb469b942011-05-09 12:09:06 -07007148
Eric Laurent544fe9b2011-11-11 15:42:52 -08007149 if (!tracksOnSession && mTailBufferCount == 0) {
7150 doProcess = false;
7151 }
7152
7153 if (activeTrackCnt() == 0) {
7154 // if no track is active and the effect tail has not been rendered,
7155 // the input buffer must be cleared here as the mixer process will not do it
7156 if (tracksOnSession || mTailBufferCount > 0) {
7157 size_t numSamples = thread->frameCount() * thread->channelCount();
7158 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
7159 if (mTailBufferCount > 0) {
7160 mTailBufferCount--;
7161 }
7162 }
7163 }
Eric Laurentdac69112010-09-28 14:09:57 -07007164 }
7165
Mathias Agopian65ab4712010-07-14 17:59:35 -07007166 size_t size = mEffects.size();
Eric Laurent544fe9b2011-11-11 15:42:52 -08007167 if (doProcess) {
Eric Laurentdac69112010-09-28 14:09:57 -07007168 for (size_t i = 0; i < size; i++) {
7169 mEffects[i]->process();
7170 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007171 }
7172 for (size_t i = 0; i < size; i++) {
7173 mEffects[i]->updateState();
7174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007175}
7176
Eric Laurentcab11242010-07-15 12:50:15 -07007177// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07007178status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007179{
7180 effect_descriptor_t desc = effect->desc();
7181 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
7182
7183 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07007184 effect->setChain(this);
7185 sp<ThreadBase> thread = mThread.promote();
7186 if (thread == 0) {
7187 return NO_INIT;
7188 }
7189 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007190
7191 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
7192 // Auxiliary effects are inserted at the beginning of mEffects vector as
7193 // they are processed first and accumulated in chain input buffer
7194 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07007195
Mathias Agopian65ab4712010-07-14 17:59:35 -07007196 // the input buffer for auxiliary effect contains mono samples in
7197 // 32 bit format. This is to avoid saturation in AudoMixer
7198 // accumulation stage. Saturation is done in EffectModule::process() before
7199 // calling the process in effect engine
7200 size_t numSamples = thread->frameCount();
7201 int32_t *buffer = new int32_t[numSamples];
7202 memset(buffer, 0, numSamples * sizeof(int32_t));
7203 effect->setInBuffer((int16_t *)buffer);
7204 // auxiliary effects output samples to chain input buffer for further processing
7205 // by insert effects
7206 effect->setOutBuffer(mInBuffer);
7207 } else {
7208 // Insert effects are inserted at the end of mEffects vector as they are processed
7209 // after track and auxiliary effects.
7210 // Insert effect order as a function of indicated preference:
7211 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
7212 // another effect is present
7213 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
7214 // last effect claiming first position
7215 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
7216 // first effect claiming last position
7217 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
7218 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
7219 // already present
7220
7221 int size = (int)mEffects.size();
7222 int idx_insert = size;
7223 int idx_insert_first = -1;
7224 int idx_insert_last = -1;
7225
7226 for (int i = 0; i < size; i++) {
7227 effect_descriptor_t d = mEffects[i]->desc();
7228 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
7229 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
7230 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
7231 // check invalid effect chaining combinations
7232 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
7233 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07007234 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007235 return INVALID_OPERATION;
7236 }
7237 // remember position of first insert effect and by default
7238 // select this as insert position for new effect
7239 if (idx_insert == size) {
7240 idx_insert = i;
7241 }
7242 // remember position of last insert effect claiming
7243 // first position
7244 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
7245 idx_insert_first = i;
7246 }
7247 // remember position of first insert effect claiming
7248 // last position
7249 if (iPref == EFFECT_FLAG_INSERT_LAST &&
7250 idx_insert_last == -1) {
7251 idx_insert_last = i;
7252 }
7253 }
7254 }
7255
7256 // modify idx_insert from first position if needed
7257 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
7258 if (idx_insert_last != -1) {
7259 idx_insert = idx_insert_last;
7260 } else {
7261 idx_insert = size;
7262 }
7263 } else {
7264 if (idx_insert_first != -1) {
7265 idx_insert = idx_insert_first + 1;
7266 }
7267 }
7268
7269 // always read samples from chain input buffer
7270 effect->setInBuffer(mInBuffer);
7271
7272 // if last effect in the chain, output samples to chain
7273 // output buffer, otherwise to chain input buffer
7274 if (idx_insert == size) {
7275 if (idx_insert != 0) {
7276 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
7277 mEffects[idx_insert-1]->configure();
7278 }
7279 effect->setOutBuffer(mOutBuffer);
7280 } else {
7281 effect->setOutBuffer(mInBuffer);
7282 }
7283 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007284
Steve Block3856b092011-10-20 11:56:00 +01007285 ALOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007286 }
7287 effect->configure();
7288 return NO_ERROR;
7289}
7290
Eric Laurentcab11242010-07-15 12:50:15 -07007291// removeEffect_l() must be called with PlaybackThread::mLock held
7292size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007293{
7294 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007295 int size = (int)mEffects.size();
7296 int i;
7297 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
7298
7299 for (i = 0; i < size; i++) {
7300 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07007301 // calling stop here will remove pre-processing effect from the audio HAL.
7302 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
7303 // the middle of a read from audio HAL
Eric Laurentec35a142011-10-05 17:42:25 -07007304 if (mEffects[i]->state() == EffectModule::ACTIVE ||
7305 mEffects[i]->state() == EffectModule::STOPPING) {
7306 mEffects[i]->stop();
7307 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007308 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
7309 delete[] effect->inBuffer();
7310 } else {
7311 if (i == size - 1 && i != 0) {
7312 mEffects[i - 1]->setOutBuffer(mOutBuffer);
7313 mEffects[i - 1]->configure();
7314 }
7315 }
7316 mEffects.removeAt(i);
Steve Block3856b092011-10-20 11:56:00 +01007317 ALOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07007318 break;
7319 }
7320 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07007321
7322 return mEffects.size();
7323}
7324
Eric Laurentcab11242010-07-15 12:50:15 -07007325// setDevice_l() must be called with PlaybackThread::mLock held
7326void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007327{
7328 size_t size = mEffects.size();
7329 for (size_t i = 0; i < size; i++) {
7330 mEffects[i]->setDevice(device);
7331 }
7332}
7333
Eric Laurentcab11242010-07-15 12:50:15 -07007334// setMode_l() must be called with PlaybackThread::mLock held
7335void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007336{
7337 size_t size = mEffects.size();
7338 for (size_t i = 0; i < size; i++) {
7339 mEffects[i]->setMode(mode);
7340 }
7341}
7342
Eric Laurentcab11242010-07-15 12:50:15 -07007343// setVolume_l() must be called with PlaybackThread::mLock held
7344bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07007345{
7346 uint32_t newLeft = *left;
7347 uint32_t newRight = *right;
7348 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07007349 int ctrlIdx = -1;
7350 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07007351
Eric Laurentcab11242010-07-15 12:50:15 -07007352 // first update volume controller
7353 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07007354 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07007355 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
7356 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07007357 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07007358 break;
7359 }
7360 }
7361
7362 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07007363 if (hasControl) {
7364 *left = mNewLeftVolume;
7365 *right = mNewRightVolume;
7366 }
7367 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07007368 }
7369
7370 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07007371 mLeftVolume = newLeft;
7372 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007373
7374 // second get volume update from volume controller
7375 if (ctrlIdx >= 0) {
7376 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07007377 mNewLeftVolume = newLeft;
7378 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07007379 }
7380 // then indicate volume to all other effects in chain.
7381 // Pass altered volume to effects before volume controller
7382 // and requested volume to effects after controller
7383 uint32_t lVol = newLeft;
7384 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07007385
Mathias Agopian65ab4712010-07-14 17:59:35 -07007386 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07007387 if ((int)i == ctrlIdx) continue;
7388 // this also works for ctrlIdx == -1 when there is no volume controller
7389 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07007390 lVol = *left;
7391 rVol = *right;
7392 }
7393 mEffects[i]->setVolume(&lVol, &rVol, false);
7394 }
7395 *left = newLeft;
7396 *right = newRight;
7397
7398 return hasControl;
7399}
7400
Mathias Agopian65ab4712010-07-14 17:59:35 -07007401status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
7402{
7403 const size_t SIZE = 256;
7404 char buffer[SIZE];
7405 String8 result;
7406
7407 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
7408 result.append(buffer);
7409
7410 bool locked = tryLock(mLock);
7411 // failed to lock - AudioFlinger is probably deadlocked
7412 if (!locked) {
7413 result.append("\tCould not lock mutex:\n");
7414 }
7415
Eric Laurentcab11242010-07-15 12:50:15 -07007416 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
7417 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07007418 mEffects.size(),
7419 (uint32_t)mInBuffer,
7420 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07007421 mActiveTrackCnt);
7422 result.append(buffer);
7423 write(fd, result.string(), result.size());
7424
7425 for (size_t i = 0; i < mEffects.size(); ++i) {
7426 sp<EffectModule> effect = mEffects[i];
7427 if (effect != 0) {
7428 effect->dump(fd, args);
7429 }
7430 }
7431
7432 if (locked) {
7433 mLock.unlock();
7434 }
7435
7436 return NO_ERROR;
7437}
7438
Eric Laurent59255e42011-07-27 19:49:51 -07007439// must be called with ThreadBase::mLock held
7440void AudioFlinger::EffectChain::setEffectSuspended_l(
7441 const effect_uuid_t *type, bool suspend)
7442{
7443 sp<SuspendedEffectDesc> desc;
7444 // use effect type UUID timelow as key as there is no real risk of identical
7445 // timeLow fields among effect type UUIDs.
7446 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7447 if (suspend) {
7448 if (index >= 0) {
7449 desc = mSuspendedEffects.valueAt(index);
7450 } else {
7451 desc = new SuspendedEffectDesc();
7452 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7453 mSuspendedEffects.add(type->timeLow, desc);
Steve Block3856b092011-10-20 11:56:00 +01007454 ALOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
Eric Laurent59255e42011-07-27 19:49:51 -07007455 }
7456 if (desc->mRefCount++ == 0) {
7457 sp<EffectModule> effect = getEffectIfEnabled(type);
7458 if (effect != 0) {
7459 desc->mEffect = effect;
7460 effect->setSuspended(true);
7461 effect->setEnabled(false);
7462 }
7463 }
7464 } else {
7465 if (index < 0) {
7466 return;
7467 }
7468 desc = mSuspendedEffects.valueAt(index);
7469 if (desc->mRefCount <= 0) {
7470 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7471 desc->mRefCount = 1;
7472 }
7473 if (--desc->mRefCount == 0) {
Steve Block3856b092011-10-20 11:56:00 +01007474 ALOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007475 if (desc->mEffect != 0) {
7476 sp<EffectModule> effect = desc->mEffect.promote();
7477 if (effect != 0) {
7478 effect->setSuspended(false);
7479 sp<EffectHandle> handle = effect->controlHandle();
7480 if (handle != 0) {
7481 effect->setEnabled(handle->enabled());
7482 }
7483 }
7484 desc->mEffect.clear();
7485 }
7486 mSuspendedEffects.removeItemsAt(index);
7487 }
7488 }
7489}
7490
7491// must be called with ThreadBase::mLock held
7492void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7493{
7494 sp<SuspendedEffectDesc> desc;
7495
7496 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7497 if (suspend) {
7498 if (index >= 0) {
7499 desc = mSuspendedEffects.valueAt(index);
7500 } else {
7501 desc = new SuspendedEffectDesc();
7502 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
Steve Block3856b092011-10-20 11:56:00 +01007503 ALOGV("setEffectSuspendedAll_l() add entry for 0");
Eric Laurent59255e42011-07-27 19:49:51 -07007504 }
7505 if (desc->mRefCount++ == 0) {
7506 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7507 for (size_t i = 0; i < effects.size(); i++) {
7508 setEffectSuspended_l(&effects[i]->desc().type, true);
7509 }
7510 }
7511 } else {
7512 if (index < 0) {
7513 return;
7514 }
7515 desc = mSuspendedEffects.valueAt(index);
7516 if (desc->mRefCount <= 0) {
7517 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7518 desc->mRefCount = 1;
7519 }
7520 if (--desc->mRefCount == 0) {
7521 Vector<const effect_uuid_t *> types;
7522 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7523 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7524 continue;
7525 }
7526 types.add(&mSuspendedEffects.valueAt(i)->mType);
7527 }
7528 for (size_t i = 0; i < types.size(); i++) {
7529 setEffectSuspended_l(types[i], false);
7530 }
Steve Block3856b092011-10-20 11:56:00 +01007531 ALOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
Eric Laurent59255e42011-07-27 19:49:51 -07007532 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7533 }
7534 }
7535}
7536
Eric Laurent6bffdb82011-09-23 08:40:41 -07007537
7538// The volume effect is used for automated tests only
7539#ifndef OPENSL_ES_H_
7540static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
7541 { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
7542const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
7543#endif //OPENSL_ES_H_
7544
Eric Laurentdb7c0792011-08-10 10:37:50 -07007545bool AudioFlinger::EffectChain::isEffectEligibleForSuspend(const effect_descriptor_t& desc)
7546{
7547 // auxiliary effects and visualizer are never suspended on output mix
7548 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) &&
7549 (((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
Eric Laurent6bffdb82011-09-23 08:40:41 -07007550 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) ||
7551 (memcmp(&desc.type, SL_IID_VOLUME, sizeof(effect_uuid_t)) == 0))) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007552 return false;
7553 }
7554 return true;
7555}
7556
Eric Laurent59255e42011-07-27 19:49:51 -07007557Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7558{
7559 Vector< sp<EffectModule> > effects;
7560 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurentdb7c0792011-08-10 10:37:50 -07007561 if (!isEffectEligibleForSuspend(mEffects[i]->desc())) {
Eric Laurent59255e42011-07-27 19:49:51 -07007562 continue;
7563 }
7564 effects.add(mEffects[i]);
7565 }
7566 return effects;
7567}
7568
7569sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7570 const effect_uuid_t *type)
7571{
7572 sp<EffectModule> effect;
7573 effect = getEffectFromType_l(type);
7574 if (effect != 0 && !effect->isEnabled()) {
7575 effect.clear();
7576 }
7577 return effect;
7578}
7579
7580void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7581 bool enabled)
7582{
7583 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7584 if (enabled) {
7585 if (index < 0) {
7586 // if the effect is not suspend check if all effects are suspended
7587 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7588 if (index < 0) {
7589 return;
7590 }
Eric Laurentdb7c0792011-08-10 10:37:50 -07007591 if (!isEffectEligibleForSuspend(effect->desc())) {
7592 return;
7593 }
Eric Laurent59255e42011-07-27 19:49:51 -07007594 setEffectSuspended_l(&effect->desc().type, enabled);
7595 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
Eric Laurentdb7c0792011-08-10 10:37:50 -07007596 if (index < 0) {
7597 LOGW("checkSuspendOnEffectEnabled() Fx should be suspended here!");
7598 return;
7599 }
Eric Laurent59255e42011-07-27 19:49:51 -07007600 }
Steve Block3856b092011-10-20 11:56:00 +01007601 ALOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007602 effect->desc().type.timeLow);
7603 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7604 // if effect is requested to suspended but was not yet enabled, supend it now.
7605 if (desc->mEffect == 0) {
7606 desc->mEffect = effect;
7607 effect->setEnabled(false);
7608 effect->setSuspended(true);
7609 }
7610 } else {
7611 if (index < 0) {
7612 return;
7613 }
Steve Block3856b092011-10-20 11:56:00 +01007614 ALOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
Eric Laurent59255e42011-07-27 19:49:51 -07007615 effect->desc().type.timeLow);
7616 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7617 desc->mEffect.clear();
7618 effect->setSuspended(false);
7619 }
7620}
7621
Mathias Agopian65ab4712010-07-14 17:59:35 -07007622#undef LOG_TAG
7623#define LOG_TAG "AudioFlinger"
7624
7625// ----------------------------------------------------------------------------
7626
7627status_t AudioFlinger::onTransact(
7628 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7629{
7630 return BnAudioFlinger::onTransact(code, data, reply, flags);
7631}
7632
Mathias Agopian65ab4712010-07-14 17:59:35 -07007633}; // namespace android