blob: 0dc1eb89fdd2703856215106e252cb7f335e13b9 [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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070055#include <cpustats/ThreadCpuUsage.h>
Eric Laurentfeb0db62011-07-22 09:04:31 -070056#include <powermanager/PowerManager.h>
Glenn Kasten4d8d0c32011-07-08 15:26:12 -070057// #define DEBUG_CPU_USAGE 10 // log statistics every n wall clock seconds
58
Mathias Agopian65ab4712010-07-14 17:59:35 -070059// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -070060
Eric Laurentde070132010-07-13 04:45:46 -070061
Mathias Agopian65ab4712010-07-14 17:59:35 -070062namespace android {
63
64static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
65static const char* kHardwareLockedString = "Hardware lock is taken\n";
66
67//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
68static const float MAX_GAIN = 4096.0f;
69static const float MAX_GAIN_INT = 0x1000;
70
71// retry counts for buffer fill timeout
72// 50 * ~20msecs = 1 second
73static const int8_t kMaxTrackRetries = 50;
74static const int8_t kMaxTrackStartupRetries = 50;
75// allow less retry attempts on direct output thread.
76// direct outputs can be a scarce resource in audio hardware and should
77// be released as quickly as possible.
78static const int8_t kMaxTrackRetriesDirect = 2;
79
80static const int kDumpLockRetries = 50;
81static const int kDumpLockSleep = 20000;
82
83static const nsecs_t kWarningThrottle = seconds(5);
84
Eric Laurent7c7f10b2011-06-17 21:29:58 -070085// RecordThread loop sleep time upon application overrun or audio HAL read error
86static const int kRecordThreadSleepUs = 5000;
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Mathias Agopian65ab4712010-07-14 17:59:35 -070088// ----------------------------------------------------------------------------
89
90static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070091 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
92 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
93 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
94 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070095}
96
97static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070098 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
99 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
100 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
101 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102}
103
Gloria Wang9ee159b2011-02-24 14:51:45 -0800104// To collect the amplifier usage
105static void addBatteryData(uint32_t params) {
106 sp<IBinder> binder =
107 defaultServiceManager()->getService(String16("media.player"));
108 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
109 if (service.get() == NULL) {
110 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
111 return;
112 }
113
114 service->addBatteryData(params);
115}
116
Dima Zavin799a70e2011-04-18 16:57:27 -0700117static int load_audio_interface(const char *if_name, const hw_module_t **mod,
118 audio_hw_device_t **dev)
119{
120 int rc;
121
122 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
123 if (rc)
124 goto out;
125
126 rc = audio_hw_device_open(*mod, dev);
127 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
128 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
129 if (rc)
130 goto out;
131
132 return 0;
133
134out:
135 *mod = NULL;
136 *dev = NULL;
137 return rc;
138}
139
140static const char *audio_interfaces[] = {
141 "primary",
142 "a2dp",
143 "usb",
144};
145#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
146
Mathias Agopian65ab4712010-07-14 17:59:35 -0700147// ----------------------------------------------------------------------------
148
149AudioFlinger::AudioFlinger()
150 : BnAudioFlinger(),
Dima Zavin799a70e2011-04-18 16:57:27 -0700151 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700152{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700153}
154
155void AudioFlinger::onFirstRef()
156{
Dima Zavin799a70e2011-04-18 16:57:27 -0700157 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700158
Eric Laurent93575202011-01-18 18:39:02 -0800159 Mutex::Autolock _l(mLock);
160
Dima Zavin799a70e2011-04-18 16:57:27 -0700161 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700162 mHardwareStatus = AUDIO_HW_IDLE;
163
Dima Zavin799a70e2011-04-18 16:57:27 -0700164 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
165 const hw_module_t *mod;
166 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700167
Dima Zavin799a70e2011-04-18 16:57:27 -0700168 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
169 if (rc)
170 continue;
171
172 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
173 mod->name, mod->id);
174 mAudioHwDevs.push(dev);
175
176 if (!mPrimaryHardwareDev) {
177 mPrimaryHardwareDev = dev;
178 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700179 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700180 }
181 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700182
183 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700184
Dima Zavin799a70e2011-04-18 16:57:27 -0700185 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
186 LOGE("Primary audio interface not found");
187 return;
188 }
189
190 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
191 audio_hw_device_t *dev = mAudioHwDevs[i];
192
193 mHardwareStatus = AUDIO_HW_INIT;
194 rc = dev->init_check(dev);
195 if (rc == 0) {
196 AutoMutex lock(mHardwareLock);
197
198 mMode = AUDIO_MODE_NORMAL;
199 mHardwareStatus = AUDIO_HW_SET_MODE;
200 dev->set_mode(dev, mMode);
201 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
202 dev->set_master_volume(dev, 1.0f);
203 mHardwareStatus = AUDIO_HW_IDLE;
204 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700206}
207
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700208status_t AudioFlinger::initCheck() const
209{
210 Mutex::Autolock _l(mLock);
211 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
212 return NO_INIT;
213 return NO_ERROR;
214}
215
Mathias Agopian65ab4712010-07-14 17:59:35 -0700216AudioFlinger::~AudioFlinger()
217{
Dima Zavin799a70e2011-04-18 16:57:27 -0700218 int num_devs = mAudioHwDevs.size();
219
Mathias Agopian65ab4712010-07-14 17:59:35 -0700220 while (!mRecordThreads.isEmpty()) {
221 // closeInput() will remove first entry from mRecordThreads
222 closeInput(mRecordThreads.keyAt(0));
223 }
224 while (!mPlaybackThreads.isEmpty()) {
225 // closeOutput() will remove first entry from mPlaybackThreads
226 closeOutput(mPlaybackThreads.keyAt(0));
227 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700228
229 for (int i = 0; i < num_devs; i++) {
230 audio_hw_device_t *dev = mAudioHwDevs[i];
231 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700232 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700233 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700234}
235
Dima Zavin799a70e2011-04-18 16:57:27 -0700236audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
237{
238 /* first matching HW device is returned */
239 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
240 audio_hw_device_t *dev = mAudioHwDevs[i];
241 if ((dev->get_supported_devices(dev) & devices) == devices)
242 return dev;
243 }
244 return NULL;
245}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700246
247status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
248{
249 const size_t SIZE = 256;
250 char buffer[SIZE];
251 String8 result;
252
253 result.append("Clients:\n");
254 for (size_t i = 0; i < mClients.size(); ++i) {
255 wp<Client> wClient = mClients.valueAt(i);
256 if (wClient != 0) {
257 sp<Client> client = wClient.promote();
258 if (client != 0) {
259 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
260 result.append(buffer);
261 }
262 }
263 }
264 write(fd, result.string(), result.size());
265 return NO_ERROR;
266}
267
268
269status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
270{
271 const size_t SIZE = 256;
272 char buffer[SIZE];
273 String8 result;
274 int hardwareStatus = mHardwareStatus;
275
276 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
277 result.append(buffer);
278 write(fd, result.string(), result.size());
279 return NO_ERROR;
280}
281
282status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
283{
284 const size_t SIZE = 256;
285 char buffer[SIZE];
286 String8 result;
287 snprintf(buffer, SIZE, "Permission Denial: "
288 "can't dump AudioFlinger from pid=%d, uid=%d\n",
289 IPCThreadState::self()->getCallingPid(),
290 IPCThreadState::self()->getCallingUid());
291 result.append(buffer);
292 write(fd, result.string(), result.size());
293 return NO_ERROR;
294}
295
296static bool tryLock(Mutex& mutex)
297{
298 bool locked = false;
299 for (int i = 0; i < kDumpLockRetries; ++i) {
300 if (mutex.tryLock() == NO_ERROR) {
301 locked = true;
302 break;
303 }
304 usleep(kDumpLockSleep);
305 }
306 return locked;
307}
308
309status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
310{
311 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
312 dumpPermissionDenial(fd, args);
313 } else {
314 // get state of hardware lock
315 bool hardwareLocked = tryLock(mHardwareLock);
316 if (!hardwareLocked) {
317 String8 result(kHardwareLockedString);
318 write(fd, result.string(), result.size());
319 } else {
320 mHardwareLock.unlock();
321 }
322
323 bool locked = tryLock(mLock);
324
325 // failed to lock - AudioFlinger is probably deadlocked
326 if (!locked) {
327 String8 result(kDeadlockedString);
328 write(fd, result.string(), result.size());
329 }
330
331 dumpClients(fd, args);
332 dumpInternals(fd, args);
333
334 // dump playback threads
335 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
336 mPlaybackThreads.valueAt(i)->dump(fd, args);
337 }
338
339 // dump record threads
340 for (size_t i = 0; i < mRecordThreads.size(); i++) {
341 mRecordThreads.valueAt(i)->dump(fd, args);
342 }
343
Dima Zavin799a70e2011-04-18 16:57:27 -0700344 // dump all hardware devs
345 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
346 audio_hw_device_t *dev = mAudioHwDevs[i];
347 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348 }
349 if (locked) mLock.unlock();
350 }
351 return NO_ERROR;
352}
353
354
355// IAudioFlinger interface
356
357
358sp<IAudioTrack> AudioFlinger::createTrack(
359 pid_t pid,
360 int streamType,
361 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700362 uint32_t format,
363 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700364 int frameCount,
365 uint32_t flags,
366 const sp<IMemory>& sharedBuffer,
367 int output,
368 int *sessionId,
369 status_t *status)
370{
371 sp<PlaybackThread::Track> track;
372 sp<TrackHandle> trackHandle;
373 sp<Client> client;
374 wp<Client> wclient;
375 status_t lStatus;
376 int lSessionId;
377
Dima Zavinfce7a472011-04-19 22:30:36 -0700378 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700379 LOGE("invalid stream type");
380 lStatus = BAD_VALUE;
381 goto Exit;
382 }
383
384 {
385 Mutex::Autolock _l(mLock);
386 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700387 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700388 if (thread == NULL) {
389 LOGE("unknown output thread");
390 lStatus = BAD_VALUE;
391 goto Exit;
392 }
393
394 wclient = mClients.valueFor(pid);
395
396 if (wclient != NULL) {
397 client = wclient.promote();
398 } else {
399 client = new Client(this, pid);
400 mClients.add(pid, client);
401 }
402
Mathias Agopian65ab4712010-07-14 17:59:35 -0700403 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700404 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700406 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
407 if (mPlaybackThreads.keyAt(i) != output) {
408 // prevent same audio session on different output threads
409 uint32_t sessions = t->hasAudioSession(*sessionId);
410 if (sessions & PlaybackThread::TRACK_SESSION) {
411 lStatus = BAD_VALUE;
412 goto Exit;
413 }
414 // check if an effect with same session ID is waiting for a track to be created
415 if (sessions & PlaybackThread::EFFECT_SESSION) {
416 effectThread = t.get();
417 }
Eric Laurentde070132010-07-13 04:45:46 -0700418 }
419 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700420 lSessionId = *sessionId;
421 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700422 // if no audio session id is provided, create one here
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700423 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700424 if (sessionId != NULL) {
425 *sessionId = lSessionId;
426 }
427 }
428 LOGV("createTrack() lSessionId: %d", lSessionId);
429
430 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700431 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700432
433 // move effect chain to this output thread if an effect on same session was waiting
434 // for a track to be created
435 if (lStatus == NO_ERROR && effectThread != NULL) {
436 Mutex::Autolock _dl(thread->mLock);
437 Mutex::Autolock _sl(effectThread->mLock);
438 moveEffectChain_l(lSessionId, effectThread, thread, true);
439 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700440 }
441 if (lStatus == NO_ERROR) {
442 trackHandle = new TrackHandle(track);
443 } else {
444 // remove local strong reference to Client before deleting the Track so that the Client
445 // destructor is called by the TrackBase destructor with mLock held
446 client.clear();
447 track.clear();
448 }
449
450Exit:
451 if(status) {
452 *status = lStatus;
453 }
454 return trackHandle;
455}
456
457uint32_t AudioFlinger::sampleRate(int output) const
458{
459 Mutex::Autolock _l(mLock);
460 PlaybackThread *thread = checkPlaybackThread_l(output);
461 if (thread == NULL) {
462 LOGW("sampleRate() unknown thread %d", output);
463 return 0;
464 }
465 return thread->sampleRate();
466}
467
468int AudioFlinger::channelCount(int output) const
469{
470 Mutex::Autolock _l(mLock);
471 PlaybackThread *thread = checkPlaybackThread_l(output);
472 if (thread == NULL) {
473 LOGW("channelCount() unknown thread %d", output);
474 return 0;
475 }
476 return thread->channelCount();
477}
478
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700479uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700480{
481 Mutex::Autolock _l(mLock);
482 PlaybackThread *thread = checkPlaybackThread_l(output);
483 if (thread == NULL) {
484 LOGW("format() unknown thread %d", output);
485 return 0;
486 }
487 return thread->format();
488}
489
490size_t AudioFlinger::frameCount(int output) const
491{
492 Mutex::Autolock _l(mLock);
493 PlaybackThread *thread = checkPlaybackThread_l(output);
494 if (thread == NULL) {
495 LOGW("frameCount() unknown thread %d", output);
496 return 0;
497 }
498 return thread->frameCount();
499}
500
501uint32_t AudioFlinger::latency(int output) const
502{
503 Mutex::Autolock _l(mLock);
504 PlaybackThread *thread = checkPlaybackThread_l(output);
505 if (thread == NULL) {
506 LOGW("latency() unknown thread %d", output);
507 return 0;
508 }
509 return thread->latency();
510}
511
512status_t AudioFlinger::setMasterVolume(float value)
513{
514 // check calling permissions
515 if (!settingsAllowed()) {
516 return PERMISSION_DENIED;
517 }
518
519 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800520 { // scope for the lock
521 AutoMutex lock(mHardwareLock);
522 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700523 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800524 value = 1.0f;
525 }
526 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700527 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700528
Eric Laurent93575202011-01-18 18:39:02 -0800529 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700530 mMasterVolume = value;
531 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
532 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
533
534 return NO_ERROR;
535}
536
537status_t AudioFlinger::setMode(int mode)
538{
539 status_t ret;
540
541 // check calling permissions
542 if (!settingsAllowed()) {
543 return PERMISSION_DENIED;
544 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700545 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 LOGW("Illegal value: setMode(%d)", mode);
547 return BAD_VALUE;
548 }
549
550 { // scope for the lock
551 AutoMutex lock(mHardwareLock);
552 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700553 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700554 mHardwareStatus = AUDIO_HW_IDLE;
555 }
556
557 if (NO_ERROR == ret) {
558 Mutex::Autolock _l(mLock);
559 mMode = mode;
560 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
561 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700562 }
563
564 return ret;
565}
566
567status_t AudioFlinger::setMicMute(bool state)
568{
569 // check calling permissions
570 if (!settingsAllowed()) {
571 return PERMISSION_DENIED;
572 }
573
574 AutoMutex lock(mHardwareLock);
575 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700576 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700577 mHardwareStatus = AUDIO_HW_IDLE;
578 return ret;
579}
580
581bool AudioFlinger::getMicMute() const
582{
Dima Zavinfce7a472011-04-19 22:30:36 -0700583 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700585 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700586 mHardwareStatus = AUDIO_HW_IDLE;
587 return state;
588}
589
590status_t AudioFlinger::setMasterMute(bool muted)
591{
592 // check calling permissions
593 if (!settingsAllowed()) {
594 return PERMISSION_DENIED;
595 }
596
Eric Laurent93575202011-01-18 18:39:02 -0800597 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 mMasterMute = muted;
599 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
600 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
601
602 return NO_ERROR;
603}
604
605float AudioFlinger::masterVolume() const
606{
607 return mMasterVolume;
608}
609
610bool AudioFlinger::masterMute() const
611{
612 return mMasterMute;
613}
614
615status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
616{
617 // check calling permissions
618 if (!settingsAllowed()) {
619 return PERMISSION_DENIED;
620 }
621
Dima Zavinfce7a472011-04-19 22:30:36 -0700622 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700623 return BAD_VALUE;
624 }
625
626 AutoMutex lock(mLock);
627 PlaybackThread *thread = NULL;
628 if (output) {
629 thread = checkPlaybackThread_l(output);
630 if (thread == NULL) {
631 return BAD_VALUE;
632 }
633 }
634
635 mStreamTypes[stream].volume = value;
636
637 if (thread == NULL) {
638 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
639 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
640 }
641 } else {
642 thread->setStreamVolume(stream, value);
643 }
644
645 return NO_ERROR;
646}
647
648status_t AudioFlinger::setStreamMute(int stream, bool muted)
649{
650 // check calling permissions
651 if (!settingsAllowed()) {
652 return PERMISSION_DENIED;
653 }
654
Dima Zavinfce7a472011-04-19 22:30:36 -0700655 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
656 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700657 return BAD_VALUE;
658 }
659
Eric Laurent93575202011-01-18 18:39:02 -0800660 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700661 mStreamTypes[stream].mute = muted;
662 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
663 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
664
665 return NO_ERROR;
666}
667
668float AudioFlinger::streamVolume(int stream, int output) const
669{
Dima Zavinfce7a472011-04-19 22:30:36 -0700670 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700671 return 0.0f;
672 }
673
674 AutoMutex lock(mLock);
675 float volume;
676 if (output) {
677 PlaybackThread *thread = checkPlaybackThread_l(output);
678 if (thread == NULL) {
679 return 0.0f;
680 }
681 volume = thread->streamVolume(stream);
682 } else {
683 volume = mStreamTypes[stream].volume;
684 }
685
686 return volume;
687}
688
689bool AudioFlinger::streamMute(int stream) const
690{
Dima Zavinfce7a472011-04-19 22:30:36 -0700691 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700692 return true;
693 }
694
695 return mStreamTypes[stream].mute;
696}
697
Mathias Agopian65ab4712010-07-14 17:59:35 -0700698status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
699{
700 status_t result;
701
702 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
703 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
704 // check calling permissions
705 if (!settingsAllowed()) {
706 return PERMISSION_DENIED;
707 }
708
Mathias Agopian65ab4712010-07-14 17:59:35 -0700709 // ioHandle == 0 means the parameters are global to the audio hardware interface
710 if (ioHandle == 0) {
711 AutoMutex lock(mHardwareLock);
712 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700713 status_t final_result = NO_ERROR;
714 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
715 audio_hw_device_t *dev = mAudioHwDevs[i];
716 result = dev->set_parameters(dev, keyValuePairs.string());
717 final_result = result ?: final_result;
718 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700719 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700720 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700721 }
722
723 // hold a strong ref on thread in case closeOutput() or closeInput() is called
724 // and the thread is exited once the lock is released
725 sp<ThreadBase> thread;
726 {
727 Mutex::Autolock _l(mLock);
728 thread = checkPlaybackThread_l(ioHandle);
729 if (thread == NULL) {
730 thread = checkRecordThread_l(ioHandle);
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700731 } else if (thread.get() == primaryPlaybackThread_l()) {
732 // indicate output device change to all input threads for pre processing
733 AudioParameter param = AudioParameter(keyValuePairs);
734 int value;
735 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
736 for (size_t i = 0; i < mRecordThreads.size(); i++) {
737 mRecordThreads.valueAt(i)->setParameters(keyValuePairs);
738 }
739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700740 }
741 }
742 if (thread != NULL) {
743 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700744 return result;
745 }
746 return BAD_VALUE;
747}
748
749String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
750{
751// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
752// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
753
754 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700755 String8 out_s8;
756
Dima Zavin799a70e2011-04-18 16:57:27 -0700757 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
758 audio_hw_device_t *dev = mAudioHwDevs[i];
759 char *s = dev->get_parameters(dev, keys.string());
760 out_s8 += String8(s);
761 free(s);
762 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700763 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700764 }
765
766 Mutex::Autolock _l(mLock);
767
768 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
769 if (playbackThread != NULL) {
770 return playbackThread->getParameters(keys);
771 }
772 RecordThread *recordThread = checkRecordThread_l(ioHandle);
773 if (recordThread != NULL) {
774 return recordThread->getParameters(keys);
775 }
776 return String8("");
777}
778
779size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
780{
Dima Zavin799a70e2011-04-18 16:57:27 -0700781 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700782}
783
784unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
785{
786 if (ioHandle == 0) {
787 return 0;
788 }
789
790 Mutex::Autolock _l(mLock);
791
792 RecordThread *recordThread = checkRecordThread_l(ioHandle);
793 if (recordThread != NULL) {
794 return recordThread->getInputFramesLost();
795 }
796 return 0;
797}
798
799status_t AudioFlinger::setVoiceVolume(float value)
800{
801 // check calling permissions
802 if (!settingsAllowed()) {
803 return PERMISSION_DENIED;
804 }
805
806 AutoMutex lock(mHardwareLock);
807 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700808 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700809 mHardwareStatus = AUDIO_HW_IDLE;
810
811 return ret;
812}
813
814status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
815{
816 status_t status;
817
818 Mutex::Autolock _l(mLock);
819
820 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
821 if (playbackThread != NULL) {
822 return playbackThread->getRenderPosition(halFrames, dspFrames);
823 }
824
825 return BAD_VALUE;
826}
827
828void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
829{
830
831 Mutex::Autolock _l(mLock);
832
833 int pid = IPCThreadState::self()->getCallingPid();
834 if (mNotificationClients.indexOfKey(pid) < 0) {
835 sp<NotificationClient> notificationClient = new NotificationClient(this,
836 client,
837 pid);
838 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
839
840 mNotificationClients.add(pid, notificationClient);
841
842 sp<IBinder> binder = client->asBinder();
843 binder->linkToDeath(notificationClient);
844
845 // the config change is always sent from playback or record threads to avoid deadlock
846 // with AudioSystem::gLock
847 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
848 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
849 }
850
851 for (size_t i = 0; i < mRecordThreads.size(); i++) {
852 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
853 }
854 }
855}
856
857void AudioFlinger::removeNotificationClient(pid_t pid)
858{
859 Mutex::Autolock _l(mLock);
860
861 int index = mNotificationClients.indexOfKey(pid);
862 if (index >= 0) {
863 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
864 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700865 mNotificationClients.removeItem(pid);
866 }
867}
868
869// audioConfigChanged_l() must be called with AudioFlinger::mLock held
870void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
871{
872 size_t size = mNotificationClients.size();
873 for (size_t i = 0; i < size; i++) {
874 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
875 }
876}
877
878// removeClient_l() must be called with AudioFlinger::mLock held
879void AudioFlinger::removeClient_l(pid_t pid)
880{
881 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
882 mClients.removeItem(pid);
883}
884
885
886// ----------------------------------------------------------------------------
887
Eric Laurent7c7f10b2011-06-17 21:29:58 -0700888AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700889 : Thread(false),
890 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentfeb0db62011-07-22 09:04:31 -0700891 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false),
892 mDevice(device)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700893{
Eric Laurentfeb0db62011-07-22 09:04:31 -0700894 mDeathRecipient = new PMDeathRecipient(this);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700895}
896
897AudioFlinger::ThreadBase::~ThreadBase()
898{
899 mParamCond.broadcast();
900 mNewParameters.clear();
Eric Laurentfeb0db62011-07-22 09:04:31 -0700901 // do not lock the mutex in destructor
902 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700903}
904
905void AudioFlinger::ThreadBase::exit()
906{
907 // keep a strong ref on ourself so that we wont get
908 // destroyed in the middle of requestExitAndWait()
909 sp <ThreadBase> strongMe = this;
910
911 LOGV("ThreadBase::exit");
912 {
913 AutoMutex lock(&mLock);
914 mExiting = true;
915 requestExit();
916 mWaitWorkCV.signal();
917 }
918 requestExitAndWait();
919}
920
921uint32_t AudioFlinger::ThreadBase::sampleRate() const
922{
923 return mSampleRate;
924}
925
926int AudioFlinger::ThreadBase::channelCount() const
927{
928 return (int)mChannelCount;
929}
930
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700931uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700932{
933 return mFormat;
934}
935
936size_t AudioFlinger::ThreadBase::frameCount() const
937{
938 return mFrameCount;
939}
940
941status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
942{
943 status_t status;
944
945 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
946 Mutex::Autolock _l(mLock);
947
948 mNewParameters.add(keyValuePairs);
949 mWaitWorkCV.signal();
950 // wait condition with timeout in case the thread loop has exited
951 // before the request could be processed
952 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
953 status = mParamStatus;
954 mWaitWorkCV.signal();
955 } else {
956 status = TIMED_OUT;
957 }
958 return status;
959}
960
961void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
962{
963 Mutex::Autolock _l(mLock);
964 sendConfigEvent_l(event, param);
965}
966
967// sendConfigEvent_l() must be called with ThreadBase::mLock held
968void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
969{
970 ConfigEvent *configEvent = new ConfigEvent();
971 configEvent->mEvent = event;
972 configEvent->mParam = param;
973 mConfigEvents.add(configEvent);
974 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
975 mWaitWorkCV.signal();
976}
977
978void AudioFlinger::ThreadBase::processConfigEvents()
979{
980 mLock.lock();
981 while(!mConfigEvents.isEmpty()) {
982 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
983 ConfigEvent *configEvent = mConfigEvents[0];
984 mConfigEvents.removeAt(0);
985 // release mLock before locking AudioFlinger mLock: lock order is always
986 // AudioFlinger then ThreadBase to avoid cross deadlock
987 mLock.unlock();
988 mAudioFlinger->mLock.lock();
989 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
990 mAudioFlinger->mLock.unlock();
991 delete configEvent;
992 mLock.lock();
993 }
994 mLock.unlock();
995}
996
997status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
998{
999 const size_t SIZE = 256;
1000 char buffer[SIZE];
1001 String8 result;
1002
1003 bool locked = tryLock(mLock);
1004 if (!locked) {
1005 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
1006 write(fd, buffer, strlen(buffer));
1007 }
1008
1009 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
1010 result.append(buffer);
1011 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1012 result.append(buffer);
1013 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1014 result.append(buffer);
1015 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1016 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001017 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1018 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001019 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1020 result.append(buffer);
1021 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1022 result.append(buffer);
1023
1024 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1025 result.append(buffer);
1026 result.append(" Index Command");
1027 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1028 snprintf(buffer, SIZE, "\n %02d ", i);
1029 result.append(buffer);
1030 result.append(mNewParameters[i]);
1031 }
1032
1033 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1034 result.append(buffer);
1035 snprintf(buffer, SIZE, " Index event param\n");
1036 result.append(buffer);
1037 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1038 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1039 result.append(buffer);
1040 }
1041 result.append("\n");
1042
1043 write(fd, result.string(), result.size());
1044
1045 if (locked) {
1046 mLock.unlock();
1047 }
1048 return NO_ERROR;
1049}
1050
Eric Laurent1d2bff02011-07-24 17:49:51 -07001051status_t AudioFlinger::ThreadBase::dumpEffectChains(int fd, const Vector<String16>& args)
1052{
1053 const size_t SIZE = 256;
1054 char buffer[SIZE];
1055 String8 result;
1056
1057 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1058 write(fd, buffer, strlen(buffer));
1059
1060 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1061 sp<EffectChain> chain = mEffectChains[i];
1062 if (chain != 0) {
1063 chain->dump(fd, args);
1064 }
1065 }
1066 return NO_ERROR;
1067}
1068
Eric Laurentfeb0db62011-07-22 09:04:31 -07001069void AudioFlinger::ThreadBase::acquireWakeLock()
1070{
1071 Mutex::Autolock _l(mLock);
1072 acquireWakeLock_l();
1073}
1074
1075void AudioFlinger::ThreadBase::acquireWakeLock_l()
1076{
1077 if (mPowerManager == 0) {
1078 // use checkService() to avoid blocking if power service is not up yet
1079 sp<IBinder> binder =
1080 defaultServiceManager()->checkService(String16("power"));
1081 if (binder == 0) {
1082 LOGW("Thread %s cannot connect to the power manager service", mName);
1083 } else {
1084 mPowerManager = interface_cast<IPowerManager>(binder);
1085 binder->linkToDeath(mDeathRecipient);
1086 }
1087 }
1088 if (mPowerManager != 0) {
1089 sp<IBinder> binder = new BBinder();
1090 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
1091 binder,
1092 String16(mName));
1093 if (status == NO_ERROR) {
1094 mWakeLockToken = binder;
1095 }
1096 LOGV("acquireWakeLock_l() %s status %d", mName, status);
1097 }
1098}
1099
1100void AudioFlinger::ThreadBase::releaseWakeLock()
1101{
1102 Mutex::Autolock _l(mLock);
Eric Laurent6dbe8832011-07-28 13:59:02 -07001103 releaseWakeLock_l();
Eric Laurentfeb0db62011-07-22 09:04:31 -07001104}
1105
1106void AudioFlinger::ThreadBase::releaseWakeLock_l()
1107{
1108 if (mWakeLockToken != 0) {
1109 LOGV("releaseWakeLock_l() %s", mName);
1110 if (mPowerManager != 0) {
1111 mPowerManager->releaseWakeLock(mWakeLockToken, 0);
1112 }
1113 mWakeLockToken.clear();
1114 }
1115}
1116
1117void AudioFlinger::ThreadBase::clearPowerManager()
1118{
1119 Mutex::Autolock _l(mLock);
1120 releaseWakeLock_l();
1121 mPowerManager.clear();
1122}
1123
1124void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who)
1125{
1126 sp<ThreadBase> thread = mThread.promote();
1127 if (thread != 0) {
1128 thread->clearPowerManager();
1129 }
1130 LOGW("power manager service died !!!");
1131}
Eric Laurent1d2bff02011-07-24 17:49:51 -07001132
Eric Laurent59255e42011-07-27 19:49:51 -07001133void AudioFlinger::ThreadBase::setEffectSuspended(
1134 const effect_uuid_t *type, bool suspend, int sessionId)
1135{
1136 Mutex::Autolock _l(mLock);
1137 setEffectSuspended_l(type, suspend, sessionId);
1138}
1139
1140void AudioFlinger::ThreadBase::setEffectSuspended_l(
1141 const effect_uuid_t *type, bool suspend, int sessionId)
1142{
1143 sp<EffectChain> chain;
1144 chain = getEffectChain_l(sessionId);
1145 if (chain != 0) {
1146 if (type != NULL) {
1147 chain->setEffectSuspended_l(type, suspend);
1148 } else {
1149 chain->setEffectSuspendedAll_l(suspend);
1150 }
1151 }
1152
1153 updateSuspendedSessions_l(type, suspend, sessionId);
1154}
1155
1156void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1157{
1158 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1159 if (index < 0) {
1160 return;
1161 }
1162
1163 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects =
1164 mSuspendedSessions.editValueAt(index);
1165
1166 for (size_t i = 0; i < sessionEffects.size(); i++) {
1167 sp <SuspendedSessionDesc> desc = sessionEffects.valueAt(i);
1168 for (int j = 0; j < desc->mRefCount; j++) {
1169 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1170 chain->setEffectSuspendedAll_l(true);
1171 } else {
1172 LOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1173 desc->mType.timeLow);
1174 chain->setEffectSuspended_l(&desc->mType, true);
1175 }
1176 }
1177 }
1178}
1179
1180void AudioFlinger::ThreadBase::updateSuspendedSessionsOnRemoveEffectChain_l(
1181 const sp<EffectChain>& chain)
1182{
1183 int index = mSuspendedSessions.indexOfKey(chain->sessionId());
1184 if (index < 0) {
1185 return;
1186 }
1187 LOGV("updateSuspendedSessionsOnRemoveEffectChain_l() removed suspended session %d",
1188 chain->sessionId());
1189 mSuspendedSessions.removeItemsAt(index);
1190}
1191
1192void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1193 bool suspend,
1194 int sessionId)
1195{
1196 int index = mSuspendedSessions.indexOfKey(sessionId);
1197
1198 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1199
1200 if (suspend) {
1201 if (index >= 0) {
1202 sessionEffects = mSuspendedSessions.editValueAt(index);
1203 } else {
1204 mSuspendedSessions.add(sessionId, sessionEffects);
1205 }
1206 } else {
1207 if (index < 0) {
1208 return;
1209 }
1210 sessionEffects = mSuspendedSessions.editValueAt(index);
1211 }
1212
1213
1214 int key = EffectChain::kKeyForSuspendAll;
1215 if (type != NULL) {
1216 key = type->timeLow;
1217 }
1218 index = sessionEffects.indexOfKey(key);
1219
1220 sp <SuspendedSessionDesc> desc;
1221 if (suspend) {
1222 if (index >= 0) {
1223 desc = sessionEffects.valueAt(index);
1224 } else {
1225 desc = new SuspendedSessionDesc();
1226 if (type != NULL) {
1227 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
1228 }
1229 sessionEffects.add(key, desc);
1230 LOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1231 }
1232 desc->mRefCount++;
1233 } else {
1234 if (index < 0) {
1235 return;
1236 }
1237 desc = sessionEffects.valueAt(index);
1238 if (--desc->mRefCount == 0) {
1239 LOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1240 sessionEffects.removeItemsAt(index);
1241 if (sessionEffects.isEmpty()) {
1242 LOGV("updateSuspendedSessions_l() restore removing session %d",
1243 sessionId);
1244 mSuspendedSessions.removeItem(sessionId);
1245 }
1246 }
1247 }
1248 if (!sessionEffects.isEmpty()) {
1249 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1250 }
1251}
1252
1253void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1254 bool enabled,
1255 int sessionId)
1256{
1257 Mutex::Autolock _l(mLock);
1258
1259 // TODO: implement PlaybackThread or RecordThread specific behavior here
1260
1261 sp<EffectChain> chain = getEffectChain_l(sessionId);
1262 if (chain != 0) {
1263 chain->checkSuspendOnEffectEnabled(effect, enabled);
1264 }
1265}
1266
Mathias Agopian65ab4712010-07-14 17:59:35 -07001267// ----------------------------------------------------------------------------
1268
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001269AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1270 AudioStreamOut* output,
1271 int id,
1272 uint32_t device)
1273 : ThreadBase(audioFlinger, id, device),
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001275 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001276{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001277 snprintf(mName, kNameLength, "AudioOut_%d", id);
1278
Mathias Agopian65ab4712010-07-14 17:59:35 -07001279 readOutputParameters();
1280
1281 mMasterVolume = mAudioFlinger->masterVolume();
1282 mMasterMute = mAudioFlinger->masterMute();
1283
Dima Zavinfce7a472011-04-19 22:30:36 -07001284 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001285 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1286 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1287 }
1288}
1289
1290AudioFlinger::PlaybackThread::~PlaybackThread()
1291{
1292 delete [] mMixBuffer;
1293}
1294
1295status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1296{
1297 dumpInternals(fd, args);
1298 dumpTracks(fd, args);
1299 dumpEffectChains(fd, args);
1300 return NO_ERROR;
1301}
1302
1303status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1304{
1305 const size_t SIZE = 256;
1306 char buffer[SIZE];
1307 String8 result;
1308
1309 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1310 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001311 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 -07001312 for (size_t i = 0; i < mTracks.size(); ++i) {
1313 sp<Track> track = mTracks[i];
1314 if (track != 0) {
1315 track->dump(buffer, SIZE);
1316 result.append(buffer);
1317 }
1318 }
1319
1320 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1321 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001322 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 -07001323 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1324 wp<Track> wTrack = mActiveTracks[i];
1325 if (wTrack != 0) {
1326 sp<Track> track = wTrack.promote();
1327 if (track != 0) {
1328 track->dump(buffer, SIZE);
1329 result.append(buffer);
1330 }
1331 }
1332 }
1333 write(fd, result.string(), result.size());
1334 return NO_ERROR;
1335}
1336
Mathias Agopian65ab4712010-07-14 17:59:35 -07001337status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1338{
1339 const size_t SIZE = 256;
1340 char buffer[SIZE];
1341 String8 result;
1342
1343 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1344 result.append(buffer);
1345 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1346 result.append(buffer);
1347 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1348 result.append(buffer);
1349 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1350 result.append(buffer);
1351 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1352 result.append(buffer);
1353 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1354 result.append(buffer);
1355 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1356 result.append(buffer);
1357 write(fd, result.string(), result.size());
1358
1359 dumpBase(fd, args);
1360
1361 return NO_ERROR;
1362}
1363
1364// Thread virtuals
1365status_t AudioFlinger::PlaybackThread::readyToRun()
1366{
1367 if (mSampleRate == 0) {
1368 LOGE("No working audio driver found.");
1369 return NO_INIT;
1370 }
1371 LOGI("AudioFlinger's thread %p ready to run", this);
1372 return NO_ERROR;
1373}
1374
1375void AudioFlinger::PlaybackThread::onFirstRef()
1376{
Eric Laurentfeb0db62011-07-22 09:04:31 -07001377 run(mName, ANDROID_PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378}
1379
1380// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1381sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1382 const sp<AudioFlinger::Client>& client,
1383 int streamType,
1384 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001385 uint32_t format,
1386 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001387 int frameCount,
1388 const sp<IMemory>& sharedBuffer,
1389 int sessionId,
1390 status_t *status)
1391{
1392 sp<Track> track;
1393 status_t lStatus;
1394
1395 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001396 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1397 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1398 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1399 "for output %p with format %d",
1400 sampleRate, format, channelMask, mOutput, mFormat);
1401 lStatus = BAD_VALUE;
1402 goto Exit;
1403 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001404 }
1405 } else {
1406 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1407 if (sampleRate > mSampleRate*2) {
1408 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1409 lStatus = BAD_VALUE;
1410 goto Exit;
1411 }
1412 }
1413
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001414 lStatus = initCheck();
1415 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001416 LOGE("Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417 goto Exit;
1418 }
1419
1420 { // scope for mLock
1421 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001422
1423 // all tracks in same audio session must share the same routing strategy otherwise
1424 // conflicts will happen when tracks are moved from one output to another by audio policy
1425 // manager
1426 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001427 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001428 for (size_t i = 0; i < mTracks.size(); ++i) {
1429 sp<Track> t = mTracks[i];
1430 if (t != 0) {
1431 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001432 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001433 lStatus = BAD_VALUE;
1434 goto Exit;
1435 }
1436 }
1437 }
1438
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001440 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001441 if (track->getCblk() == NULL || track->name() < 0) {
1442 lStatus = NO_MEMORY;
1443 goto Exit;
1444 }
1445 mTracks.add(track);
1446
1447 sp<EffectChain> chain = getEffectChain_l(sessionId);
1448 if (chain != 0) {
1449 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1450 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001451 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001452 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001453 }
1454 }
1455 lStatus = NO_ERROR;
1456
1457Exit:
1458 if(status) {
1459 *status = lStatus;
1460 }
1461 return track;
1462}
1463
1464uint32_t AudioFlinger::PlaybackThread::latency() const
1465{
1466 if (mOutput) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001467 return mOutput->stream->get_latency(mOutput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001468 }
1469 else {
1470 return 0;
1471 }
1472}
1473
1474status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1475{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001476 mMasterVolume = value;
1477 return NO_ERROR;
1478}
1479
1480status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1481{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001482 mMasterMute = muted;
1483 return NO_ERROR;
1484}
1485
1486float AudioFlinger::PlaybackThread::masterVolume() const
1487{
1488 return mMasterVolume;
1489}
1490
1491bool AudioFlinger::PlaybackThread::masterMute() const
1492{
1493 return mMasterMute;
1494}
1495
1496status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1497{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001498 mStreamTypes[stream].volume = value;
1499 return NO_ERROR;
1500}
1501
1502status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1503{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001504 mStreamTypes[stream].mute = muted;
1505 return NO_ERROR;
1506}
1507
1508float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1509{
1510 return mStreamTypes[stream].volume;
1511}
1512
1513bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1514{
1515 return mStreamTypes[stream].mute;
1516}
1517
Mathias Agopian65ab4712010-07-14 17:59:35 -07001518// addTrack_l() must be called with ThreadBase::mLock held
1519status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1520{
1521 status_t status = ALREADY_EXISTS;
1522
1523 // set retry count for buffer fill
1524 track->mRetryCount = kMaxTrackStartupRetries;
1525 if (mActiveTracks.indexOf(track) < 0) {
1526 // the track is newly added, make sure it fills up all its
1527 // buffers before playing. This is to ensure the client will
1528 // effectively get the latency it requested.
1529 track->mFillingUpStatus = Track::FS_FILLING;
1530 track->mResetDone = false;
1531 mActiveTracks.add(track);
1532 if (track->mainBuffer() != mMixBuffer) {
1533 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1534 if (chain != 0) {
1535 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001536 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001537 }
1538 }
1539
1540 status = NO_ERROR;
1541 }
1542
1543 LOGV("mWaitWorkCV.broadcast");
1544 mWaitWorkCV.broadcast();
1545
1546 return status;
1547}
1548
1549// destroyTrack_l() must be called with ThreadBase::mLock held
1550void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1551{
1552 track->mState = TrackBase::TERMINATED;
1553 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001554 removeTrack_l(track);
1555 }
1556}
1557
1558void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1559{
1560 mTracks.remove(track);
1561 deleteTrackName_l(track->name());
1562 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1563 if (chain != 0) {
1564 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001565 }
1566}
1567
1568String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1569{
Dima Zavinfce7a472011-04-19 22:30:36 -07001570 String8 out_s8;
1571 char *s;
1572
Dima Zavin799a70e2011-04-18 16:57:27 -07001573 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001574 out_s8 = String8(s);
1575 free(s);
1576 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001577}
1578
1579// destroyTrack_l() must be called with AudioFlinger::mLock held
1580void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1581 AudioSystem::OutputDescriptor desc;
1582 void *param2 = 0;
1583
1584 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1585
1586 switch (event) {
1587 case AudioSystem::OUTPUT_OPENED:
1588 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001589 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001590 desc.samplingRate = mSampleRate;
1591 desc.format = mFormat;
1592 desc.frameCount = mFrameCount;
1593 desc.latency = latency();
1594 param2 = &desc;
1595 break;
1596
1597 case AudioSystem::STREAM_CONFIG_CHANGED:
1598 param2 = &param;
1599 case AudioSystem::OUTPUT_CLOSED:
1600 default:
1601 break;
1602 }
1603 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1604}
1605
1606void AudioFlinger::PlaybackThread::readOutputParameters()
1607{
Dima Zavin799a70e2011-04-18 16:57:27 -07001608 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001609 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1610 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001611 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1612 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1613 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001614
1615 // FIXME - Current mixer implementation only supports stereo output: Always
1616 // Allocate a stereo buffer even if HW output is mono.
1617 if (mMixBuffer != NULL) delete[] mMixBuffer;
1618 mMixBuffer = new int16_t[mFrameCount * 2];
1619 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1620
Eric Laurentde070132010-07-13 04:45:46 -07001621 // force reconfiguration of effect chains and engines to take new buffer size and audio
1622 // parameters into account
1623 // Note that mLock is not held when readOutputParameters() is called from the constructor
1624 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1625 // matter.
1626 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1627 Vector< sp<EffectChain> > effectChains = mEffectChains;
1628 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001629 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001630 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001631}
1632
1633status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1634{
1635 if (halFrames == 0 || dspFrames == 0) {
1636 return BAD_VALUE;
1637 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001638 if (initCheck() != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001639 return INVALID_OPERATION;
1640 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001641 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001642
Dima Zavin799a70e2011-04-18 16:57:27 -07001643 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001644}
1645
Eric Laurent39e94f82010-07-28 01:32:47 -07001646uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001647{
1648 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001649 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001650 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001651 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001652 }
1653
1654 for (size_t i = 0; i < mTracks.size(); ++i) {
1655 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001656 if (sessionId == track->sessionId() &&
1657 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001658 result |= TRACK_SESSION;
1659 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001660 }
1661 }
1662
Eric Laurent39e94f82010-07-28 01:32:47 -07001663 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001664}
1665
Eric Laurentde070132010-07-13 04:45:46 -07001666uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1667{
Dima Zavinfce7a472011-04-19 22:30:36 -07001668 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001669 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001670 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1671 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001672 }
1673 for (size_t i = 0; i < mTracks.size(); i++) {
1674 sp<Track> track = mTracks[i];
1675 if (sessionId == track->sessionId() &&
1676 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001677 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001678 }
1679 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001680 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001681}
1682
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683
1684// ----------------------------------------------------------------------------
1685
Dima Zavin799a70e2011-04-18 16:57:27 -07001686AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001687 : PlaybackThread(audioFlinger, output, id, device),
1688 mAudioMixer(0)
1689{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07001690 mType = ThreadBase::MIXER;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001691 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1692
1693 // FIXME - Current mixer implementation only supports stereo output
1694 if (mChannelCount == 1) {
1695 LOGE("Invalid audio hardware channel count");
1696 }
1697}
1698
1699AudioFlinger::MixerThread::~MixerThread()
1700{
1701 delete mAudioMixer;
1702}
1703
1704bool AudioFlinger::MixerThread::threadLoop()
1705{
1706 Vector< sp<Track> > tracksToRemove;
1707 uint32_t mixerStatus = MIXER_IDLE;
1708 nsecs_t standbyTime = systemTime();
1709 size_t mixBufferSize = mFrameCount * mFrameSize;
1710 // FIXME: Relaxed timing because of a certain device that can't meet latency
1711 // Should be reduced to 2x after the vendor fixes the driver issue
1712 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1713 nsecs_t lastWarning = 0;
1714 bool longStandbyExit = false;
1715 uint32_t activeSleepTime = activeSleepTimeUs();
1716 uint32_t idleSleepTime = idleSleepTimeUs();
1717 uint32_t sleepTime = idleSleepTime;
1718 Vector< sp<EffectChain> > effectChains;
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001719#ifdef DEBUG_CPU_USAGE
1720 ThreadCpuUsage cpu;
1721 const CentralTendencyStatistics& stats = cpu.statistics();
1722#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001723
Eric Laurentfeb0db62011-07-22 09:04:31 -07001724 acquireWakeLock();
1725
Mathias Agopian65ab4712010-07-14 17:59:35 -07001726 while (!exitPending())
1727 {
Glenn Kasten4d8d0c32011-07-08 15:26:12 -07001728#ifdef DEBUG_CPU_USAGE
1729 cpu.sampleAndEnable();
1730 unsigned n = stats.n();
1731 // cpu.elapsed() is expensive, so don't call it every loop
1732 if ((n & 127) == 1) {
1733 long long elapsed = cpu.elapsed();
1734 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
1735 double perLoop = elapsed / (double) n;
1736 double perLoop100 = perLoop * 0.01;
1737 double mean = stats.mean();
1738 double stddev = stats.stddev();
1739 double minimum = stats.minimum();
1740 double maximum = stats.maximum();
1741 cpu.resetStatistics();
1742 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",
1743 elapsed * .000000001, n, perLoop * .000001,
1744 mean * .001,
1745 stddev * .001,
1746 minimum * .001,
1747 maximum * .001,
1748 mean / perLoop100,
1749 stddev / perLoop100,
1750 minimum / perLoop100,
1751 maximum / perLoop100);
1752 }
1753 }
1754#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -07001755 processConfigEvents();
1756
1757 mixerStatus = MIXER_IDLE;
1758 { // scope for mLock
1759
1760 Mutex::Autolock _l(mLock);
1761
1762 if (checkForNewParameters_l()) {
1763 mixBufferSize = mFrameCount * mFrameSize;
1764 // FIXME: Relaxed timing because of a certain device that can't meet latency
1765 // Should be reduced to 2x after the vendor fixes the driver issue
1766 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1767 activeSleepTime = activeSleepTimeUs();
1768 idleSleepTime = idleSleepTimeUs();
1769 }
1770
1771 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1772
1773 // put audio hardware into standby after short delay
1774 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1775 mSuspended) {
1776 if (!mStandby) {
1777 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001778 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001779 mStandby = true;
1780 mBytesWritten = 0;
1781 }
1782
1783 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1784 // we're about to wait, flush the binder command buffer
1785 IPCThreadState::self()->flushCommands();
1786
1787 if (exitPending()) break;
1788
Eric Laurentfeb0db62011-07-22 09:04:31 -07001789 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001790 // wait until we have something to do...
1791 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1792 mWaitWorkCV.wait(mLock);
1793 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07001794 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795
1796 if (mMasterMute == false) {
1797 char value[PROPERTY_VALUE_MAX];
1798 property_get("ro.audio.silent", value, "0");
1799 if (atoi(value)) {
1800 LOGD("Silence is golden");
1801 setMasterMute(true);
1802 }
1803 }
1804
1805 standbyTime = systemTime() + kStandbyTimeInNsecs;
1806 sleepTime = idleSleepTime;
1807 continue;
1808 }
1809 }
1810
1811 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1812
1813 // prevent any changes in effect chain list and in each effect chain
1814 // during mixing and effect process as the audio buffers could be deleted
1815 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001816 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001817 }
1818
1819 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1820 // mix buffers...
1821 mAudioMixer->process();
1822 sleepTime = 0;
1823 standbyTime = systemTime() + kStandbyTimeInNsecs;
1824 //TODO: delay standby when effects have a tail
1825 } else {
1826 // If no tracks are ready, sleep once for the duration of an output
1827 // buffer size, then write 0s to the output
1828 if (sleepTime == 0) {
1829 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1830 sleepTime = activeSleepTime;
1831 } else {
1832 sleepTime = idleSleepTime;
1833 }
1834 } else if (mBytesWritten != 0 ||
1835 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1836 memset (mMixBuffer, 0, mixBufferSize);
1837 sleepTime = 0;
1838 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1839 }
1840 // TODO add standby time extension fct of effect tail
1841 }
1842
1843 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001844 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001845 }
1846 // sleepTime == 0 means we must write to audio hardware
1847 if (sleepTime == 0) {
1848 for (size_t i = 0; i < effectChains.size(); i ++) {
1849 effectChains[i]->process_l();
1850 }
1851 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001852 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001853 mLastWriteTime = systemTime();
1854 mInWrite = true;
1855 mBytesWritten += mixBufferSize;
1856
Dima Zavin799a70e2011-04-18 16:57:27 -07001857 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001858 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1859 mNumWrites++;
1860 mInWrite = false;
1861 nsecs_t now = systemTime();
1862 nsecs_t delta = now - mLastWriteTime;
1863 if (delta > maxPeriod) {
1864 mNumDelayedWrites++;
1865 if ((now - lastWarning) > kWarningThrottle) {
1866 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1867 ns2ms(delta), mNumDelayedWrites, this);
1868 lastWarning = now;
1869 }
1870 if (mStandby) {
1871 longStandbyExit = true;
1872 }
1873 }
1874 mStandby = false;
1875 } else {
1876 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001877 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001878 usleep(sleepTime);
1879 }
1880
1881 // finally let go of all our tracks, without the lock held
1882 // since we can't guarantee the destructors won't acquire that
1883 // same lock.
1884 tracksToRemove.clear();
1885
1886 // Effect chains will be actually deleted here if they were removed from
1887 // mEffectChains list during mixing or effects processing
1888 effectChains.clear();
1889 }
1890
1891 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001892 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894
Eric Laurentfeb0db62011-07-22 09:04:31 -07001895 releaseWakeLock();
1896
Mathias Agopian65ab4712010-07-14 17:59:35 -07001897 LOGV("MixerThread %p exiting", this);
1898 return false;
1899}
1900
1901// prepareTracks_l() must be called with ThreadBase::mLock held
1902uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1903{
1904
1905 uint32_t mixerStatus = MIXER_IDLE;
1906 // find out which tracks need to be processed
1907 size_t count = activeTracks.size();
1908 size_t mixedTracks = 0;
1909 size_t tracksWithEffect = 0;
1910
1911 float masterVolume = mMasterVolume;
1912 bool masterMute = mMasterMute;
1913
Eric Laurent571d49c2010-08-11 05:20:11 -07001914 if (masterMute) {
1915 masterVolume = 0;
1916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001917 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07001918 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001919 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07001920 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07001921 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 masterVolume = (float)((v + (1 << 23)) >> 24);
1923 chain.clear();
1924 }
1925
1926 for (size_t i=0 ; i<count ; i++) {
1927 sp<Track> t = activeTracks[i].promote();
1928 if (t == 0) continue;
1929
1930 Track* const track = t.get();
1931 audio_track_cblk_t* cblk = track->cblk();
1932
1933 // The first time a track is added we wait
1934 // for all its buffers to be filled before processing it
1935 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07001936 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07001937 !track->isPaused() && !track->isTerminated())
1938 {
1939 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1940
1941 mixedTracks++;
1942
1943 // track->mainBuffer() != mMixBuffer means there is an effect chain
1944 // connected to the track
1945 chain.clear();
1946 if (track->mainBuffer() != mMixBuffer) {
1947 chain = getEffectChain_l(track->sessionId());
1948 // Delegate volume control to effect in track effect chain if needed
1949 if (chain != 0) {
1950 tracksWithEffect++;
1951 } else {
1952 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1953 track->name(), track->sessionId());
1954 }
1955 }
1956
1957
1958 int param = AudioMixer::VOLUME;
1959 if (track->mFillingUpStatus == Track::FS_FILLED) {
1960 // no ramp for the first volume setting
1961 track->mFillingUpStatus = Track::FS_ACTIVE;
1962 if (track->mState == TrackBase::RESUMING) {
1963 track->mState = TrackBase::ACTIVE;
1964 param = AudioMixer::RAMP_VOLUME;
1965 }
Eric Laurent243f5f92011-02-28 16:52:51 -08001966 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001967 } else if (cblk->server != 0) {
1968 // If the track is stopped before the first frame was mixed,
1969 // do not apply ramp
1970 param = AudioMixer::RAMP_VOLUME;
1971 }
1972
1973 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07001974 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07001975 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001977 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001978 if (track->isPausing()) {
1979 track->setPaused();
1980 }
1981 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001982
Mathias Agopian65ab4712010-07-14 17:59:35 -07001983 // read original volumes with volume control
1984 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001985 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07001986 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1987 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988
Eric Laurente0aed6d2010-09-10 17:44:44 -07001989 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001990 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07001991 // Delegate volume control to effect in track effect chain if needed
1992 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1993 // Do not ramp volume if volume is controlled by effect
1994 param = AudioMixer::VOLUME;
1995 track->mHasVolumeController = true;
1996 } else {
1997 // force no volume ramp when volume controller was just disabled or removed
1998 // from effect chain to avoid volume spike
1999 if (track->mHasVolumeController) {
2000 param = AudioMixer::VOLUME;
2001 }
2002 track->mHasVolumeController = false;
2003 }
2004
2005 // Convert volumes from 8.24 to 4.12 format
2006 int16_t left, right, aux;
2007 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2008 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2009 left = int16_t(v_clamped);
2010 v_clamped = (vr + (1 << 11)) >> 12;
2011 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2012 right = int16_t(v_clamped);
2013
2014 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
2015 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002016
Mathias Agopian65ab4712010-07-14 17:59:35 -07002017 // XXX: these things DON'T need to be done each time
2018 mAudioMixer->setBufferProvider(track);
2019 mAudioMixer->enable(AudioMixer::MIXING);
2020
2021 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
2022 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
2023 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
2024 mAudioMixer->setParameter(
2025 AudioMixer::TRACK,
2026 AudioMixer::FORMAT, (void *)track->format());
2027 mAudioMixer->setParameter(
2028 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002029 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002030 mAudioMixer->setParameter(
2031 AudioMixer::RESAMPLE,
2032 AudioMixer::SAMPLE_RATE,
2033 (void *)(cblk->sampleRate));
2034 mAudioMixer->setParameter(
2035 AudioMixer::TRACK,
2036 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
2037 mAudioMixer->setParameter(
2038 AudioMixer::TRACK,
2039 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
2040
2041 // reset retry count
2042 track->mRetryCount = kMaxTrackRetries;
2043 mixerStatus = MIXER_TRACKS_READY;
2044 } else {
2045 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
2046 if (track->isStopped()) {
2047 track->reset();
2048 }
2049 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2050 // We have consumed all the buffers of this track.
2051 // Remove it from the list of active tracks.
2052 tracksToRemove->add(track);
2053 } else {
2054 // No buffers for this track. Give it a few chances to
2055 // fill a buffer, then remove it from active list.
2056 if (--(track->mRetryCount) <= 0) {
2057 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
2058 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07002059 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07002060 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002061 } else if (mixerStatus != MIXER_TRACKS_READY) {
2062 mixerStatus = MIXER_TRACKS_ENABLED;
2063 }
2064 }
2065 mAudioMixer->disable(AudioMixer::MIXING);
2066 }
2067 }
2068
2069 // remove all the tracks that need to be...
2070 count = tracksToRemove->size();
2071 if (UNLIKELY(count)) {
2072 for (size_t i=0 ; i<count ; i++) {
2073 const sp<Track>& track = tracksToRemove->itemAt(i);
2074 mActiveTracks.remove(track);
2075 if (track->mainBuffer() != mMixBuffer) {
2076 chain = getEffectChain_l(track->sessionId());
2077 if (chain != 0) {
2078 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002079 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002080 }
2081 }
2082 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002083 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002084 }
2085 }
2086 }
2087
2088 // mix buffer must be cleared if all tracks are connected to an
2089 // effect chain as in this case the mixer will not write to
2090 // mix buffer and track effects will accumulate into it
2091 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
2092 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
2093 }
2094
2095 return mixerStatus;
2096}
2097
2098void AudioFlinger::MixerThread::invalidateTracks(int streamType)
2099{
Eric Laurentde070132010-07-13 04:45:46 -07002100 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
2101 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002102 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07002103
Mathias Agopian65ab4712010-07-14 17:59:35 -07002104 size_t size = mTracks.size();
2105 for (size_t i = 0; i < size; i++) {
2106 sp<Track> t = mTracks[i];
2107 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07002108 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002109 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002110 }
2111 }
2112}
2113
2114
2115// getTrackName_l() must be called with ThreadBase::mLock held
2116int AudioFlinger::MixerThread::getTrackName_l()
2117{
2118 return mAudioMixer->getTrackName();
2119}
2120
2121// deleteTrackName_l() must be called with ThreadBase::mLock held
2122void AudioFlinger::MixerThread::deleteTrackName_l(int name)
2123{
2124 LOGV("remove track (%d) and delete from mixer", name);
2125 mAudioMixer->deleteTrackName(name);
2126}
2127
2128// checkForNewParameters_l() must be called with ThreadBase::mLock held
2129bool AudioFlinger::MixerThread::checkForNewParameters_l()
2130{
2131 bool reconfig = false;
2132
2133 while (!mNewParameters.isEmpty()) {
2134 status_t status = NO_ERROR;
2135 String8 keyValuePair = mNewParameters[0];
2136 AudioParameter param = AudioParameter(keyValuePair);
2137 int value;
2138
2139 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
2140 reconfig = true;
2141 }
2142 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002143 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002144 status = BAD_VALUE;
2145 } else {
2146 reconfig = true;
2147 }
2148 }
2149 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002150 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002151 status = BAD_VALUE;
2152 } else {
2153 reconfig = true;
2154 }
2155 }
2156 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2157 // do not accept frame count changes if tracks are open as the track buffer
2158 // size depends on frame count and correct behavior would not be garantied
2159 // if frame count is changed after track creation
2160 if (!mTracks.isEmpty()) {
2161 status = INVALID_OPERATION;
2162 } else {
2163 reconfig = true;
2164 }
2165 }
2166 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002167 // when changing the audio output device, call addBatteryData to notify
2168 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07002169 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002170 uint32_t params = 0;
2171 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07002172 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08002173 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
2174 }
2175
2176 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07002177 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08002178 // check if any other device (except speaker) is on
2179 if (value & deviceWithoutSpeaker ) {
2180 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
2181 }
2182
2183 if (params != 0) {
2184 addBatteryData(params);
2185 }
2186 }
2187
Mathias Agopian65ab4712010-07-14 17:59:35 -07002188 // forward device change to effects that have requested to be
2189 // aware of attached audio device.
2190 mDevice = (uint32_t)value;
2191 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07002192 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002193 }
2194 }
2195
2196 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002197 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002198 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002199 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002200 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002201 mStandby = true;
2202 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002203 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002204 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002205 }
2206 if (status == NO_ERROR && reconfig) {
2207 delete mAudioMixer;
2208 readOutputParameters();
2209 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
2210 for (size_t i = 0; i < mTracks.size() ; i++) {
2211 int name = getTrackName_l();
2212 if (name < 0) break;
2213 mTracks[i]->mName = name;
2214 // limit track sample rate to 2 x new output sample rate
2215 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
2216 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2217 }
2218 }
2219 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2220 }
2221 }
2222
2223 mNewParameters.removeAt(0);
2224
2225 mParamStatus = status;
2226 mParamCond.signal();
2227 mWaitWorkCV.wait(mLock);
2228 }
2229 return reconfig;
2230}
2231
2232status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2233{
2234 const size_t SIZE = 256;
2235 char buffer[SIZE];
2236 String8 result;
2237
2238 PlaybackThread::dumpInternals(fd, args);
2239
2240 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2241 result.append(buffer);
2242 write(fd, result.string(), result.size());
2243 return NO_ERROR;
2244}
2245
2246uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2247{
Dima Zavin799a70e2011-04-18 16:57:27 -07002248 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002249}
2250
2251uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2252{
Eric Laurent60e18242010-07-29 06:50:24 -07002253 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002254}
2255
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002256uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2257{
2258 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2259}
2260
Mathias Agopian65ab4712010-07-14 17:59:35 -07002261// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002262AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002263 : PlaybackThread(audioFlinger, output, id, device)
2264{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002265 mType = ThreadBase::DIRECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002266}
2267
2268AudioFlinger::DirectOutputThread::~DirectOutputThread()
2269{
2270}
2271
2272
2273static inline int16_t clamp16(int32_t sample)
2274{
2275 if ((sample>>15) ^ (sample>>31))
2276 sample = 0x7FFF ^ (sample>>31);
2277 return sample;
2278}
2279
2280static inline
2281int32_t mul(int16_t in, int16_t v)
2282{
2283#if defined(__arm__) && !defined(__thumb__)
2284 int32_t out;
2285 asm( "smulbb %[out], %[in], %[v] \n"
2286 : [out]"=r"(out)
2287 : [in]"%r"(in), [v]"r"(v)
2288 : );
2289 return out;
2290#else
2291 return in * int32_t(v);
2292#endif
2293}
2294
2295void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2296{
2297 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002298 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002299 return;
2300 }
2301
2302 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002303 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002304 size_t count = mFrameCount * mChannelCount;
2305 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2306 int16_t *dst = mMixBuffer + count-1;
2307 while(count--) {
2308 *dst-- = (int16_t)(*src--^0x80) << 8;
2309 }
2310 }
2311
2312 size_t frameCount = mFrameCount;
2313 int16_t *out = mMixBuffer;
2314 if (ramp) {
2315 if (mChannelCount == 1) {
2316 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2317 int32_t vlInc = d / (int32_t)frameCount;
2318 int32_t vl = ((int32_t)mLeftVolShort << 16);
2319 do {
2320 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2321 out++;
2322 vl += vlInc;
2323 } while (--frameCount);
2324
2325 } else {
2326 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2327 int32_t vlInc = d / (int32_t)frameCount;
2328 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2329 int32_t vrInc = d / (int32_t)frameCount;
2330 int32_t vl = ((int32_t)mLeftVolShort << 16);
2331 int32_t vr = ((int32_t)mRightVolShort << 16);
2332 do {
2333 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2334 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2335 out += 2;
2336 vl += vlInc;
2337 vr += vrInc;
2338 } while (--frameCount);
2339 }
2340 } else {
2341 if (mChannelCount == 1) {
2342 do {
2343 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2344 out++;
2345 } while (--frameCount);
2346 } else {
2347 do {
2348 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2349 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2350 out += 2;
2351 } while (--frameCount);
2352 }
2353 }
2354
2355 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002356 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002357 size_t count = mFrameCount * mChannelCount;
2358 int16_t *src = mMixBuffer;
2359 uint8_t *dst = (uint8_t *)mMixBuffer;
2360 while(count--) {
2361 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2362 }
2363 }
2364
2365 mLeftVolShort = leftVol;
2366 mRightVolShort = rightVol;
2367}
2368
2369bool AudioFlinger::DirectOutputThread::threadLoop()
2370{
2371 uint32_t mixerStatus = MIXER_IDLE;
2372 sp<Track> trackToRemove;
2373 sp<Track> activeTrack;
2374 nsecs_t standbyTime = systemTime();
2375 int8_t *curBuf;
2376 size_t mixBufferSize = mFrameCount*mFrameSize;
2377 uint32_t activeSleepTime = activeSleepTimeUs();
2378 uint32_t idleSleepTime = idleSleepTimeUs();
2379 uint32_t sleepTime = idleSleepTime;
2380 // use shorter standby delay as on normal output to release
2381 // hardware resources as soon as possible
2382 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2383
Eric Laurentfeb0db62011-07-22 09:04:31 -07002384 acquireWakeLock();
2385
Mathias Agopian65ab4712010-07-14 17:59:35 -07002386 while (!exitPending())
2387 {
2388 bool rampVolume;
2389 uint16_t leftVol;
2390 uint16_t rightVol;
2391 Vector< sp<EffectChain> > effectChains;
2392
2393 processConfigEvents();
2394
2395 mixerStatus = MIXER_IDLE;
2396
2397 { // scope for the mLock
2398
2399 Mutex::Autolock _l(mLock);
2400
2401 if (checkForNewParameters_l()) {
2402 mixBufferSize = mFrameCount*mFrameSize;
2403 activeSleepTime = activeSleepTimeUs();
2404 idleSleepTime = idleSleepTimeUs();
2405 standbyDelay = microseconds(activeSleepTime*2);
2406 }
2407
2408 // put audio hardware into standby after short delay
2409 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2410 mSuspended) {
2411 // wait until we have something to do...
2412 if (!mStandby) {
2413 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002414 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002415 mStandby = true;
2416 mBytesWritten = 0;
2417 }
2418
2419 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2420 // we're about to wait, flush the binder command buffer
2421 IPCThreadState::self()->flushCommands();
2422
2423 if (exitPending()) break;
2424
Eric Laurentfeb0db62011-07-22 09:04:31 -07002425 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002426 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2427 mWaitWorkCV.wait(mLock);
2428 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002429 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002430
2431 if (mMasterMute == false) {
2432 char value[PROPERTY_VALUE_MAX];
2433 property_get("ro.audio.silent", value, "0");
2434 if (atoi(value)) {
2435 LOGD("Silence is golden");
2436 setMasterMute(true);
2437 }
2438 }
2439
2440 standbyTime = systemTime() + standbyDelay;
2441 sleepTime = idleSleepTime;
2442 continue;
2443 }
2444 }
2445
2446 effectChains = mEffectChains;
2447
2448 // find out which tracks need to be processed
2449 if (mActiveTracks.size() != 0) {
2450 sp<Track> t = mActiveTracks[0].promote();
2451 if (t == 0) continue;
2452
2453 Track* const track = t.get();
2454 audio_track_cblk_t* cblk = track->cblk();
2455
2456 // The first time a track is added we wait
2457 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002458 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002459 !track->isPaused() && !track->isTerminated())
2460 {
2461 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2462
2463 if (track->mFillingUpStatus == Track::FS_FILLED) {
2464 track->mFillingUpStatus = Track::FS_ACTIVE;
2465 mLeftVolFloat = mRightVolFloat = 0;
2466 mLeftVolShort = mRightVolShort = 0;
2467 if (track->mState == TrackBase::RESUMING) {
2468 track->mState = TrackBase::ACTIVE;
2469 rampVolume = true;
2470 }
2471 } else if (cblk->server != 0) {
2472 // If the track is stopped before the first frame was mixed,
2473 // do not apply ramp
2474 rampVolume = true;
2475 }
2476 // compute volume for this track
2477 float left, right;
2478 if (track->isMuted() || mMasterMute || track->isPausing() ||
2479 mStreamTypes[track->type()].mute) {
2480 left = right = 0;
2481 if (track->isPausing()) {
2482 track->setPaused();
2483 }
2484 } else {
2485 float typeVolume = mStreamTypes[track->type()].volume;
2486 float v = mMasterVolume * typeVolume;
2487 float v_clamped = v * cblk->volume[0];
2488 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2489 left = v_clamped/MAX_GAIN;
2490 v_clamped = v * cblk->volume[1];
2491 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2492 right = v_clamped/MAX_GAIN;
2493 }
2494
2495 if (left != mLeftVolFloat || right != mRightVolFloat) {
2496 mLeftVolFloat = left;
2497 mRightVolFloat = right;
2498
2499 // If audio HAL implements volume control,
2500 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002501 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002502 left = 1.0f;
2503 right = 1.0f;
2504 }
2505
2506 // Convert volumes from float to 8.24
2507 uint32_t vl = (uint32_t)(left * (1 << 24));
2508 uint32_t vr = (uint32_t)(right * (1 << 24));
2509
2510 // Delegate volume control to effect in track effect chain if needed
2511 // only one effect chain can be present on DirectOutputThread, so if
2512 // there is one, the track is connected to it
2513 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002514 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002515 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002516 rampVolume = false;
2517 }
2518 }
2519
2520 // Convert volumes from 8.24 to 4.12 format
2521 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2522 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2523 leftVol = (uint16_t)v_clamped;
2524 v_clamped = (vr + (1 << 11)) >> 12;
2525 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2526 rightVol = (uint16_t)v_clamped;
2527 } else {
2528 leftVol = mLeftVolShort;
2529 rightVol = mRightVolShort;
2530 rampVolume = false;
2531 }
2532
2533 // reset retry count
2534 track->mRetryCount = kMaxTrackRetriesDirect;
2535 activeTrack = t;
2536 mixerStatus = MIXER_TRACKS_READY;
2537 } else {
2538 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2539 if (track->isStopped()) {
2540 track->reset();
2541 }
2542 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2543 // We have consumed all the buffers of this track.
2544 // Remove it from the list of active tracks.
2545 trackToRemove = track;
2546 } else {
2547 // No buffers for this track. Give it a few chances to
2548 // fill a buffer, then remove it from active list.
2549 if (--(track->mRetryCount) <= 0) {
2550 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2551 trackToRemove = track;
2552 } else {
2553 mixerStatus = MIXER_TRACKS_ENABLED;
2554 }
2555 }
2556 }
2557 }
2558
2559 // remove all the tracks that need to be...
2560 if (UNLIKELY(trackToRemove != 0)) {
2561 mActiveTracks.remove(trackToRemove);
2562 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002563 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2564 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002565 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002566 }
2567 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002568 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002569 }
2570 }
2571
Eric Laurentde070132010-07-13 04:45:46 -07002572 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002573 }
2574
2575 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2576 AudioBufferProvider::Buffer buffer;
2577 size_t frameCount = mFrameCount;
2578 curBuf = (int8_t *)mMixBuffer;
2579 // output audio to hardware
2580 while (frameCount) {
2581 buffer.frameCount = frameCount;
2582 activeTrack->getNextBuffer(&buffer);
2583 if (UNLIKELY(buffer.raw == 0)) {
2584 memset(curBuf, 0, frameCount * mFrameSize);
2585 break;
2586 }
2587 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2588 frameCount -= buffer.frameCount;
2589 curBuf += buffer.frameCount * mFrameSize;
2590 activeTrack->releaseBuffer(&buffer);
2591 }
2592 sleepTime = 0;
2593 standbyTime = systemTime() + standbyDelay;
2594 } else {
2595 if (sleepTime == 0) {
2596 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2597 sleepTime = activeSleepTime;
2598 } else {
2599 sleepTime = idleSleepTime;
2600 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002601 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002602 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2603 sleepTime = 0;
2604 }
2605 }
2606
2607 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002608 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002609 }
2610 // sleepTime == 0 means we must write to audio hardware
2611 if (sleepTime == 0) {
2612 if (mixerStatus == MIXER_TRACKS_READY) {
2613 applyVolume(leftVol, rightVol, rampVolume);
2614 }
2615 for (size_t i = 0; i < effectChains.size(); i ++) {
2616 effectChains[i]->process_l();
2617 }
Eric Laurentde070132010-07-13 04:45:46 -07002618 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002619
2620 mLastWriteTime = systemTime();
2621 mInWrite = true;
2622 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002623 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002624 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2625 mNumWrites++;
2626 mInWrite = false;
2627 mStandby = false;
2628 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002629 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002630 usleep(sleepTime);
2631 }
2632
2633 // finally let go of removed track, without the lock held
2634 // since we can't guarantee the destructors won't acquire that
2635 // same lock.
2636 trackToRemove.clear();
2637 activeTrack.clear();
2638
2639 // Effect chains will be actually deleted here if they were removed from
2640 // mEffectChains list during mixing or effects processing
2641 effectChains.clear();
2642 }
2643
2644 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002645 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002646 }
2647
Eric Laurentfeb0db62011-07-22 09:04:31 -07002648 releaseWakeLock();
2649
Mathias Agopian65ab4712010-07-14 17:59:35 -07002650 LOGV("DirectOutputThread %p exiting", this);
2651 return false;
2652}
2653
2654// getTrackName_l() must be called with ThreadBase::mLock held
2655int AudioFlinger::DirectOutputThread::getTrackName_l()
2656{
2657 return 0;
2658}
2659
2660// deleteTrackName_l() must be called with ThreadBase::mLock held
2661void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2662{
2663}
2664
2665// checkForNewParameters_l() must be called with ThreadBase::mLock held
2666bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2667{
2668 bool reconfig = false;
2669
2670 while (!mNewParameters.isEmpty()) {
2671 status_t status = NO_ERROR;
2672 String8 keyValuePair = mNewParameters[0];
2673 AudioParameter param = AudioParameter(keyValuePair);
2674 int value;
2675
2676 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2677 // do not accept frame count changes if tracks are open as the track buffer
2678 // size depends on frame count and correct behavior would not be garantied
2679 // if frame count is changed after track creation
2680 if (!mTracks.isEmpty()) {
2681 status = INVALID_OPERATION;
2682 } else {
2683 reconfig = true;
2684 }
2685 }
2686 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002687 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002688 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002689 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002690 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002691 mStandby = true;
2692 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002693 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002694 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002695 }
2696 if (status == NO_ERROR && reconfig) {
2697 readOutputParameters();
2698 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2699 }
2700 }
2701
2702 mNewParameters.removeAt(0);
2703
2704 mParamStatus = status;
2705 mParamCond.signal();
2706 mWaitWorkCV.wait(mLock);
2707 }
2708 return reconfig;
2709}
2710
2711uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2712{
2713 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002714 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002715 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002716 } else {
2717 time = 10000;
2718 }
2719 return time;
2720}
2721
2722uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2723{
2724 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002725 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002726 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002727 } else {
2728 time = 10000;
2729 }
2730 return time;
2731}
2732
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002733uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2734{
2735 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002736 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002737 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2738 } else {
2739 time = 10000;
2740 }
2741 return time;
2742}
2743
2744
Mathias Agopian65ab4712010-07-14 17:59:35 -07002745// ----------------------------------------------------------------------------
2746
2747AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2748 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2749{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07002750 mType = ThreadBase::DUPLICATING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002751 addOutputTrack(mainThread);
2752}
2753
2754AudioFlinger::DuplicatingThread::~DuplicatingThread()
2755{
2756 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2757 mOutputTracks[i]->destroy();
2758 }
2759 mOutputTracks.clear();
2760}
2761
2762bool AudioFlinger::DuplicatingThread::threadLoop()
2763{
2764 Vector< sp<Track> > tracksToRemove;
2765 uint32_t mixerStatus = MIXER_IDLE;
2766 nsecs_t standbyTime = systemTime();
2767 size_t mixBufferSize = mFrameCount*mFrameSize;
2768 SortedVector< sp<OutputTrack> > outputTracks;
2769 uint32_t writeFrames = 0;
2770 uint32_t activeSleepTime = activeSleepTimeUs();
2771 uint32_t idleSleepTime = idleSleepTimeUs();
2772 uint32_t sleepTime = idleSleepTime;
2773 Vector< sp<EffectChain> > effectChains;
2774
Eric Laurentfeb0db62011-07-22 09:04:31 -07002775 acquireWakeLock();
2776
Mathias Agopian65ab4712010-07-14 17:59:35 -07002777 while (!exitPending())
2778 {
2779 processConfigEvents();
2780
2781 mixerStatus = MIXER_IDLE;
2782 { // scope for the mLock
2783
2784 Mutex::Autolock _l(mLock);
2785
2786 if (checkForNewParameters_l()) {
2787 mixBufferSize = mFrameCount*mFrameSize;
2788 updateWaitTime();
2789 activeSleepTime = activeSleepTimeUs();
2790 idleSleepTime = idleSleepTimeUs();
2791 }
2792
2793 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2794
2795 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2796 outputTracks.add(mOutputTracks[i]);
2797 }
2798
2799 // put audio hardware into standby after short delay
2800 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2801 mSuspended) {
2802 if (!mStandby) {
2803 for (size_t i = 0; i < outputTracks.size(); i++) {
2804 outputTracks[i]->stop();
2805 }
2806 mStandby = true;
2807 mBytesWritten = 0;
2808 }
2809
2810 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2811 // we're about to wait, flush the binder command buffer
2812 IPCThreadState::self()->flushCommands();
2813 outputTracks.clear();
2814
2815 if (exitPending()) break;
2816
Eric Laurentfeb0db62011-07-22 09:04:31 -07002817 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002818 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2819 mWaitWorkCV.wait(mLock);
2820 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
Eric Laurentfeb0db62011-07-22 09:04:31 -07002821 acquireWakeLock_l();
2822
Mathias Agopian65ab4712010-07-14 17:59:35 -07002823 if (mMasterMute == false) {
2824 char value[PROPERTY_VALUE_MAX];
2825 property_get("ro.audio.silent", value, "0");
2826 if (atoi(value)) {
2827 LOGD("Silence is golden");
2828 setMasterMute(true);
2829 }
2830 }
2831
2832 standbyTime = systemTime() + kStandbyTimeInNsecs;
2833 sleepTime = idleSleepTime;
2834 continue;
2835 }
2836 }
2837
2838 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2839
2840 // prevent any changes in effect chain list and in each effect chain
2841 // during mixing and effect process as the audio buffers could be deleted
2842 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002843 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002844 }
2845
2846 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2847 // mix buffers...
2848 if (outputsReady(outputTracks)) {
2849 mAudioMixer->process();
2850 } else {
2851 memset(mMixBuffer, 0, mixBufferSize);
2852 }
2853 sleepTime = 0;
2854 writeFrames = mFrameCount;
2855 } else {
2856 if (sleepTime == 0) {
2857 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2858 sleepTime = activeSleepTime;
2859 } else {
2860 sleepTime = idleSleepTime;
2861 }
2862 } else if (mBytesWritten != 0) {
2863 // flush remaining overflow buffers in output tracks
2864 for (size_t i = 0; i < outputTracks.size(); i++) {
2865 if (outputTracks[i]->isActive()) {
2866 sleepTime = 0;
2867 writeFrames = 0;
2868 memset(mMixBuffer, 0, mixBufferSize);
2869 break;
2870 }
2871 }
2872 }
2873 }
2874
2875 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002876 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002877 }
2878 // sleepTime == 0 means we must write to audio hardware
2879 if (sleepTime == 0) {
2880 for (size_t i = 0; i < effectChains.size(); i ++) {
2881 effectChains[i]->process_l();
2882 }
2883 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002884 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002885
2886 standbyTime = systemTime() + kStandbyTimeInNsecs;
2887 for (size_t i = 0; i < outputTracks.size(); i++) {
2888 outputTracks[i]->write(mMixBuffer, writeFrames);
2889 }
2890 mStandby = false;
2891 mBytesWritten += mixBufferSize;
2892 } else {
2893 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002894 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002895 usleep(sleepTime);
2896 }
2897
2898 // finally let go of all our tracks, without the lock held
2899 // since we can't guarantee the destructors won't acquire that
2900 // same lock.
2901 tracksToRemove.clear();
2902 outputTracks.clear();
2903
2904 // Effect chains will be actually deleted here if they were removed from
2905 // mEffectChains list during mixing or effects processing
2906 effectChains.clear();
2907 }
2908
Eric Laurentfeb0db62011-07-22 09:04:31 -07002909 releaseWakeLock();
2910
Mathias Agopian65ab4712010-07-14 17:59:35 -07002911 return false;
2912}
2913
2914void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2915{
2916 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2917 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2918 this,
2919 mSampleRate,
2920 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002921 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002922 frameCount);
2923 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002924 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002925 mOutputTracks.add(outputTrack);
2926 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2927 updateWaitTime();
2928 }
2929}
2930
2931void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2932{
2933 Mutex::Autolock _l(mLock);
2934 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2935 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2936 mOutputTracks[i]->destroy();
2937 mOutputTracks.removeAt(i);
2938 updateWaitTime();
2939 return;
2940 }
2941 }
2942 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2943}
2944
2945void AudioFlinger::DuplicatingThread::updateWaitTime()
2946{
2947 mWaitTimeMs = UINT_MAX;
2948 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2949 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2950 if (strong != NULL) {
2951 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2952 if (waitTimeMs < mWaitTimeMs) {
2953 mWaitTimeMs = waitTimeMs;
2954 }
2955 }
2956 }
2957}
2958
2959
2960bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2961{
2962 for (size_t i = 0; i < outputTracks.size(); i++) {
2963 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2964 if (thread == 0) {
2965 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2966 return false;
2967 }
2968 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2969 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2970 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2971 return false;
2972 }
2973 }
2974 return true;
2975}
2976
2977uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2978{
2979 return (mWaitTimeMs * 1000) / 2;
2980}
2981
2982// ----------------------------------------------------------------------------
2983
2984// TrackBase constructor must be called with AudioFlinger::mLock held
2985AudioFlinger::ThreadBase::TrackBase::TrackBase(
2986 const wp<ThreadBase>& thread,
2987 const sp<Client>& client,
2988 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002989 uint32_t format,
2990 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002991 int frameCount,
2992 uint32_t flags,
2993 const sp<IMemory>& sharedBuffer,
2994 int sessionId)
2995 : RefBase(),
2996 mThread(thread),
2997 mClient(client),
2998 mCblk(0),
2999 mFrameCount(0),
3000 mState(IDLE),
3001 mClientTid(-1),
3002 mFormat(format),
3003 mFlags(flags & ~SYSTEM_FLAGS_MASK),
3004 mSessionId(sessionId)
3005{
3006 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
3007
3008 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
3009 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003010 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003011 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
3012 if (sharedBuffer == 0) {
3013 size += bufferSize;
3014 }
3015
3016 if (client != NULL) {
3017 mCblkMemory = client->heap()->allocate(size);
3018 if (mCblkMemory != 0) {
3019 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
3020 if (mCblk) { // construct the shared structure in-place.
3021 new(mCblk) audio_track_cblk_t();
3022 // clear all buffers
3023 mCblk->frameCount = frameCount;
3024 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003025 mChannelCount = channelCount;
3026 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003027 if (sharedBuffer == 0) {
3028 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3029 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3030 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003031 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003032 mCblk->flags = CBLK_UNDERRUN_ON;
3033 } else {
3034 mBuffer = sharedBuffer->pointer();
3035 }
3036 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3037 }
3038 } else {
3039 LOGE("not enough memory for AudioTrack size=%u", size);
3040 client->heap()->dump("AudioTrack");
3041 return;
3042 }
3043 } else {
3044 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
3045 if (mCblk) { // construct the shared structure in-place.
3046 new(mCblk) audio_track_cblk_t();
3047 // clear all buffers
3048 mCblk->frameCount = frameCount;
3049 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003050 mChannelCount = channelCount;
3051 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003052 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
3053 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
3054 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07003055 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003056 mCblk->flags = CBLK_UNDERRUN_ON;
3057 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
3058 }
3059 }
3060}
3061
3062AudioFlinger::ThreadBase::TrackBase::~TrackBase()
3063{
3064 if (mCblk) {
3065 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
3066 if (mClient == NULL) {
3067 delete mCblk;
3068 }
3069 }
3070 mCblkMemory.clear(); // and free the shared memory
3071 if (mClient != NULL) {
3072 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
3073 mClient.clear();
3074 }
3075}
3076
3077void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3078{
3079 buffer->raw = 0;
3080 mFrameCount = buffer->frameCount;
3081 step();
3082 buffer->frameCount = 0;
3083}
3084
3085bool AudioFlinger::ThreadBase::TrackBase::step() {
3086 bool result;
3087 audio_track_cblk_t* cblk = this->cblk();
3088
3089 result = cblk->stepServer(mFrameCount);
3090 if (!result) {
3091 LOGV("stepServer failed acquiring cblk mutex");
3092 mFlags |= STEPSERVER_FAILED;
3093 }
3094 return result;
3095}
3096
3097void AudioFlinger::ThreadBase::TrackBase::reset() {
3098 audio_track_cblk_t* cblk = this->cblk();
3099
3100 cblk->user = 0;
3101 cblk->server = 0;
3102 cblk->userBase = 0;
3103 cblk->serverBase = 0;
3104 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
3105 LOGV("TrackBase::reset");
3106}
3107
3108sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
3109{
3110 return mCblkMemory;
3111}
3112
3113int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
3114 return (int)mCblk->sampleRate;
3115}
3116
3117int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003118 return (const int)mChannelCount;
3119}
3120
3121uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
3122 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003123}
3124
3125void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
3126 audio_track_cblk_t* cblk = this->cblk();
3127 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
3128 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
3129
3130 // Check validity of returned pointer in case the track control block would have been corrupted.
3131 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
3132 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
3133 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 -07003134 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003136 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003137 return 0;
3138 }
3139
3140 return bufferStart;
3141}
3142
3143// ----------------------------------------------------------------------------
3144
3145// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
3146AudioFlinger::PlaybackThread::Track::Track(
3147 const wp<ThreadBase>& thread,
3148 const sp<Client>& client,
3149 int streamType,
3150 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003151 uint32_t format,
3152 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 int frameCount,
3154 const sp<IMemory>& sharedBuffer,
3155 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003156 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07003157 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
3158 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07003159{
3160 if (mCblk != NULL) {
3161 sp<ThreadBase> baseThread = thread.promote();
3162 if (baseThread != 0) {
3163 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
3164 mName = playbackThread->getTrackName_l();
3165 mMainBuffer = playbackThread->mixBuffer();
3166 }
3167 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3168 if (mName < 0) {
3169 LOGE("no more track names available");
3170 }
3171 mVolume[0] = 1.0f;
3172 mVolume[1] = 1.0f;
3173 mStreamType = streamType;
3174 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
3175 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Eric Laurentedc15ad2011-07-21 19:35:01 -07003176 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(uint8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003177 }
3178}
3179
3180AudioFlinger::PlaybackThread::Track::~Track()
3181{
3182 LOGV("PlaybackThread::Track destructor");
3183 sp<ThreadBase> thread = mThread.promote();
3184 if (thread != 0) {
3185 Mutex::Autolock _l(thread->mLock);
3186 mState = TERMINATED;
3187 }
3188}
3189
3190void AudioFlinger::PlaybackThread::Track::destroy()
3191{
3192 // NOTE: destroyTrack_l() can remove a strong reference to this Track
3193 // by removing it from mTracks vector, so there is a risk that this Tracks's
3194 // desctructor is called. As the destructor needs to lock mLock,
3195 // we must acquire a strong reference on this Track before locking mLock
3196 // here so that the destructor is called only when exiting this function.
3197 // On the other hand, as long as Track::destroy() is only called by
3198 // TrackHandle destructor, the TrackHandle still holds a strong ref on
3199 // this Track with its member mTrack.
3200 sp<Track> keep(this);
3201 { // scope for mLock
3202 sp<ThreadBase> thread = mThread.promote();
3203 if (thread != 0) {
3204 if (!isOutputTrack()) {
3205 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07003206 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003207 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003208 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08003209
3210 // to track the speaker usage
3211 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003212 }
3213 AudioSystem::releaseOutput(thread->id());
3214 }
3215 Mutex::Autolock _l(thread->mLock);
3216 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3217 playbackThread->destroyTrack_l(this);
3218 }
3219 }
3220}
3221
3222void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
3223{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003224 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 -07003225 mName - AudioMixer::TRACK0,
3226 (mClient == NULL) ? getpid() : mClient->pid(),
3227 mStreamType,
3228 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003229 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003230 mSessionId,
3231 mFrameCount,
3232 mState,
3233 mMute,
3234 mFillingUpStatus,
3235 mCblk->sampleRate,
3236 mCblk->volume[0],
3237 mCblk->volume[1],
3238 mCblk->server,
3239 mCblk->user,
3240 (int)mMainBuffer,
3241 (int)mAuxBuffer);
3242}
3243
3244status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3245{
3246 audio_track_cblk_t* cblk = this->cblk();
3247 uint32_t framesReady;
3248 uint32_t framesReq = buffer->frameCount;
3249
3250 // Check if last stepServer failed, try to step now
3251 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3252 if (!step()) goto getNextBuffer_exit;
3253 LOGV("stepServer recovered");
3254 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3255 }
3256
3257 framesReady = cblk->framesReady();
3258
3259 if (LIKELY(framesReady)) {
3260 uint32_t s = cblk->server;
3261 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3262
3263 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3264 if (framesReq > framesReady) {
3265 framesReq = framesReady;
3266 }
3267 if (s + framesReq > bufferEnd) {
3268 framesReq = bufferEnd - s;
3269 }
3270
3271 buffer->raw = getBuffer(s, framesReq);
3272 if (buffer->raw == 0) goto getNextBuffer_exit;
3273
3274 buffer->frameCount = framesReq;
3275 return NO_ERROR;
3276 }
3277
3278getNextBuffer_exit:
3279 buffer->raw = 0;
3280 buffer->frameCount = 0;
3281 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3282 return NOT_ENOUGH_DATA;
3283}
3284
3285bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003286 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003287
3288 if (mCblk->framesReady() >= mCblk->frameCount ||
3289 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3290 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003291 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003292 return true;
3293 }
3294 return false;
3295}
3296
3297status_t AudioFlinger::PlaybackThread::Track::start()
3298{
3299 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003300 LOGV("start(%d), calling thread %d session %d",
3301 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003302 sp<ThreadBase> thread = mThread.promote();
3303 if (thread != 0) {
3304 Mutex::Autolock _l(thread->mLock);
3305 int state = mState;
3306 // here the track could be either new, or restarted
3307 // in both cases "unstop" the track
3308 if (mState == PAUSED) {
3309 mState = TrackBase::RESUMING;
3310 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3311 } else {
3312 mState = TrackBase::ACTIVE;
3313 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3314 }
3315
3316 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3317 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003318 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003319 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003320 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003321 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003322
3323 // to track the speaker usage
3324 if (status == NO_ERROR) {
3325 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3326 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 }
3328 if (status == NO_ERROR) {
3329 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3330 playbackThread->addTrack_l(this);
3331 } else {
3332 mState = state;
3333 }
3334 } else {
3335 status = BAD_VALUE;
3336 }
3337 return status;
3338}
3339
3340void AudioFlinger::PlaybackThread::Track::stop()
3341{
3342 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3343 sp<ThreadBase> thread = mThread.promote();
3344 if (thread != 0) {
3345 Mutex::Autolock _l(thread->mLock);
3346 int state = mState;
3347 if (mState > STOPPED) {
3348 mState = STOPPED;
3349 // If the track is not active (PAUSED and buffers full), flush buffers
3350 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3351 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3352 reset();
3353 }
3354 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3355 }
3356 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3357 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003358 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003359 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003360 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003361 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003362
3363 // to track the speaker usage
3364 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 }
3366 }
3367}
3368
3369void AudioFlinger::PlaybackThread::Track::pause()
3370{
3371 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3372 sp<ThreadBase> thread = mThread.promote();
3373 if (thread != 0) {
3374 Mutex::Autolock _l(thread->mLock);
3375 if (mState == ACTIVE || mState == RESUMING) {
3376 mState = PAUSING;
3377 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3378 if (!isOutputTrack()) {
3379 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003380 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003381 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003382 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003383 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003384
3385 // to track the speaker usage
3386 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003387 }
3388 }
3389 }
3390}
3391
3392void AudioFlinger::PlaybackThread::Track::flush()
3393{
3394 LOGV("flush(%d)", mName);
3395 sp<ThreadBase> thread = mThread.promote();
3396 if (thread != 0) {
3397 Mutex::Autolock _l(thread->mLock);
3398 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3399 return;
3400 }
3401 // No point remaining in PAUSED state after a flush => go to
3402 // STOPPED state
3403 mState = STOPPED;
3404
Eric Laurent38ccae22011-03-28 18:37:07 -07003405 // do not reset the track if it is still in the process of being stopped or paused.
3406 // this will be done by prepareTracks_l() when the track is stopped.
3407 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3408 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3409 reset();
3410 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003411 }
3412}
3413
3414void AudioFlinger::PlaybackThread::Track::reset()
3415{
3416 // Do not reset twice to avoid discarding data written just after a flush and before
3417 // the audioflinger thread detects the track is stopped.
3418 if (!mResetDone) {
3419 TrackBase::reset();
3420 // Force underrun condition to avoid false underrun callback until first data is
3421 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003422 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3423 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003424 mFillingUpStatus = FS_FILLING;
3425 mResetDone = true;
3426 }
3427}
3428
3429void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3430{
3431 mMute = muted;
3432}
3433
3434void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3435{
3436 mVolume[0] = left;
3437 mVolume[1] = right;
3438}
3439
3440status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3441{
3442 status_t status = DEAD_OBJECT;
3443 sp<ThreadBase> thread = mThread.promote();
3444 if (thread != 0) {
3445 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3446 status = playbackThread->attachAuxEffect(this, EffectId);
3447 }
3448 return status;
3449}
3450
3451void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3452{
3453 mAuxEffectId = EffectId;
3454 mAuxBuffer = buffer;
3455}
3456
3457// ----------------------------------------------------------------------------
3458
3459// RecordTrack constructor must be called with AudioFlinger::mLock held
3460AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3461 const wp<ThreadBase>& thread,
3462 const sp<Client>& client,
3463 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003464 uint32_t format,
3465 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003466 int frameCount,
3467 uint32_t flags,
3468 int sessionId)
3469 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003470 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003471 mOverflow(false)
3472{
3473 if (mCblk != NULL) {
3474 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003475 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003476 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003477 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003478 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003479 } else {
3480 mCblk->frameSize = sizeof(int8_t);
3481 }
3482 }
3483}
3484
3485AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3486{
3487 sp<ThreadBase> thread = mThread.promote();
3488 if (thread != 0) {
3489 AudioSystem::releaseInput(thread->id());
3490 }
3491}
3492
3493status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3494{
3495 audio_track_cblk_t* cblk = this->cblk();
3496 uint32_t framesAvail;
3497 uint32_t framesReq = buffer->frameCount;
3498
3499 // Check if last stepServer failed, try to step now
3500 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3501 if (!step()) goto getNextBuffer_exit;
3502 LOGV("stepServer recovered");
3503 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3504 }
3505
3506 framesAvail = cblk->framesAvailable_l();
3507
3508 if (LIKELY(framesAvail)) {
3509 uint32_t s = cblk->server;
3510 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3511
3512 if (framesReq > framesAvail) {
3513 framesReq = framesAvail;
3514 }
3515 if (s + framesReq > bufferEnd) {
3516 framesReq = bufferEnd - s;
3517 }
3518
3519 buffer->raw = getBuffer(s, framesReq);
3520 if (buffer->raw == 0) goto getNextBuffer_exit;
3521
3522 buffer->frameCount = framesReq;
3523 return NO_ERROR;
3524 }
3525
3526getNextBuffer_exit:
3527 buffer->raw = 0;
3528 buffer->frameCount = 0;
3529 return NOT_ENOUGH_DATA;
3530}
3531
3532status_t AudioFlinger::RecordThread::RecordTrack::start()
3533{
3534 sp<ThreadBase> thread = mThread.promote();
3535 if (thread != 0) {
3536 RecordThread *recordThread = (RecordThread *)thread.get();
3537 return recordThread->start(this);
3538 } else {
3539 return BAD_VALUE;
3540 }
3541}
3542
3543void AudioFlinger::RecordThread::RecordTrack::stop()
3544{
3545 sp<ThreadBase> thread = mThread.promote();
3546 if (thread != 0) {
3547 RecordThread *recordThread = (RecordThread *)thread.get();
3548 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003549 TrackBase::reset();
3550 // Force overerrun condition to avoid false overrun callback until first data is
3551 // read from buffer
3552 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003553 }
3554}
3555
3556void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3557{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003558 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003559 (mClient == NULL) ? getpid() : mClient->pid(),
3560 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003561 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 mSessionId,
3563 mFrameCount,
3564 mState,
3565 mCblk->sampleRate,
3566 mCblk->server,
3567 mCblk->user);
3568}
3569
3570
3571// ----------------------------------------------------------------------------
3572
3573AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3574 const wp<ThreadBase>& thread,
3575 DuplicatingThread *sourceThread,
3576 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003577 uint32_t format,
3578 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003579 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003580 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003581 mActive(false), mSourceThread(sourceThread)
3582{
3583
3584 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3585 if (mCblk != NULL) {
3586 mCblk->flags |= CBLK_DIRECTION_OUT;
3587 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3588 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3589 mOutBuffer.frameCount = 0;
3590 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003591 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3592 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3593 mCblk, mBuffer, mCblk->buffers,
3594 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 } else {
3596 LOGW("Error creating output track on thread %p", playbackThread);
3597 }
3598}
3599
3600AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3601{
3602 clearBufferQueue();
3603}
3604
3605status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3606{
3607 status_t status = Track::start();
3608 if (status != NO_ERROR) {
3609 return status;
3610 }
3611
3612 mActive = true;
3613 mRetryCount = 127;
3614 return status;
3615}
3616
3617void AudioFlinger::PlaybackThread::OutputTrack::stop()
3618{
3619 Track::stop();
3620 clearBufferQueue();
3621 mOutBuffer.frameCount = 0;
3622 mActive = false;
3623}
3624
3625bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3626{
3627 Buffer *pInBuffer;
3628 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003629 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630 bool outputBufferFull = false;
3631 inBuffer.frameCount = frames;
3632 inBuffer.i16 = data;
3633
3634 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3635
3636 if (!mActive && frames != 0) {
3637 start();
3638 sp<ThreadBase> thread = mThread.promote();
3639 if (thread != 0) {
3640 MixerThread *mixerThread = (MixerThread *)thread.get();
3641 if (mCblk->frameCount > frames){
3642 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3643 uint32_t startFrames = (mCblk->frameCount - frames);
3644 pInBuffer = new Buffer;
3645 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3646 pInBuffer->frameCount = startFrames;
3647 pInBuffer->i16 = pInBuffer->mBuffer;
3648 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3649 mBufferQueue.add(pInBuffer);
3650 } else {
3651 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3652 }
3653 }
3654 }
3655 }
3656
3657 while (waitTimeLeftMs) {
3658 // First write pending buffers, then new data
3659 if (mBufferQueue.size()) {
3660 pInBuffer = mBufferQueue.itemAt(0);
3661 } else {
3662 pInBuffer = &inBuffer;
3663 }
3664
3665 if (pInBuffer->frameCount == 0) {
3666 break;
3667 }
3668
3669 if (mOutBuffer.frameCount == 0) {
3670 mOutBuffer.frameCount = pInBuffer->frameCount;
3671 nsecs_t startTime = systemTime();
3672 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3673 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3674 outputBufferFull = true;
3675 break;
3676 }
3677 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3678 if (waitTimeLeftMs >= waitTimeMs) {
3679 waitTimeLeftMs -= waitTimeMs;
3680 } else {
3681 waitTimeLeftMs = 0;
3682 }
3683 }
3684
3685 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3686 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3687 mCblk->stepUser(outFrames);
3688 pInBuffer->frameCount -= outFrames;
3689 pInBuffer->i16 += outFrames * channelCount;
3690 mOutBuffer.frameCount -= outFrames;
3691 mOutBuffer.i16 += outFrames * channelCount;
3692
3693 if (pInBuffer->frameCount == 0) {
3694 if (mBufferQueue.size()) {
3695 mBufferQueue.removeAt(0);
3696 delete [] pInBuffer->mBuffer;
3697 delete pInBuffer;
3698 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3699 } else {
3700 break;
3701 }
3702 }
3703 }
3704
3705 // If we could not write all frames, allocate a buffer and queue it for next time.
3706 if (inBuffer.frameCount) {
3707 sp<ThreadBase> thread = mThread.promote();
3708 if (thread != 0 && !thread->standby()) {
3709 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3710 pInBuffer = new Buffer;
3711 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3712 pInBuffer->frameCount = inBuffer.frameCount;
3713 pInBuffer->i16 = pInBuffer->mBuffer;
3714 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3715 mBufferQueue.add(pInBuffer);
3716 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3717 } else {
3718 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3719 }
3720 }
3721 }
3722
3723 // Calling write() with a 0 length buffer, means that no more data will be written:
3724 // If no more buffers are pending, fill output track buffer to make sure it is started
3725 // by output mixer.
3726 if (frames == 0 && mBufferQueue.size() == 0) {
3727 if (mCblk->user < mCblk->frameCount) {
3728 frames = mCblk->frameCount - mCblk->user;
3729 pInBuffer = new Buffer;
3730 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3731 pInBuffer->frameCount = frames;
3732 pInBuffer->i16 = pInBuffer->mBuffer;
3733 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3734 mBufferQueue.add(pInBuffer);
3735 } else if (mActive) {
3736 stop();
3737 }
3738 }
3739
3740 return outputBufferFull;
3741}
3742
3743status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3744{
3745 int active;
3746 status_t result;
3747 audio_track_cblk_t* cblk = mCblk;
3748 uint32_t framesReq = buffer->frameCount;
3749
3750// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3751 buffer->frameCount = 0;
3752
3753 uint32_t framesAvail = cblk->framesAvailable();
3754
3755
3756 if (framesAvail == 0) {
3757 Mutex::Autolock _l(cblk->lock);
3758 goto start_loop_here;
3759 while (framesAvail == 0) {
3760 active = mActive;
3761 if (UNLIKELY(!active)) {
3762 LOGV("Not active and NO_MORE_BUFFERS");
3763 return AudioTrack::NO_MORE_BUFFERS;
3764 }
3765 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3766 if (result != NO_ERROR) {
3767 return AudioTrack::NO_MORE_BUFFERS;
3768 }
3769 // read the server count again
3770 start_loop_here:
3771 framesAvail = cblk->framesAvailable_l();
3772 }
3773 }
3774
3775// if (framesAvail < framesReq) {
3776// return AudioTrack::NO_MORE_BUFFERS;
3777// }
3778
3779 if (framesReq > framesAvail) {
3780 framesReq = framesAvail;
3781 }
3782
3783 uint32_t u = cblk->user;
3784 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3785
3786 if (u + framesReq > bufferEnd) {
3787 framesReq = bufferEnd - u;
3788 }
3789
3790 buffer->frameCount = framesReq;
3791 buffer->raw = (void *)cblk->buffer(u);
3792 return NO_ERROR;
3793}
3794
3795
3796void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3797{
3798 size_t size = mBufferQueue.size();
3799 Buffer *pBuffer;
3800
3801 for (size_t i = 0; i < size; i++) {
3802 pBuffer = mBufferQueue.itemAt(i);
3803 delete [] pBuffer->mBuffer;
3804 delete pBuffer;
3805 }
3806 mBufferQueue.clear();
3807}
3808
3809// ----------------------------------------------------------------------------
3810
3811AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3812 : RefBase(),
3813 mAudioFlinger(audioFlinger),
3814 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3815 mPid(pid)
3816{
3817 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3818}
3819
3820// Client destructor must be called with AudioFlinger::mLock held
3821AudioFlinger::Client::~Client()
3822{
3823 mAudioFlinger->removeClient_l(mPid);
3824}
3825
3826const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3827{
3828 return mMemoryDealer;
3829}
3830
3831// ----------------------------------------------------------------------------
3832
3833AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3834 const sp<IAudioFlingerClient>& client,
3835 pid_t pid)
3836 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3837{
3838}
3839
3840AudioFlinger::NotificationClient::~NotificationClient()
3841{
3842 mClient.clear();
3843}
3844
3845void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3846{
3847 sp<NotificationClient> keep(this);
3848 {
3849 mAudioFlinger->removeNotificationClient(mPid);
3850 }
3851}
3852
3853// ----------------------------------------------------------------------------
3854
3855AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3856 : BnAudioTrack(),
3857 mTrack(track)
3858{
3859}
3860
3861AudioFlinger::TrackHandle::~TrackHandle() {
3862 // just stop the track on deletion, associated resources
3863 // will be freed from the main thread once all pending buffers have
3864 // been played. Unless it's not in the active track list, in which
3865 // case we free everything now...
3866 mTrack->destroy();
3867}
3868
3869status_t AudioFlinger::TrackHandle::start() {
3870 return mTrack->start();
3871}
3872
3873void AudioFlinger::TrackHandle::stop() {
3874 mTrack->stop();
3875}
3876
3877void AudioFlinger::TrackHandle::flush() {
3878 mTrack->flush();
3879}
3880
3881void AudioFlinger::TrackHandle::mute(bool e) {
3882 mTrack->mute(e);
3883}
3884
3885void AudioFlinger::TrackHandle::pause() {
3886 mTrack->pause();
3887}
3888
3889void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3890 mTrack->setVolume(left, right);
3891}
3892
3893sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3894 return mTrack->getCblk();
3895}
3896
3897status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3898{
3899 return mTrack->attachAuxEffect(EffectId);
3900}
3901
3902status_t AudioFlinger::TrackHandle::onTransact(
3903 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3904{
3905 return BnAudioTrack::onTransact(code, data, reply, flags);
3906}
3907
3908// ----------------------------------------------------------------------------
3909
3910sp<IAudioRecord> AudioFlinger::openRecord(
3911 pid_t pid,
3912 int input,
3913 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003914 uint32_t format,
3915 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916 int frameCount,
3917 uint32_t flags,
3918 int *sessionId,
3919 status_t *status)
3920{
3921 sp<RecordThread::RecordTrack> recordTrack;
3922 sp<RecordHandle> recordHandle;
3923 sp<Client> client;
3924 wp<Client> wclient;
3925 status_t lStatus;
3926 RecordThread *thread;
3927 size_t inFrameCount;
3928 int lSessionId;
3929
3930 // check calling permissions
3931 if (!recordingAllowed()) {
3932 lStatus = PERMISSION_DENIED;
3933 goto Exit;
3934 }
3935
3936 // add client to list
3937 { // scope for mLock
3938 Mutex::Autolock _l(mLock);
3939 thread = checkRecordThread_l(input);
3940 if (thread == NULL) {
3941 lStatus = BAD_VALUE;
3942 goto Exit;
3943 }
3944
3945 wclient = mClients.valueFor(pid);
3946 if (wclient != NULL) {
3947 client = wclient.promote();
3948 } else {
3949 client = new Client(this, pid);
3950 mClients.add(pid, client);
3951 }
3952
3953 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07003954 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003955 lSessionId = *sessionId;
3956 } else {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003957 lSessionId = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958 if (sessionId != NULL) {
3959 *sessionId = lSessionId;
3960 }
3961 }
3962 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003963 recordTrack = thread->createRecordTrack_l(client,
3964 sampleRate,
3965 format,
3966 channelMask,
3967 frameCount,
3968 flags,
3969 lSessionId,
3970 &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07003972 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003973 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3974 // destructor is called by the TrackBase destructor with mLock held
3975 client.clear();
3976 recordTrack.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977 goto Exit;
3978 }
3979
3980 // return to handle to client
3981 recordHandle = new RecordHandle(recordTrack);
3982 lStatus = NO_ERROR;
3983
3984Exit:
3985 if (status) {
3986 *status = lStatus;
3987 }
3988 return recordHandle;
3989}
3990
3991// ----------------------------------------------------------------------------
3992
3993AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3994 : BnAudioRecord(),
3995 mRecordTrack(recordTrack)
3996{
3997}
3998
3999AudioFlinger::RecordHandle::~RecordHandle() {
4000 stop();
4001}
4002
4003status_t AudioFlinger::RecordHandle::start() {
4004 LOGV("RecordHandle::start()");
4005 return mRecordTrack->start();
4006}
4007
4008void AudioFlinger::RecordHandle::stop() {
4009 LOGV("RecordHandle::stop()");
4010 mRecordTrack->stop();
4011}
4012
4013sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
4014 return mRecordTrack->getCblk();
4015}
4016
4017status_t AudioFlinger::RecordHandle::onTransact(
4018 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4019{
4020 return BnAudioRecord::onTransact(code, data, reply, flags);
4021}
4022
4023// ----------------------------------------------------------------------------
4024
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004025AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
4026 AudioStreamIn *input,
4027 uint32_t sampleRate,
4028 uint32_t channels,
4029 int id,
4030 uint32_t device) :
4031 ThreadBase(audioFlinger, id, device),
4032 mInput(input), mTrack(NULL), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004034 mType = ThreadBase::RECORD;
Eric Laurentfeb0db62011-07-22 09:04:31 -07004035
4036 snprintf(mName, kNameLength, "AudioIn_%d", id);
4037
Dima Zavinfce7a472011-04-19 22:30:36 -07004038 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 mReqSampleRate = sampleRate;
4040 readInputParameters();
4041}
4042
4043
4044AudioFlinger::RecordThread::~RecordThread()
4045{
4046 delete[] mRsmpInBuffer;
4047 if (mResampler != 0) {
4048 delete mResampler;
4049 delete[] mRsmpOutBuffer;
4050 }
4051}
4052
4053void AudioFlinger::RecordThread::onFirstRef()
4054{
Eric Laurentfeb0db62011-07-22 09:04:31 -07004055 run(mName, PRIORITY_URGENT_AUDIO);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004056}
4057
4058bool AudioFlinger::RecordThread::threadLoop()
4059{
4060 AudioBufferProvider::Buffer buffer;
4061 sp<RecordTrack> activeTrack;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004062 Vector< sp<EffectChain> > effectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063
Eric Laurent44d98482010-09-30 16:12:31 -07004064 nsecs_t lastWarning = 0;
4065
Eric Laurentfeb0db62011-07-22 09:04:31 -07004066 acquireWakeLock();
4067
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068 // start recording
4069 while (!exitPending()) {
4070
4071 processConfigEvents();
4072
4073 { // scope for mLock
4074 Mutex::Autolock _l(mLock);
4075 checkForNewParameters_l();
4076 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
4077 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004078 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004079 mStandby = true;
4080 }
4081
4082 if (exitPending()) break;
4083
Eric Laurentfeb0db62011-07-22 09:04:31 -07004084 releaseWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004085 LOGV("RecordThread: loop stopping");
4086 // go to sleep
4087 mWaitWorkCV.wait(mLock);
4088 LOGV("RecordThread: loop starting");
Eric Laurentfeb0db62011-07-22 09:04:31 -07004089 acquireWakeLock_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090 continue;
4091 }
4092 if (mActiveTrack != 0) {
4093 if (mActiveTrack->mState == TrackBase::PAUSING) {
4094 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004095 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096 mStandby = true;
4097 }
4098 mActiveTrack.clear();
4099 mStartStopCond.broadcast();
4100 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
4101 if (mReqChannelCount != mActiveTrack->channelCount()) {
4102 mActiveTrack.clear();
4103 mStartStopCond.broadcast();
4104 } else if (mBytesRead != 0) {
4105 // record start succeeds only if first read from audio input
4106 // succeeds
4107 if (mBytesRead > 0) {
4108 mActiveTrack->mState = TrackBase::ACTIVE;
4109 } else {
4110 mActiveTrack.clear();
4111 }
4112 mStartStopCond.broadcast();
4113 }
4114 mStandby = false;
4115 }
4116 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004117 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 }
4119
4120 if (mActiveTrack != 0) {
4121 if (mActiveTrack->mState != TrackBase::ACTIVE &&
4122 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004123 unlockEffectChains(effectChains);
4124 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125 continue;
4126 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004127 for (size_t i = 0; i < effectChains.size(); i ++) {
4128 effectChains[i]->process_l();
4129 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004130
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131 buffer.frameCount = mFrameCount;
4132 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
4133 size_t framesOut = buffer.frameCount;
4134 if (mResampler == 0) {
4135 // no resampling
4136 while (framesOut) {
4137 size_t framesIn = mFrameCount - mRsmpInIndex;
4138 if (framesIn) {
4139 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
4140 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
4141 if (framesIn > framesOut)
4142 framesIn = framesOut;
4143 mRsmpInIndex += framesIn;
4144 framesOut -= framesIn;
4145 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07004146 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 memcpy(dst, src, framesIn * mFrameSize);
4148 } else {
4149 int16_t *src16 = (int16_t *)src;
4150 int16_t *dst16 = (int16_t *)dst;
4151 if (mChannelCount == 1) {
4152 while (framesIn--) {
4153 *dst16++ = *src16;
4154 *dst16++ = *src16++;
4155 }
4156 } else {
4157 while (framesIn--) {
4158 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
4159 src16 += 2;
4160 }
4161 }
4162 }
4163 }
4164 if (framesOut && mFrameCount == mRsmpInIndex) {
4165 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004166 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004167 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168 framesOut = 0;
4169 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07004170 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004171 mRsmpInIndex = 0;
4172 }
4173 if (mBytesRead < 0) {
4174 LOGE("Error reading audio input");
4175 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4176 // Force input into standby so that it tries to
4177 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004178 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004179 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180 }
4181 mRsmpInIndex = mFrameCount;
4182 framesOut = 0;
4183 buffer.frameCount = 0;
4184 }
4185 }
4186 }
4187 } else {
4188 // resampling
4189
4190 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
4191 // alter output frame count as if we were expecting stereo samples
4192 if (mChannelCount == 1 && mReqChannelCount == 1) {
4193 framesOut >>= 1;
4194 }
4195 mResampler->resample(mRsmpOutBuffer, framesOut, this);
4196 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
4197 // are 32 bit aligned which should be always true.
4198 if (mChannelCount == 2 && mReqChannelCount == 1) {
4199 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
4200 // the resampler always outputs stereo samples: do post stereo to mono conversion
4201 int16_t *src = (int16_t *)mRsmpOutBuffer;
4202 int16_t *dst = buffer.i16;
4203 while (framesOut--) {
4204 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
4205 src += 2;
4206 }
4207 } else {
4208 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
4209 }
4210
4211 }
4212 mActiveTrack->releaseBuffer(&buffer);
4213 mActiveTrack->overflow();
4214 }
4215 // client isn't retrieving buffers fast enough
4216 else {
Eric Laurent44d98482010-09-30 16:12:31 -07004217 if (!mActiveTrack->setOverflow()) {
4218 nsecs_t now = systemTime();
4219 if ((now - lastWarning) > kWarningThrottle) {
4220 LOGW("RecordThread: buffer overflow");
4221 lastWarning = now;
4222 }
4223 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004224 // Release the processor for a while before asking for a new buffer.
4225 // This will give the application more chance to read from the buffer and
4226 // clear the overflow.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004227 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004228 }
4229 }
Eric Laurentec437d82011-07-26 20:54:46 -07004230 // enable changes in effect chain
4231 unlockEffectChains(effectChains);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004232 effectChains.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004233 }
4234
4235 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004236 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 }
4238 mActiveTrack.clear();
4239
4240 mStartStopCond.broadcast();
4241
Eric Laurentfeb0db62011-07-22 09:04:31 -07004242 releaseWakeLock();
4243
Mathias Agopian65ab4712010-07-14 17:59:35 -07004244 LOGV("RecordThread %p exiting", this);
4245 return false;
4246}
4247
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004248
4249sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
4250 const sp<AudioFlinger::Client>& client,
4251 uint32_t sampleRate,
4252 int format,
4253 int channelMask,
4254 int frameCount,
4255 uint32_t flags,
4256 int sessionId,
4257 status_t *status)
4258{
4259 sp<RecordTrack> track;
4260 status_t lStatus;
4261
4262 lStatus = initCheck();
4263 if (lStatus != NO_ERROR) {
4264 LOGE("Audio driver not initialized.");
4265 goto Exit;
4266 }
4267
4268 { // scope for mLock
4269 Mutex::Autolock _l(mLock);
4270
4271 track = new RecordTrack(this, client, sampleRate,
4272 format, channelMask, frameCount, flags, sessionId);
4273
4274 if (track->getCblk() == NULL) {
4275 lStatus = NO_MEMORY;
4276 goto Exit;
4277 }
4278
4279 mTrack = track.get();
4280
4281 }
4282 lStatus = NO_ERROR;
4283
4284Exit:
4285 if (status) {
4286 *status = lStatus;
4287 }
4288 return track;
4289}
4290
Mathias Agopian65ab4712010-07-14 17:59:35 -07004291status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
4292{
4293 LOGV("RecordThread::start");
4294 sp <ThreadBase> strongMe = this;
4295 status_t status = NO_ERROR;
4296 {
4297 AutoMutex lock(&mLock);
4298 if (mActiveTrack != 0) {
4299 if (recordTrack != mActiveTrack.get()) {
4300 status = -EBUSY;
4301 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4302 mActiveTrack->mState = TrackBase::ACTIVE;
4303 }
4304 return status;
4305 }
4306
4307 recordTrack->mState = TrackBase::IDLE;
4308 mActiveTrack = recordTrack;
4309 mLock.unlock();
4310 status_t status = AudioSystem::startInput(mId);
4311 mLock.lock();
4312 if (status != NO_ERROR) {
4313 mActiveTrack.clear();
4314 return status;
4315 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004316 mRsmpInIndex = mFrameCount;
4317 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004318 if (mResampler != NULL) {
4319 mResampler->reset();
4320 }
4321 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004322 // signal thread to start
4323 LOGV("Signal record thread");
4324 mWaitWorkCV.signal();
4325 // do not wait for mStartStopCond if exiting
4326 if (mExiting) {
4327 mActiveTrack.clear();
4328 status = INVALID_OPERATION;
4329 goto startError;
4330 }
4331 mStartStopCond.wait(mLock);
4332 if (mActiveTrack == 0) {
4333 LOGV("Record failed to start");
4334 status = BAD_VALUE;
4335 goto startError;
4336 }
4337 LOGV("Record started OK");
4338 return status;
4339 }
4340startError:
4341 AudioSystem::stopInput(mId);
4342 return status;
4343}
4344
4345void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4346 LOGV("RecordThread::stop");
4347 sp <ThreadBase> strongMe = this;
4348 {
4349 AutoMutex lock(&mLock);
4350 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4351 mActiveTrack->mState = TrackBase::PAUSING;
4352 // do not wait for mStartStopCond if exiting
4353 if (mExiting) {
4354 return;
4355 }
4356 mStartStopCond.wait(mLock);
4357 // if we have been restarted, recordTrack == mActiveTrack.get() here
4358 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4359 mLock.unlock();
4360 AudioSystem::stopInput(mId);
4361 mLock.lock();
4362 LOGV("Record stopped OK");
4363 }
4364 }
4365 }
4366}
4367
4368status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4369{
4370 const size_t SIZE = 256;
4371 char buffer[SIZE];
4372 String8 result;
4373 pid_t pid = 0;
4374
4375 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4376 result.append(buffer);
4377
4378 if (mActiveTrack != 0) {
4379 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004380 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004381 mActiveTrack->dump(buffer, SIZE);
4382 result.append(buffer);
4383
4384 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4385 result.append(buffer);
4386 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4387 result.append(buffer);
4388 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4389 result.append(buffer);
4390 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4391 result.append(buffer);
4392 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4393 result.append(buffer);
4394
4395
4396 } else {
4397 result.append("No record client\n");
4398 }
4399 write(fd, result.string(), result.size());
4400
4401 dumpBase(fd, args);
Eric Laurent1d2bff02011-07-24 17:49:51 -07004402 dumpEffectChains(fd, args);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004403
4404 return NO_ERROR;
4405}
4406
4407status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4408{
4409 size_t framesReq = buffer->frameCount;
4410 size_t framesReady = mFrameCount - mRsmpInIndex;
4411 int channelCount;
4412
4413 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004414 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415 if (mBytesRead < 0) {
4416 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4417 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4418 // Force input into standby so that it tries to
4419 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004420 mInput->stream->common.standby(&mInput->stream->common);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004421 usleep(kRecordThreadSleepUs);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 }
4423 buffer->raw = 0;
4424 buffer->frameCount = 0;
4425 return NOT_ENOUGH_DATA;
4426 }
4427 mRsmpInIndex = 0;
4428 framesReady = mFrameCount;
4429 }
4430
4431 if (framesReq > framesReady) {
4432 framesReq = framesReady;
4433 }
4434
4435 if (mChannelCount == 1 && mReqChannelCount == 2) {
4436 channelCount = 1;
4437 } else {
4438 channelCount = 2;
4439 }
4440 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4441 buffer->frameCount = framesReq;
4442 return NO_ERROR;
4443}
4444
4445void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4446{
4447 mRsmpInIndex += buffer->frameCount;
4448 buffer->frameCount = 0;
4449}
4450
4451bool AudioFlinger::RecordThread::checkForNewParameters_l()
4452{
4453 bool reconfig = false;
4454
4455 while (!mNewParameters.isEmpty()) {
4456 status_t status = NO_ERROR;
4457 String8 keyValuePair = mNewParameters[0];
4458 AudioParameter param = AudioParameter(keyValuePair);
4459 int value;
4460 int reqFormat = mFormat;
4461 int reqSamplingRate = mReqSampleRate;
4462 int reqChannelCount = mReqChannelCount;
4463
4464 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4465 reqSamplingRate = value;
4466 reconfig = true;
4467 }
4468 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4469 reqFormat = value;
4470 reconfig = true;
4471 }
4472 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004473 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004474 reconfig = true;
4475 }
4476 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4477 // do not accept frame count changes if tracks are open as the track buffer
4478 // size depends on frame count and correct behavior would not be garantied
4479 // if frame count is changed after track creation
4480 if (mActiveTrack != 0) {
4481 status = INVALID_OPERATION;
4482 } else {
4483 reconfig = true;
4484 }
4485 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004486 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
4487 // forward device change to effects that have requested to be
4488 // aware of attached audio device.
4489 for (size_t i = 0; i < mEffectChains.size(); i++) {
4490 mEffectChains[i]->setDevice_l(value);
4491 }
4492 // store input device and output device but do not forward output device to audio HAL.
4493 // Note that status is ignored by the caller for output device
4494 // (see AudioFlinger::setParameters()
4495 if (value & AUDIO_DEVICE_OUT_ALL) {
4496 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_OUT_ALL);
4497 status = BAD_VALUE;
4498 } else {
4499 mDevice &= (uint32_t)~(value & AUDIO_DEVICE_IN_ALL);
4500 }
4501 mDevice |= (uint32_t)value;
4502 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004504 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004505 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004506 mInput->stream->common.standby(&mInput->stream->common);
4507 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 }
4509 if (reconfig) {
4510 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004511 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004512 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004513 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4514 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004515 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516 status = NO_ERROR;
4517 }
4518 if (status == NO_ERROR) {
4519 readInputParameters();
4520 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4521 }
4522 }
4523 }
4524
4525 mNewParameters.removeAt(0);
4526
4527 mParamStatus = status;
4528 mParamCond.signal();
4529 mWaitWorkCV.wait(mLock);
4530 }
4531 return reconfig;
4532}
4533
4534String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4535{
Dima Zavinfce7a472011-04-19 22:30:36 -07004536 char *s;
4537 String8 out_s8;
4538
Dima Zavin799a70e2011-04-18 16:57:27 -07004539 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004540 out_s8 = String8(s);
4541 free(s);
4542 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004543}
4544
4545void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4546 AudioSystem::OutputDescriptor desc;
4547 void *param2 = 0;
4548
4549 switch (event) {
4550 case AudioSystem::INPUT_OPENED:
4551 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004552 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004553 desc.samplingRate = mSampleRate;
4554 desc.format = mFormat;
4555 desc.frameCount = mFrameCount;
4556 desc.latency = 0;
4557 param2 = &desc;
4558 break;
4559
4560 case AudioSystem::INPUT_CLOSED:
4561 default:
4562 break;
4563 }
4564 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4565}
4566
4567void AudioFlinger::RecordThread::readInputParameters()
4568{
4569 if (mRsmpInBuffer) delete mRsmpInBuffer;
4570 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4571 if (mResampler) delete mResampler;
4572 mResampler = 0;
4573
Dima Zavin799a70e2011-04-18 16:57:27 -07004574 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004575 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4576 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004577 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4578 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4579 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004580 mFrameCount = mInputBytes / mFrameSize;
4581 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4582
4583 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4584 {
4585 int channelCount;
4586 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4587 // stereo to mono post process as the resampler always outputs stereo.
4588 if (mChannelCount == 1 && mReqChannelCount == 2) {
4589 channelCount = 1;
4590 } else {
4591 channelCount = 2;
4592 }
4593 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4594 mResampler->setSampleRate(mSampleRate);
4595 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4596 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4597
4598 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4599 if (mChannelCount == 1 && mReqChannelCount == 1) {
4600 mFrameCount >>= 1;
4601 }
4602
4603 }
4604 mRsmpInIndex = mFrameCount;
4605}
4606
4607unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4608{
Dima Zavin799a70e2011-04-18 16:57:27 -07004609 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004610}
4611
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004612uint32_t AudioFlinger::RecordThread::hasAudioSession(int sessionId)
4613{
4614 Mutex::Autolock _l(mLock);
4615 uint32_t result = 0;
4616 if (getEffectChain_l(sessionId) != 0) {
4617 result = EFFECT_SESSION;
4618 }
4619
4620 if (mTrack != NULL && sessionId == mTrack->sessionId()) {
4621 result |= TRACK_SESSION;
4622 }
4623
4624 return result;
4625}
4626
Mathias Agopian65ab4712010-07-14 17:59:35 -07004627// ----------------------------------------------------------------------------
4628
4629int AudioFlinger::openOutput(uint32_t *pDevices,
4630 uint32_t *pSamplingRate,
4631 uint32_t *pFormat,
4632 uint32_t *pChannels,
4633 uint32_t *pLatencyMs,
4634 uint32_t flags)
4635{
4636 status_t status;
4637 PlaybackThread *thread = NULL;
4638 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4639 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4640 uint32_t format = pFormat ? *pFormat : 0;
4641 uint32_t channels = pChannels ? *pChannels : 0;
4642 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004643 audio_stream_out_t *outStream;
4644 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004645
4646 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4647 pDevices ? *pDevices : 0,
4648 samplingRate,
4649 format,
4650 channels,
4651 flags);
4652
4653 if (pDevices == NULL || *pDevices == 0) {
4654 return 0;
4655 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004656
Mathias Agopian65ab4712010-07-14 17:59:35 -07004657 Mutex::Autolock _l(mLock);
4658
Dima Zavin799a70e2011-04-18 16:57:27 -07004659 outHwDev = findSuitableHwDev_l(*pDevices);
4660 if (outHwDev == NULL)
4661 return 0;
4662
4663 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4664 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004665 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004666 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 samplingRate,
4668 format,
4669 channels,
4670 status);
4671
4672 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004673 if (outStream != NULL) {
4674 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004675 int id = nextUniqueId();
Dima Zavin799a70e2011-04-18 16:57:27 -07004676
Dima Zavinfce7a472011-04-19 22:30:36 -07004677 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4678 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4679 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004680 thread = new DirectOutputThread(this, output, id, *pDevices);
4681 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4682 } else {
4683 thread = new MixerThread(this, output, id, *pDevices);
4684 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004685 }
4686 mPlaybackThreads.add(id, thread);
4687
4688 if (pSamplingRate) *pSamplingRate = samplingRate;
4689 if (pFormat) *pFormat = format;
4690 if (pChannels) *pChannels = channels;
4691 if (pLatencyMs) *pLatencyMs = thread->latency();
4692
4693 // notify client processes of the new output creation
4694 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4695 return id;
4696 }
4697
4698 return 0;
4699}
4700
4701int AudioFlinger::openDuplicateOutput(int output1, int output2)
4702{
4703 Mutex::Autolock _l(mLock);
4704 MixerThread *thread1 = checkMixerThread_l(output1);
4705 MixerThread *thread2 = checkMixerThread_l(output2);
4706
4707 if (thread1 == NULL || thread2 == NULL) {
4708 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4709 return 0;
4710 }
4711
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004712 int id = nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4714 thread->addOutputTrack(thread2);
4715 mPlaybackThreads.add(id, thread);
4716 // notify client processes of the new output creation
4717 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4718 return id;
4719}
4720
4721status_t AudioFlinger::closeOutput(int output)
4722{
4723 // keep strong reference on the playback thread so that
4724 // it is not destroyed while exit() is executed
4725 sp <PlaybackThread> thread;
4726 {
4727 Mutex::Autolock _l(mLock);
4728 thread = checkPlaybackThread_l(output);
4729 if (thread == NULL) {
4730 return BAD_VALUE;
4731 }
4732
4733 LOGV("closeOutput() %d", output);
4734
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004735 if (thread->type() == ThreadBase::MIXER) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004736 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004737 if (mPlaybackThreads.valueAt(i)->type() == ThreadBase::DUPLICATING) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004738 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4739 dupThread->removeOutputTrack((MixerThread *)thread.get());
4740 }
4741 }
4742 }
4743 void *param2 = 0;
4744 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4745 mPlaybackThreads.removeItem(output);
4746 }
4747 thread->exit();
4748
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004749 if (thread->type() != ThreadBase::DUPLICATING) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004750 AudioStreamOut *out = thread->getOutput();
4751 out->hwDev->close_output_stream(out->hwDev, out->stream);
4752 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004753 }
4754 return NO_ERROR;
4755}
4756
4757status_t AudioFlinger::suspendOutput(int output)
4758{
4759 Mutex::Autolock _l(mLock);
4760 PlaybackThread *thread = checkPlaybackThread_l(output);
4761
4762 if (thread == NULL) {
4763 return BAD_VALUE;
4764 }
4765
4766 LOGV("suspendOutput() %d", output);
4767 thread->suspend();
4768
4769 return NO_ERROR;
4770}
4771
4772status_t AudioFlinger::restoreOutput(int output)
4773{
4774 Mutex::Autolock _l(mLock);
4775 PlaybackThread *thread = checkPlaybackThread_l(output);
4776
4777 if (thread == NULL) {
4778 return BAD_VALUE;
4779 }
4780
4781 LOGV("restoreOutput() %d", output);
4782
4783 thread->restore();
4784
4785 return NO_ERROR;
4786}
4787
4788int AudioFlinger::openInput(uint32_t *pDevices,
4789 uint32_t *pSamplingRate,
4790 uint32_t *pFormat,
4791 uint32_t *pChannels,
4792 uint32_t acoustics)
4793{
4794 status_t status;
4795 RecordThread *thread = NULL;
4796 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4797 uint32_t format = pFormat ? *pFormat : 0;
4798 uint32_t channels = pChannels ? *pChannels : 0;
4799 uint32_t reqSamplingRate = samplingRate;
4800 uint32_t reqFormat = format;
4801 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004802 audio_stream_in_t *inStream;
4803 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004804
4805 if (pDevices == NULL || *pDevices == 0) {
4806 return 0;
4807 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004808
Mathias Agopian65ab4712010-07-14 17:59:35 -07004809 Mutex::Autolock _l(mLock);
4810
Dima Zavin799a70e2011-04-18 16:57:27 -07004811 inHwDev = findSuitableHwDev_l(*pDevices);
4812 if (inHwDev == NULL)
4813 return 0;
4814
4815 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4816 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004817 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004818 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004819 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004820 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004821 samplingRate,
4822 format,
4823 channels,
4824 acoustics,
4825 status);
4826
4827 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4828 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4829 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07004830 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004831 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004832 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004833 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004834 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07004835 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4836 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004837 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004838 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004839 }
4840
Dima Zavin799a70e2011-04-18 16:57:27 -07004841 if (inStream != NULL) {
4842 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4843
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004844 int id = nextUniqueId();
4845 // Start record thread
4846 // RecorThread require both input and output device indication to forward to audio
4847 // pre processing modules
4848 uint32_t device = (*pDevices) | primaryOutputDevice_l();
4849 thread = new RecordThread(this,
4850 input,
4851 reqSamplingRate,
4852 reqChannels,
4853 id,
4854 device);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004855 mRecordThreads.add(id, thread);
4856 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4857 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4858 if (pFormat) *pFormat = format;
4859 if (pChannels) *pChannels = reqChannels;
4860
Dima Zavin799a70e2011-04-18 16:57:27 -07004861 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004862
4863 // notify client processes of the new input creation
4864 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4865 return id;
4866 }
4867
4868 return 0;
4869}
4870
4871status_t AudioFlinger::closeInput(int input)
4872{
4873 // keep strong reference on the record thread so that
4874 // it is not destroyed while exit() is executed
4875 sp <RecordThread> thread;
4876 {
4877 Mutex::Autolock _l(mLock);
4878 thread = checkRecordThread_l(input);
4879 if (thread == NULL) {
4880 return BAD_VALUE;
4881 }
4882
4883 LOGV("closeInput() %d", input);
4884 void *param2 = 0;
4885 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4886 mRecordThreads.removeItem(input);
4887 }
4888 thread->exit();
4889
Dima Zavin799a70e2011-04-18 16:57:27 -07004890 AudioStreamIn *in = thread->getInput();
4891 in->hwDev->close_input_stream(in->hwDev, in->stream);
4892 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004893
4894 return NO_ERROR;
4895}
4896
4897status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4898{
4899 Mutex::Autolock _l(mLock);
4900 MixerThread *dstThread = checkMixerThread_l(output);
4901 if (dstThread == NULL) {
4902 LOGW("setStreamOutput() bad output id %d", output);
4903 return BAD_VALUE;
4904 }
4905
4906 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4907 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4908
4909 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4910 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4911 if (thread != dstThread &&
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004912 thread->type() != ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004913 MixerThread *srcThread = (MixerThread *)thread;
4914 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004915 }
Eric Laurentde070132010-07-13 04:45:46 -07004916 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917
4918 return NO_ERROR;
4919}
4920
4921
4922int AudioFlinger::newAudioSessionId()
4923{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004924 return nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004925}
4926
4927// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4928AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4929{
4930 PlaybackThread *thread = NULL;
4931 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4932 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4933 }
4934 return thread;
4935}
4936
4937// checkMixerThread_l() must be called with AudioFlinger::mLock held
4938AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4939{
4940 PlaybackThread *thread = checkPlaybackThread_l(output);
4941 if (thread != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004942 if (thread->type() == ThreadBase::DIRECT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004943 thread = NULL;
4944 }
4945 }
4946 return (MixerThread *)thread;
4947}
4948
4949// checkRecordThread_l() must be called with AudioFlinger::mLock held
4950AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4951{
4952 RecordThread *thread = NULL;
4953 if (mRecordThreads.indexOfKey(input) >= 0) {
4954 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4955 }
4956 return thread;
4957}
4958
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004959uint32_t AudioFlinger::nextUniqueId()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004960{
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004961 return android_atomic_inc(&mNextUniqueId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004962}
4963
Eric Laurent7c7f10b2011-06-17 21:29:58 -07004964AudioFlinger::PlaybackThread *AudioFlinger::primaryPlaybackThread_l()
4965{
4966 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4967 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4968 if (thread->getOutput()->hwDev == mPrimaryHardwareDev) {
4969 return thread;
4970 }
4971 }
4972 return NULL;
4973}
4974
4975uint32_t AudioFlinger::primaryOutputDevice_l()
4976{
4977 PlaybackThread *thread = primaryPlaybackThread_l();
4978
4979 if (thread == NULL) {
4980 return 0;
4981 }
4982
4983 return thread->device();
4984}
4985
4986
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987// ----------------------------------------------------------------------------
4988// Effect management
4989// ----------------------------------------------------------------------------
4990
4991
Mathias Agopian65ab4712010-07-14 17:59:35 -07004992status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4993{
4994 Mutex::Autolock _l(mLock);
4995 return EffectQueryNumberEffects(numEffects);
4996}
4997
4998status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4999{
5000 Mutex::Autolock _l(mLock);
5001 return EffectQueryEffect(index, descriptor);
5002}
5003
5004status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
5005{
5006 Mutex::Autolock _l(mLock);
5007 return EffectGetDescriptor(pUuid, descriptor);
5008}
5009
5010
Mathias Agopian65ab4712010-07-14 17:59:35 -07005011sp<IEffect> AudioFlinger::createEffect(pid_t pid,
5012 effect_descriptor_t *pDesc,
5013 const sp<IEffectClient>& effectClient,
5014 int32_t priority,
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005015 int io,
Mathias Agopian65ab4712010-07-14 17:59:35 -07005016 int sessionId,
5017 status_t *status,
5018 int *id,
5019 int *enabled)
5020{
5021 status_t lStatus = NO_ERROR;
5022 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005023 effect_descriptor_t desc;
5024 sp<Client> client;
5025 wp<Client> wclient;
5026
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005027 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, io %d",
5028 pid, effectClient.get(), priority, sessionId, io);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005029
5030 if (pDesc == NULL) {
5031 lStatus = BAD_VALUE;
5032 goto Exit;
5033 }
5034
Eric Laurent84e9a102010-09-23 16:10:16 -07005035 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005036 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005037 lStatus = PERMISSION_DENIED;
5038 goto Exit;
5039 }
5040
Dima Zavinfce7a472011-04-19 22:30:36 -07005041 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07005042 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07005043 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005044 lStatus = PERMISSION_DENIED;
5045 goto Exit;
5046 }
5047
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005048 if (io == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07005049 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005050 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07005051 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07005052 lStatus = BAD_VALUE;
5053 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07005054 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005055 // if the output returned by getOutputForEffect() is removed before we lock the
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005056 // mutex below, the call to checkPlaybackThread_l(io) below will detect it
Eric Laurent84e9a102010-09-23 16:10:16 -07005057 // and we will exit safely
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005058 io = AudioSystem::getOutputForEffect(&desc);
Eric Laurent84e9a102010-09-23 16:10:16 -07005059 }
5060 }
5061
Mathias Agopian65ab4712010-07-14 17:59:35 -07005062 {
5063 Mutex::Autolock _l(mLock);
5064
Mathias Agopian65ab4712010-07-14 17:59:35 -07005065
5066 if (!EffectIsNullUuid(&pDesc->uuid)) {
5067 // if uuid is specified, request effect descriptor
5068 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
5069 if (lStatus < 0) {
5070 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
5071 goto Exit;
5072 }
5073 } else {
5074 // if uuid is not specified, look for an available implementation
5075 // of the required type in effect factory
5076 if (EffectIsNullUuid(&pDesc->type)) {
5077 LOGW("createEffect() no effect type");
5078 lStatus = BAD_VALUE;
5079 goto Exit;
5080 }
5081 uint32_t numEffects = 0;
5082 effect_descriptor_t d;
5083 bool found = false;
5084
5085 lStatus = EffectQueryNumberEffects(&numEffects);
5086 if (lStatus < 0) {
5087 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
5088 goto Exit;
5089 }
5090 for (uint32_t i = 0; i < numEffects; i++) {
5091 lStatus = EffectQueryEffect(i, &desc);
5092 if (lStatus < 0) {
5093 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
5094 continue;
5095 }
5096 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
5097 // If matching type found save effect descriptor. If the session is
5098 // 0 and the effect is not auxiliary, continue enumeration in case
5099 // an auxiliary version of this effect type is available
5100 found = true;
5101 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07005102 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005103 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5104 break;
5105 }
5106 }
5107 }
5108 if (!found) {
5109 lStatus = BAD_VALUE;
5110 LOGW("createEffect() effect not found");
5111 goto Exit;
5112 }
5113 // For same effect type, chose auxiliary version over insert version if
5114 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07005115 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005116 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
5117 memcpy(&desc, &d, sizeof(effect_descriptor_t));
5118 }
5119 }
5120
5121 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07005122 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07005123 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5124 lStatus = INVALID_OPERATION;
5125 goto Exit;
5126 }
5127
Eric Laurent59255e42011-07-27 19:49:51 -07005128 // check recording permission for visualizer
5129 if ((memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0) &&
5130 !recordingAllowed()) {
5131 lStatus = PERMISSION_DENIED;
5132 goto Exit;
5133 }
5134
Mathias Agopian65ab4712010-07-14 17:59:35 -07005135 // return effect descriptor
5136 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
5137
5138 // If output is not specified try to find a matching audio session ID in one of the
5139 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07005140 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
5141 // because of code checking output when entering the function.
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005142 // Note: io is never 0 when creating an effect on an input
5143 if (io == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07005144 // look for the thread where the specified audio session is present
5145 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
5146 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005147 io = mPlaybackThreads.keyAt(i);
Eric Laurent84e9a102010-09-23 16:10:16 -07005148 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07005149 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005150 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005151 if (io == 0) {
5152 for (size_t i = 0; i < mRecordThreads.size(); i++) {
5153 if (mRecordThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
5154 io = mRecordThreads.keyAt(i);
5155 break;
5156 }
5157 }
5158 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005159 // If no output thread contains the requested session ID, default to
5160 // first output. The effect chain will be moved to the correct output
5161 // thread when a track with the same session ID is created
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005162 if (io == 0 && mPlaybackThreads.size()) {
5163 io = mPlaybackThreads.keyAt(0);
5164 }
5165 LOGV("createEffect() got io %d for effect %s", io, desc.name);
5166 }
5167 ThreadBase *thread = checkRecordThread_l(io);
5168 if (thread == NULL) {
5169 thread = checkPlaybackThread_l(io);
5170 if (thread == NULL) {
5171 LOGE("createEffect() unknown output thread");
5172 lStatus = BAD_VALUE;
5173 goto Exit;
Eric Laurent84e9a102010-09-23 16:10:16 -07005174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005175 }
Eric Laurent84e9a102010-09-23 16:10:16 -07005176
Mathias Agopian65ab4712010-07-14 17:59:35 -07005177 wclient = mClients.valueFor(pid);
5178
5179 if (wclient != NULL) {
5180 client = wclient.promote();
5181 } else {
5182 client = new Client(this, pid);
5183 mClients.add(pid, client);
5184 }
5185
5186 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07005187 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
5188 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005189 if (handle != 0 && id != NULL) {
5190 *id = handle->id();
5191 }
5192 }
5193
5194Exit:
5195 if(status) {
5196 *status = lStatus;
5197 }
5198 return handle;
5199}
5200
Eric Laurent59255e42011-07-27 19:49:51 -07005201status_t AudioFlinger::moveEffects(int sessionId, int srcOutput, int dstOutput)
Eric Laurentde070132010-07-13 04:45:46 -07005202{
5203 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
Eric Laurent59255e42011-07-27 19:49:51 -07005204 sessionId, srcOutput, dstOutput);
Eric Laurentde070132010-07-13 04:45:46 -07005205 Mutex::Autolock _l(mLock);
5206 if (srcOutput == dstOutput) {
5207 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
5208 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005209 }
Eric Laurentde070132010-07-13 04:45:46 -07005210 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
5211 if (srcThread == NULL) {
5212 LOGW("moveEffects() bad srcOutput %d", srcOutput);
5213 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005214 }
Eric Laurentde070132010-07-13 04:45:46 -07005215 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
5216 if (dstThread == NULL) {
5217 LOGW("moveEffects() bad dstOutput %d", dstOutput);
5218 return BAD_VALUE;
5219 }
5220
5221 Mutex::Autolock _dl(dstThread->mLock);
5222 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent59255e42011-07-27 19:49:51 -07005223 moveEffectChain_l(sessionId, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07005224
Mathias Agopian65ab4712010-07-14 17:59:35 -07005225 return NO_ERROR;
5226}
5227
Eric Laurentde070132010-07-13 04:45:46 -07005228// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
Eric Laurent59255e42011-07-27 19:49:51 -07005229status_t AudioFlinger::moveEffectChain_l(int sessionId,
Eric Laurentde070132010-07-13 04:45:46 -07005230 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07005231 AudioFlinger::PlaybackThread *dstThread,
5232 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07005233{
5234 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005235 sessionId, srcThread, dstThread);
Eric Laurentde070132010-07-13 04:45:46 -07005236
Eric Laurent59255e42011-07-27 19:49:51 -07005237 sp<EffectChain> chain = srcThread->getEffectChain_l(sessionId);
Eric Laurentde070132010-07-13 04:45:46 -07005238 if (chain == 0) {
5239 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
Eric Laurent59255e42011-07-27 19:49:51 -07005240 sessionId, srcThread);
Eric Laurentde070132010-07-13 04:45:46 -07005241 return INVALID_OPERATION;
5242 }
5243
Eric Laurent39e94f82010-07-28 01:32:47 -07005244 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07005245 // so that a new chain is created with correct parameters when first effect is added. This is
5246 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
5247 // removed.
5248 srcThread->removeEffectChain_l(chain);
5249
5250 // transfer all effects one by one so that new effect chain is created on new thread with
5251 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07005252 int dstOutput = dstThread->id();
5253 sp<EffectChain> dstChain;
5254 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07005255 sp<EffectModule> effect = chain->getEffectFromId_l(0);
5256 while (effect != 0) {
5257 srcThread->removeEffect_l(effect);
5258 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07005259 // if the move request is not received from audio policy manager, the effect must be
5260 // re-registered with the new strategy and output
5261 if (dstChain == 0) {
5262 dstChain = effect->chain().promote();
5263 if (dstChain == 0) {
5264 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
5265 srcThread->addEffect_l(effect);
5266 return NO_INIT;
5267 }
5268 strategy = dstChain->strategy();
5269 }
5270 if (reRegister) {
5271 AudioSystem::unregisterEffect(effect->id());
5272 AudioSystem::registerEffect(&effect->desc(),
5273 dstOutput,
5274 strategy,
Eric Laurent59255e42011-07-27 19:49:51 -07005275 sessionId,
Eric Laurent39e94f82010-07-28 01:32:47 -07005276 effect->id());
5277 }
Eric Laurentde070132010-07-13 04:45:46 -07005278 effect = chain->getEffectFromId_l(0);
5279 }
5280
5281 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005282}
5283
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005284
Mathias Agopian65ab4712010-07-14 17:59:35 -07005285// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005286sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
Mathias Agopian65ab4712010-07-14 17:59:35 -07005287 const sp<AudioFlinger::Client>& client,
5288 const sp<IEffectClient>& effectClient,
5289 int32_t priority,
5290 int sessionId,
5291 effect_descriptor_t *desc,
5292 int *enabled,
5293 status_t *status
5294 )
5295{
5296 sp<EffectModule> effect;
5297 sp<EffectHandle> handle;
5298 status_t lStatus;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07005300 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005301 bool effectCreated = false;
5302 bool effectRegistered = false;
5303
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005304 lStatus = initCheck();
5305 if (lStatus != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005306 LOGW("createEffect_l() Audio driver not initialized.");
Mathias Agopian65ab4712010-07-14 17:59:35 -07005307 goto Exit;
5308 }
5309
5310 // Do not allow effects with session ID 0 on direct output or duplicating threads
5311 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07005312 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07005313 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
5314 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005315 lStatus = BAD_VALUE;
5316 goto Exit;
5317 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005318 // Only Pre processor effects are allowed on input threads and only on input threads
5319 if ((mType == RECORD &&
5320 (desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) ||
5321 (mType != RECORD &&
5322 (desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
5323 LOGW("createEffect_l() effect %s (flags %08x) created on wrong thread type %d",
5324 desc->name, desc->flags, mType);
5325 lStatus = BAD_VALUE;
5326 goto Exit;
5327 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005328
5329 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
5330
5331 { // scope for mLock
5332 Mutex::Autolock _l(mLock);
5333
5334 // check for existing effect chain with the requested audio session
5335 chain = getEffectChain_l(sessionId);
5336 if (chain == 0) {
5337 // create a new chain for this session
5338 LOGV("createEffect_l() new effect chain for session %d", sessionId);
5339 chain = new EffectChain(this, sessionId);
5340 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07005341 chain->setStrategy(getStrategyForSession_l(sessionId));
5342 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005343 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07005344 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005345 }
5346
5347 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
5348
5349 if (effect == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005350 int id = mAudioFlinger->nextUniqueId();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005351 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07005352 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353 if (lStatus != NO_ERROR) {
5354 goto Exit;
5355 }
5356 effectRegistered = true;
5357 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07005358 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359 lStatus = effect->status();
5360 if (lStatus != NO_ERROR) {
5361 goto Exit;
5362 }
Eric Laurentcab11242010-07-15 12:50:15 -07005363 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364 if (lStatus != NO_ERROR) {
5365 goto Exit;
5366 }
5367 effectCreated = true;
5368
5369 effect->setDevice(mDevice);
5370 effect->setMode(mAudioFlinger->getMode());
5371 }
5372 // create effect handle and connect it to effect module
5373 handle = new EffectHandle(effect, client, effectClient, priority);
5374 lStatus = effect->addHandle(handle);
5375 if (enabled) {
5376 *enabled = (int)effect->isEnabled();
5377 }
5378 }
5379
5380Exit:
5381 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005382 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005383 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005384 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005385 }
5386 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005387 AudioSystem::unregisterEffect(effect->id());
5388 }
5389 if (chainCreated) {
5390 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 }
5392 handle.clear();
5393 }
5394
5395 if(status) {
5396 *status = lStatus;
5397 }
5398 return handle;
5399}
5400
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005401sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(int sessionId, int effectId)
5402{
5403 sp<EffectModule> effect;
5404
5405 sp<EffectChain> chain = getEffectChain_l(sessionId);
5406 if (chain != 0) {
5407 effect = chain->getEffectFromId_l(effectId);
5408 }
5409 return effect;
5410}
5411
Eric Laurentde070132010-07-13 04:45:46 -07005412// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5413// PlaybackThread::mLock held
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005414status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
Eric Laurentde070132010-07-13 04:45:46 -07005415{
5416 // check for existing effect chain with the requested audio session
5417 int sessionId = effect->sessionId();
5418 sp<EffectChain> chain = getEffectChain_l(sessionId);
5419 bool chainCreated = false;
5420
5421 if (chain == 0) {
5422 // create a new chain for this session
5423 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5424 chain = new EffectChain(this, sessionId);
5425 addEffectChain_l(chain);
5426 chain->setStrategy(getStrategyForSession_l(sessionId));
5427 chainCreated = true;
5428 }
5429 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5430
5431 if (chain->getEffectFromId_l(effect->id()) != 0) {
5432 LOGW("addEffect_l() %p effect %s already present in chain %p",
5433 this, effect->desc().name, chain.get());
5434 return BAD_VALUE;
5435 }
5436
5437 status_t status = chain->addEffect_l(effect);
5438 if (status != NO_ERROR) {
5439 if (chainCreated) {
5440 removeEffectChain_l(chain);
5441 }
5442 return status;
5443 }
5444
5445 effect->setDevice(mDevice);
5446 effect->setMode(mAudioFlinger->getMode());
5447 return NO_ERROR;
5448}
5449
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005450void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect) {
Eric Laurentde070132010-07-13 04:45:46 -07005451
5452 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005454 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5455 detachAuxEffect_l(effect->id());
5456 }
5457
5458 sp<EffectChain> chain = effect->chain().promote();
5459 if (chain != 0) {
5460 // remove effect chain if removing last effect
5461 if (chain->removeEffect_l(effect) == 0) {
5462 removeEffectChain_l(chain);
5463 }
5464 } else {
5465 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5466 }
5467}
5468
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005469void AudioFlinger::ThreadBase::lockEffectChains_l(
5470 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5471{
5472 effectChains = mEffectChains;
5473 for (size_t i = 0; i < mEffectChains.size(); i++) {
5474 mEffectChains[i]->lock();
5475 }
5476}
5477
5478void AudioFlinger::ThreadBase::unlockEffectChains(
5479 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
5480{
5481 for (size_t i = 0; i < effectChains.size(); i++) {
5482 effectChains[i]->unlock();
5483 }
5484}
5485
5486sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(int sessionId)
5487{
5488 Mutex::Autolock _l(mLock);
5489 return getEffectChain_l(sessionId);
5490}
5491
5492sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(int sessionId)
5493{
5494 sp<EffectChain> chain;
5495
5496 size_t size = mEffectChains.size();
5497 for (size_t i = 0; i < size; i++) {
5498 if (mEffectChains[i]->sessionId() == sessionId) {
5499 chain = mEffectChains[i];
5500 break;
5501 }
5502 }
5503 return chain;
5504}
5505
5506void AudioFlinger::ThreadBase::setMode(uint32_t mode)
5507{
5508 Mutex::Autolock _l(mLock);
5509 size_t size = mEffectChains.size();
5510 for (size_t i = 0; i < size; i++) {
5511 mEffectChains[i]->setMode_l(mode);
5512 }
5513}
5514
5515void AudioFlinger::ThreadBase::disconnectEffect(const sp<EffectModule>& effect,
Eric Laurentde070132010-07-13 04:45:46 -07005516 const wp<EffectHandle>& handle) {
Eric Laurent59255e42011-07-27 19:49:51 -07005517
Mathias Agopian65ab4712010-07-14 17:59:35 -07005518 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005519 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005520 // delete the effect module if removing last handle on it
5521 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07005522 removeEffect_l(effect);
5523 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005524 }
5525}
5526
5527status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5528{
5529 int session = chain->sessionId();
5530 int16_t *buffer = mMixBuffer;
5531 bool ownsBuffer = false;
5532
5533 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5534 if (session > 0) {
5535 // Only one effect chain can be present in direct output thread and it uses
5536 // the mix buffer as input
5537 if (mType != DIRECT) {
5538 size_t numSamples = mFrameCount * mChannelCount;
5539 buffer = new int16_t[numSamples];
5540 memset(buffer, 0, numSamples * sizeof(int16_t));
5541 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5542 ownsBuffer = true;
5543 }
5544
5545 // Attach all tracks with same session ID to this chain.
5546 for (size_t i = 0; i < mTracks.size(); ++i) {
5547 sp<Track> track = mTracks[i];
5548 if (session == track->sessionId()) {
5549 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5550 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005551 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005552 }
5553 }
5554
5555 // indicate all active tracks in the chain
5556 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5557 sp<Track> track = mActiveTracks[i].promote();
5558 if (track == 0) continue;
5559 if (session == track->sessionId()) {
5560 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005561 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005562 }
5563 }
5564 }
5565
5566 chain->setInBuffer(buffer, ownsBuffer);
5567 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005568 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005569 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005570 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5571 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005572 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005573 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5574 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005575 // Effect chain for other sessions are inserted at beginning of effect
5576 // chains list to be processed before output mix effects. Relative order between other
5577 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005578 size_t size = mEffectChains.size();
5579 size_t i = 0;
5580 for (i = 0; i < size; i++) {
5581 if (mEffectChains[i]->sessionId() < session) break;
5582 }
5583 mEffectChains.insertAt(chain, i);
Eric Laurent59255e42011-07-27 19:49:51 -07005584 checkSuspendOnAddEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005585
5586 return NO_ERROR;
5587}
5588
5589size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5590{
5591 int session = chain->sessionId();
5592
5593 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5594
5595 for (size_t i = 0; i < mEffectChains.size(); i++) {
5596 if (chain == mEffectChains[i]) {
Eric Laurent59255e42011-07-27 19:49:51 -07005597 updateSuspendedSessionsOnRemoveEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005598 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005599 // detach all active tracks from the chain
5600 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5601 sp<Track> track = mActiveTracks[i].promote();
5602 if (track == 0) continue;
5603 if (session == track->sessionId()) {
5604 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5605 chain.get(), session);
5606 chain->decActiveTrackCnt();
5607 }
5608 }
5609
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610 // detach all tracks with same session ID from this chain
5611 for (size_t i = 0; i < mTracks.size(); ++i) {
5612 sp<Track> track = mTracks[i];
5613 if (session == track->sessionId()) {
5614 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005615 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005616 }
5617 }
Eric Laurentde070132010-07-13 04:45:46 -07005618 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005619 }
5620 }
5621 return mEffectChains.size();
5622}
5623
Eric Laurentde070132010-07-13 04:45:46 -07005624status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5625 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005626{
5627 Mutex::Autolock _l(mLock);
5628 return attachAuxEffect_l(track, EffectId);
5629}
5630
Eric Laurentde070132010-07-13 04:45:46 -07005631status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5632 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005633{
5634 status_t status = NO_ERROR;
5635
5636 if (EffectId == 0) {
5637 track->setAuxBuffer(0, NULL);
5638 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005639 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5640 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005641 if (effect != 0) {
5642 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5643 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5644 } else {
5645 status = INVALID_OPERATION;
5646 }
5647 } else {
5648 status = BAD_VALUE;
5649 }
5650 }
5651 return status;
5652}
5653
5654void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5655{
5656 for (size_t i = 0; i < mTracks.size(); ++i) {
5657 sp<Track> track = mTracks[i];
5658 if (track->auxEffectId() == effectId) {
5659 attachAuxEffect_l(track, 0);
5660 }
5661 }
5662}
5663
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005664status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
5665{
5666 // only one chain per input thread
5667 if (mEffectChains.size() != 0) {
5668 return INVALID_OPERATION;
5669 }
5670 LOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
5671
5672 chain->setInBuffer(NULL);
5673 chain->setOutBuffer(NULL);
5674
Eric Laurent59255e42011-07-27 19:49:51 -07005675 checkSuspendOnAddEffectChain_l(chain);
5676
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005677 mEffectChains.add(chain);
5678
5679 return NO_ERROR;
5680}
5681
5682size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
5683{
5684 LOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
5685 LOGW_IF(mEffectChains.size() != 1,
5686 "removeEffectChain_l() %p invalid chain size %d on thread %p",
5687 chain.get(), mEffectChains.size(), this);
5688 if (mEffectChains.size() == 1) {
Eric Laurent59255e42011-07-27 19:49:51 -07005689 updateSuspendedSessionsOnRemoveEffectChain_l(chain);
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005690 mEffectChains.removeAt(0);
5691 }
5692 return 0;
5693}
5694
Mathias Agopian65ab4712010-07-14 17:59:35 -07005695// ----------------------------------------------------------------------------
5696// EffectModule implementation
5697// ----------------------------------------------------------------------------
5698
5699#undef LOG_TAG
5700#define LOG_TAG "AudioFlinger::EffectModule"
5701
5702AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5703 const wp<AudioFlinger::EffectChain>& chain,
5704 effect_descriptor_t *desc,
5705 int id,
5706 int sessionId)
5707 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
Eric Laurent59255e42011-07-27 19:49:51 -07005708 mStatus(NO_INIT), mState(IDLE), mSuspended(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005709{
5710 LOGV("Constructor %p", this);
5711 int lStatus;
5712 sp<ThreadBase> thread = mThread.promote();
5713 if (thread == 0) {
5714 return;
5715 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005716
5717 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5718
5719 // create effect engine from effect factory
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005720 mStatus = EffectCreate(&desc->uuid, sessionId, thread->id(), &mEffectInterface);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005721
5722 if (mStatus != NO_ERROR) {
5723 return;
5724 }
5725 lStatus = init();
5726 if (lStatus < 0) {
5727 mStatus = lStatus;
5728 goto Error;
5729 }
5730
5731 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5732 return;
5733Error:
5734 EffectRelease(mEffectInterface);
5735 mEffectInterface = NULL;
5736 LOGV("Constructor Error %d", mStatus);
5737}
5738
5739AudioFlinger::EffectModule::~EffectModule()
5740{
5741 LOGV("Destructor %p", this);
5742 if (mEffectInterface != NULL) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005743 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
5744 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
5745 sp<ThreadBase> thread = mThread.promote();
5746 if (thread != 0) {
5747 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
5748 }
5749 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 // release effect engine
5751 EffectRelease(mEffectInterface);
5752 }
5753}
5754
5755status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5756{
5757 status_t status;
5758
5759 Mutex::Autolock _l(mLock);
5760 // First handle in mHandles has highest priority and controls the effect module
5761 int priority = handle->priority();
5762 size_t size = mHandles.size();
5763 sp<EffectHandle> h;
5764 size_t i;
5765 for (i = 0; i < size; i++) {
5766 h = mHandles[i].promote();
5767 if (h == 0) continue;
5768 if (h->priority() <= priority) break;
5769 }
5770 // if inserted in first place, move effect control from previous owner to this handle
5771 if (i == 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07005772 bool enabled = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005773 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07005774 enabled = h->enabled();
5775 h->setControl(false/*hasControl*/, true /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005776 }
Eric Laurent59255e42011-07-27 19:49:51 -07005777 handle->setControl(true /*hasControl*/, false /*signal*/, enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005778 status = NO_ERROR;
5779 } else {
5780 status = ALREADY_EXISTS;
5781 }
Eric Laurent59255e42011-07-27 19:49:51 -07005782 LOGV("addHandle() %p added handle %p in position %d", this, handle.get(), i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005783 mHandles.insertAt(handle, i);
5784 return status;
5785}
5786
5787size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5788{
5789 Mutex::Autolock _l(mLock);
5790 size_t size = mHandles.size();
5791 size_t i;
5792 for (i = 0; i < size; i++) {
5793 if (mHandles[i] == handle) break;
5794 }
5795 if (i == size) {
5796 return size;
5797 }
Eric Laurent59255e42011-07-27 19:49:51 -07005798 LOGV("removeHandle() %p removed handle %p in position %d", this, handle.unsafe_get(), i);
5799
5800 bool enabled = false;
5801 EffectHandle *hdl = handle.unsafe_get();
5802 if (hdl) {
5803 LOGV("removeHandle() unsafe_get OK");
5804 enabled = hdl->enabled();
5805 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005806 mHandles.removeAt(i);
5807 size = mHandles.size();
5808 // if removed from first place, move effect control from this handle to next in line
5809 if (i == 0 && size != 0) {
5810 sp<EffectHandle> h = mHandles[0].promote();
5811 if (h != 0) {
Eric Laurent59255e42011-07-27 19:49:51 -07005812 h->setControl(true /*hasControl*/, true /*signal*/ , enabled /*enabled*/);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005813 }
5814 }
5815
Eric Laurentec437d82011-07-26 20:54:46 -07005816 // Prevent calls to process() and other functions on effect interface from now on.
5817 // The effect engine will be released by the destructor when the last strong reference on
5818 // this object is released which can happen after next process is called.
5819 if (size == 0) {
5820 mState = DESTROYED;
Eric Laurentdac69112010-09-28 14:09:57 -07005821 }
5822
Mathias Agopian65ab4712010-07-14 17:59:35 -07005823 return size;
5824}
5825
Eric Laurent59255e42011-07-27 19:49:51 -07005826sp<AudioFlinger::EffectHandle> AudioFlinger::EffectModule::controlHandle()
5827{
5828 Mutex::Autolock _l(mLock);
5829 sp<EffectHandle> handle;
5830 if (mHandles.size() != 0) {
5831 handle = mHandles[0].promote();
5832 }
5833 return handle;
5834}
5835
5836
5837
Mathias Agopian65ab4712010-07-14 17:59:35 -07005838void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5839{
Eric Laurent59255e42011-07-27 19:49:51 -07005840 LOGV("disconnect() %p handle %p ", this, handle.unsafe_get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005841 // keep a strong reference on this EffectModule to avoid calling the
5842 // destructor before we exit
5843 sp<EffectModule> keep(this);
5844 {
5845 sp<ThreadBase> thread = mThread.promote();
5846 if (thread != 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07005847 thread->disconnectEffect(keep, handle);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005848 }
5849 }
5850}
5851
5852void AudioFlinger::EffectModule::updateState() {
5853 Mutex::Autolock _l(mLock);
5854
5855 switch (mState) {
5856 case RESTART:
5857 reset_l();
5858 // FALL THROUGH
5859
5860 case STARTING:
5861 // clear auxiliary effect input buffer for next accumulation
5862 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5863 memset(mConfig.inputCfg.buffer.raw,
5864 0,
5865 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5866 }
5867 start_l();
5868 mState = ACTIVE;
5869 break;
5870 case STOPPING:
5871 stop_l();
5872 mDisableWaitCnt = mMaxDisableWaitCnt;
5873 mState = STOPPED;
5874 break;
5875 case STOPPED:
5876 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5877 // turn off sequence.
5878 if (--mDisableWaitCnt == 0) {
5879 reset_l();
5880 mState = IDLE;
5881 }
5882 break;
Eric Laurentec437d82011-07-26 20:54:46 -07005883 default: //IDLE , ACTIVE, DESTROYED
Mathias Agopian65ab4712010-07-14 17:59:35 -07005884 break;
5885 }
5886}
5887
5888void AudioFlinger::EffectModule::process()
5889{
5890 Mutex::Autolock _l(mLock);
5891
Eric Laurentec437d82011-07-26 20:54:46 -07005892 if (mState == DESTROYED || mEffectInterface == NULL ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07005893 mConfig.inputCfg.buffer.raw == NULL ||
5894 mConfig.outputCfg.buffer.raw == NULL) {
5895 return;
5896 }
5897
Eric Laurent8f45bd72010-08-31 13:50:07 -07005898 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005899 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5900 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5901 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5902 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005903 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005904 }
5905
5906 // do the actual processing in the effect engine
5907 int ret = (*mEffectInterface)->process(mEffectInterface,
5908 &mConfig.inputCfg.buffer,
5909 &mConfig.outputCfg.buffer);
5910
5911 // force transition to IDLE state when engine is ready
5912 if (mState == STOPPED && ret == -ENODATA) {
5913 mDisableWaitCnt = 1;
5914 }
5915
5916 // clear auxiliary effect input buffer for next accumulation
5917 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005918 memset(mConfig.inputCfg.buffer.raw, 0,
5919 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005920 }
5921 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005922 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5923 // If an insert effect is idle and input buffer is different from output buffer,
5924 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005925 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07005926 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005927 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5928 int16_t *in = mConfig.inputCfg.buffer.s16;
5929 int16_t *out = mConfig.outputCfg.buffer.s16;
5930 for (size_t i = 0; i < frameCnt; i++) {
5931 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005932 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005933 }
5934 }
5935}
5936
5937void AudioFlinger::EffectModule::reset_l()
5938{
5939 if (mEffectInterface == NULL) {
5940 return;
5941 }
5942 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5943}
5944
5945status_t AudioFlinger::EffectModule::configure()
5946{
5947 uint32_t channels;
5948 if (mEffectInterface == NULL) {
5949 return NO_INIT;
5950 }
5951
5952 sp<ThreadBase> thread = mThread.promote();
5953 if (thread == 0) {
5954 return DEAD_OBJECT;
5955 }
5956
5957 // TODO: handle configuration of effects replacing track process
5958 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005959 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005960 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07005961 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005962 }
5963
5964 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005965 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005966 } else {
5967 mConfig.inputCfg.channels = channels;
5968 }
5969 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07005970 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5971 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005972 mConfig.inputCfg.samplingRate = thread->sampleRate();
5973 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5974 mConfig.inputCfg.bufferProvider.cookie = NULL;
5975 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5976 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5977 mConfig.outputCfg.bufferProvider.cookie = NULL;
5978 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5979 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5980 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5981 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07005982 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07005983 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005984 // - in other sessions:
5985 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5986 // other effect: overwrites output buffer: input buffer == output buffer
5987 // Auxiliary effect:
5988 // accumulates in output buffer: input buffer != output buffer
5989 // Therefore: accumulate <=> input buffer != output buffer
5990 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5991 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5992 } else {
5993 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5994 }
5995 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5996 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5997 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5998 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5999
Eric Laurentde070132010-07-13 04:45:46 -07006000 LOGV("configure() %p thread %p buffer %p framecount %d",
6001 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
6002
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006004 uint32_t size = sizeof(int);
6005 status_t status = (*mEffectInterface)->command(mEffectInterface,
6006 EFFECT_CMD_CONFIGURE,
6007 sizeof(effect_config_t),
6008 &mConfig,
6009 &size,
6010 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006011 if (status == 0) {
6012 status = cmdStatus;
6013 }
6014
6015 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
6016 (1000 * mConfig.outputCfg.buffer.frameCount);
6017
6018 return status;
6019}
6020
6021status_t AudioFlinger::EffectModule::init()
6022{
6023 Mutex::Autolock _l(mLock);
6024 if (mEffectInterface == NULL) {
6025 return NO_INIT;
6026 }
6027 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006028 uint32_t size = sizeof(status_t);
6029 status_t status = (*mEffectInterface)->command(mEffectInterface,
6030 EFFECT_CMD_INIT,
6031 0,
6032 NULL,
6033 &size,
6034 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006035 if (status == 0) {
6036 status = cmdStatus;
6037 }
6038 return status;
6039}
6040
6041status_t AudioFlinger::EffectModule::start_l()
6042{
6043 if (mEffectInterface == NULL) {
6044 return NO_INIT;
6045 }
6046 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006047 uint32_t size = sizeof(status_t);
6048 status_t status = (*mEffectInterface)->command(mEffectInterface,
6049 EFFECT_CMD_ENABLE,
6050 0,
6051 NULL,
6052 &size,
6053 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006054 if (status == 0) {
6055 status = cmdStatus;
6056 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006057 if (status == 0 &&
6058 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6059 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6060 sp<ThreadBase> thread = mThread.promote();
6061 if (thread != 0) {
6062 thread->stream()->add_audio_effect(thread->stream(), mEffectInterface);
6063 }
6064 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006065 return status;
6066}
6067
Eric Laurentec437d82011-07-26 20:54:46 -07006068status_t AudioFlinger::EffectModule::stop()
6069{
6070 Mutex::Autolock _l(mLock);
6071 return stop_l();
6072}
6073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074status_t AudioFlinger::EffectModule::stop_l()
6075{
6076 if (mEffectInterface == NULL) {
6077 return NO_INIT;
6078 }
6079 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006080 uint32_t size = sizeof(status_t);
6081 status_t status = (*mEffectInterface)->command(mEffectInterface,
6082 EFFECT_CMD_DISABLE,
6083 0,
6084 NULL,
6085 &size,
6086 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006087 if (status == 0) {
6088 status = cmdStatus;
6089 }
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006090 if (status == 0 &&
6091 ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC ||
6092 (mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC)) {
6093 sp<ThreadBase> thread = mThread.promote();
6094 if (thread != 0) {
6095 thread->stream()->remove_audio_effect(thread->stream(), mEffectInterface);
6096 }
6097 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006098 return status;
6099}
6100
Eric Laurent25f43952010-07-28 05:40:18 -07006101status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
6102 uint32_t cmdSize,
6103 void *pCmdData,
6104 uint32_t *replySize,
6105 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006106{
6107 Mutex::Autolock _l(mLock);
6108// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
6109
Eric Laurentec437d82011-07-26 20:54:46 -07006110 if (mState == DESTROYED || mEffectInterface == NULL) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006111 return NO_INIT;
6112 }
Eric Laurent25f43952010-07-28 05:40:18 -07006113 status_t status = (*mEffectInterface)->command(mEffectInterface,
6114 cmdCode,
6115 cmdSize,
6116 pCmdData,
6117 replySize,
6118 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006119 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07006120 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006121 for (size_t i = 1; i < mHandles.size(); i++) {
6122 sp<EffectHandle> h = mHandles[i].promote();
6123 if (h != 0) {
6124 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
6125 }
6126 }
6127 }
6128 return status;
6129}
6130
6131status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
6132{
6133 Mutex::Autolock _l(mLock);
6134 LOGV("setEnabled %p enabled %d", this, enabled);
6135
6136 if (enabled != isEnabled()) {
6137 switch (mState) {
6138 // going from disabled to enabled
6139 case IDLE:
6140 mState = STARTING;
6141 break;
6142 case STOPPED:
6143 mState = RESTART;
6144 break;
6145 case STOPPING:
6146 mState = ACTIVE;
6147 break;
6148
6149 // going from enabled to disabled
6150 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006151 mState = STOPPED;
6152 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006153 case STARTING:
6154 mState = IDLE;
6155 break;
6156 case ACTIVE:
6157 mState = STOPPING;
6158 break;
Eric Laurentec437d82011-07-26 20:54:46 -07006159 case DESTROYED:
6160 return NO_ERROR; // simply ignore as we are being destroyed
Mathias Agopian65ab4712010-07-14 17:59:35 -07006161 }
6162 for (size_t i = 1; i < mHandles.size(); i++) {
6163 sp<EffectHandle> h = mHandles[i].promote();
6164 if (h != 0) {
6165 h->setEnabled(enabled);
6166 }
6167 }
6168 }
6169 return NO_ERROR;
6170}
6171
6172bool AudioFlinger::EffectModule::isEnabled()
6173{
6174 switch (mState) {
6175 case RESTART:
6176 case STARTING:
6177 case ACTIVE:
6178 return true;
6179 case IDLE:
6180 case STOPPING:
6181 case STOPPED:
Eric Laurentec437d82011-07-26 20:54:46 -07006182 case DESTROYED:
Mathias Agopian65ab4712010-07-14 17:59:35 -07006183 default:
6184 return false;
6185 }
6186}
6187
Eric Laurent8f45bd72010-08-31 13:50:07 -07006188bool AudioFlinger::EffectModule::isProcessEnabled()
6189{
6190 switch (mState) {
6191 case RESTART:
6192 case ACTIVE:
6193 case STOPPING:
6194 case STOPPED:
6195 return true;
6196 case IDLE:
6197 case STARTING:
Eric Laurentec437d82011-07-26 20:54:46 -07006198 case DESTROYED:
Eric Laurent8f45bd72010-08-31 13:50:07 -07006199 default:
6200 return false;
6201 }
6202}
6203
Mathias Agopian65ab4712010-07-14 17:59:35 -07006204status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
6205{
6206 Mutex::Autolock _l(mLock);
6207 status_t status = NO_ERROR;
6208
6209 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
6210 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07006211 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07006212 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
6213 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006214 status_t cmdStatus;
6215 uint32_t volume[2];
6216 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07006217 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006218 volume[0] = *left;
6219 volume[1] = *right;
6220 if (controller) {
6221 pVolume = volume;
6222 }
Eric Laurent25f43952010-07-28 05:40:18 -07006223 status = (*mEffectInterface)->command(mEffectInterface,
6224 EFFECT_CMD_SET_VOLUME,
6225 size,
6226 volume,
6227 &size,
6228 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006229 if (controller && status == NO_ERROR && size == sizeof(volume)) {
6230 *left = volume[0];
6231 *right = volume[1];
6232 }
6233 }
6234 return status;
6235}
6236
6237status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
6238{
6239 Mutex::Autolock _l(mLock);
6240 status_t status = NO_ERROR;
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006241 if (device && (mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
6242 // audio pre processing modules on RecordThread can receive both output and
6243 // input device indication in the same call
6244 uint32_t dev = device & AUDIO_DEVICE_OUT_ALL;
6245 if (dev) {
6246 status_t cmdStatus;
6247 uint32_t size = sizeof(status_t);
6248
6249 status = (*mEffectInterface)->command(mEffectInterface,
6250 EFFECT_CMD_SET_DEVICE,
6251 sizeof(uint32_t),
6252 &dev,
6253 &size,
6254 &cmdStatus);
6255 if (status == NO_ERROR) {
6256 status = cmdStatus;
6257 }
6258 }
6259 dev = device & AUDIO_DEVICE_IN_ALL;
6260 if (dev) {
6261 status_t cmdStatus;
6262 uint32_t size = sizeof(status_t);
6263
6264 status_t status2 = (*mEffectInterface)->command(mEffectInterface,
6265 EFFECT_CMD_SET_INPUT_DEVICE,
6266 sizeof(uint32_t),
6267 &dev,
6268 &size,
6269 &cmdStatus);
6270 if (status2 == NO_ERROR) {
6271 status2 = cmdStatus;
6272 }
6273 if (status == NO_ERROR) {
6274 status = status2;
6275 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006276 }
6277 }
6278 return status;
6279}
6280
6281status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
6282{
6283 Mutex::Autolock _l(mLock);
6284 status_t status = NO_ERROR;
6285 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006286 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07006287 uint32_t size = sizeof(status_t);
6288 status = (*mEffectInterface)->command(mEffectInterface,
6289 EFFECT_CMD_SET_AUDIO_MODE,
6290 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07006291 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07006292 &size,
6293 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006294 if (status == NO_ERROR) {
6295 status = cmdStatus;
6296 }
6297 }
6298 return status;
6299}
6300
Eric Laurent59255e42011-07-27 19:49:51 -07006301void AudioFlinger::EffectModule::setSuspended(bool suspended)
6302{
6303 Mutex::Autolock _l(mLock);
6304 mSuspended = suspended;
6305}
6306bool AudioFlinger::EffectModule::suspended()
6307{
6308 Mutex::Autolock _l(mLock);
6309 return mSuspended;
6310}
6311
Mathias Agopian65ab4712010-07-14 17:59:35 -07006312status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
6313{
6314 const size_t SIZE = 256;
6315 char buffer[SIZE];
6316 String8 result;
6317
6318 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
6319 result.append(buffer);
6320
6321 bool locked = tryLock(mLock);
6322 // failed to lock - AudioFlinger is probably deadlocked
6323 if (!locked) {
6324 result.append("\t\tCould not lock Fx mutex:\n");
6325 }
6326
6327 result.append("\t\tSession Status State Engine:\n");
6328 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
6329 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
6330 result.append(buffer);
6331
6332 result.append("\t\tDescriptor:\n");
6333 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6334 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
6335 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
6336 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
6337 result.append(buffer);
6338 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
6339 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
6340 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
6341 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
6342 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07006343 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006344 mDescriptor.apiVersion,
6345 mDescriptor.flags);
6346 result.append(buffer);
6347 snprintf(buffer, SIZE, "\t\t- name: %s\n",
6348 mDescriptor.name);
6349 result.append(buffer);
6350 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
6351 mDescriptor.implementor);
6352 result.append(buffer);
6353
6354 result.append("\t\t- Input configuration:\n");
6355 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6356 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6357 (uint32_t)mConfig.inputCfg.buffer.raw,
6358 mConfig.inputCfg.buffer.frameCount,
6359 mConfig.inputCfg.samplingRate,
6360 mConfig.inputCfg.channels,
6361 mConfig.inputCfg.format);
6362 result.append(buffer);
6363
6364 result.append("\t\t- Output configuration:\n");
6365 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
6366 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
6367 (uint32_t)mConfig.outputCfg.buffer.raw,
6368 mConfig.outputCfg.buffer.frameCount,
6369 mConfig.outputCfg.samplingRate,
6370 mConfig.outputCfg.channels,
6371 mConfig.outputCfg.format);
6372 result.append(buffer);
6373
6374 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
6375 result.append(buffer);
6376 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
6377 for (size_t i = 0; i < mHandles.size(); ++i) {
6378 sp<EffectHandle> handle = mHandles[i].promote();
6379 if (handle != 0) {
6380 handle->dump(buffer, SIZE);
6381 result.append(buffer);
6382 }
6383 }
6384
6385 result.append("\n");
6386
6387 write(fd, result.string(), result.length());
6388
6389 if (locked) {
6390 mLock.unlock();
6391 }
6392
6393 return NO_ERROR;
6394}
6395
6396// ----------------------------------------------------------------------------
6397// EffectHandle implementation
6398// ----------------------------------------------------------------------------
6399
6400#undef LOG_TAG
6401#define LOG_TAG "AudioFlinger::EffectHandle"
6402
6403AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
6404 const sp<AudioFlinger::Client>& client,
6405 const sp<IEffectClient>& effectClient,
6406 int32_t priority)
6407 : BnEffect(),
Eric Laurent59255e42011-07-27 19:49:51 -07006408 mEffect(effect), mEffectClient(effectClient), mClient(client),
6409 mPriority(priority), mHasControl(false), mEnabled(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006410{
6411 LOGV("constructor %p", this);
6412
6413 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
6414 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
6415 if (mCblkMemory != 0) {
6416 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
6417
6418 if (mCblk) {
6419 new(mCblk) effect_param_cblk_t();
6420 mBuffer = (uint8_t *)mCblk + bufOffset;
6421 }
6422 } else {
6423 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
6424 return;
6425 }
6426}
6427
6428AudioFlinger::EffectHandle::~EffectHandle()
6429{
6430 LOGV("Destructor %p", this);
6431 disconnect();
Eric Laurent59255e42011-07-27 19:49:51 -07006432 LOGV("Destructor DONE %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006433}
6434
6435status_t AudioFlinger::EffectHandle::enable()
6436{
Eric Laurent59255e42011-07-27 19:49:51 -07006437 LOGV("enable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438 if (!mHasControl) return INVALID_OPERATION;
6439 if (mEffect == 0) return DEAD_OBJECT;
6440
Eric Laurent59255e42011-07-27 19:49:51 -07006441 mEnabled = true;
6442
6443 sp<ThreadBase> thread = mEffect->thread().promote();
6444 if (thread != 0) {
6445 thread->checkSuspendOnEffectEnabled(mEffect, true, mEffect->sessionId());
6446 }
6447
6448 // checkSuspendOnEffectEnabled() can suspend this same effect when enabled
6449 if (mEffect->suspended()) {
6450 return NO_ERROR;
6451 }
6452
Mathias Agopian65ab4712010-07-14 17:59:35 -07006453 return mEffect->setEnabled(true);
6454}
6455
6456status_t AudioFlinger::EffectHandle::disable()
6457{
Eric Laurent59255e42011-07-27 19:49:51 -07006458 LOGV("disable %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006459 if (!mHasControl) return INVALID_OPERATION;
Eric Laurent59255e42011-07-27 19:49:51 -07006460 if (mEffect == 0) return DEAD_OBJECT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006461
Eric Laurent59255e42011-07-27 19:49:51 -07006462 mEnabled = false;
6463
6464 if (mEffect->suspended()) {
6465 return NO_ERROR;
6466 }
6467
6468 status_t status = mEffect->setEnabled(false);
6469
6470 sp<ThreadBase> thread = mEffect->thread().promote();
6471 if (thread != 0) {
6472 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6473 }
6474
6475 return status;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006476}
6477
6478void AudioFlinger::EffectHandle::disconnect()
6479{
Eric Laurent59255e42011-07-27 19:49:51 -07006480 LOGV("disconnect %p", this);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006481 if (mEffect == 0) {
6482 return;
6483 }
Eric Laurent59255e42011-07-27 19:49:51 -07006484
Mathias Agopian65ab4712010-07-14 17:59:35 -07006485 mEffect->disconnect(this);
Eric Laurent59255e42011-07-27 19:49:51 -07006486
6487 sp<ThreadBase> thread = mEffect->thread().promote();
6488 if (thread != 0) {
6489 thread->checkSuspendOnEffectEnabled(mEffect, false, mEffect->sessionId());
6490 }
6491
Mathias Agopian65ab4712010-07-14 17:59:35 -07006492 // release sp on module => module destructor can be called now
6493 mEffect.clear();
6494 if (mCblk) {
6495 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
6496 }
6497 mCblkMemory.clear(); // and free the shared memory
6498 if (mClient != 0) {
6499 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
6500 mClient.clear();
6501 }
6502}
6503
Eric Laurent25f43952010-07-28 05:40:18 -07006504status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
6505 uint32_t cmdSize,
6506 void *pCmdData,
6507 uint32_t *replySize,
6508 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006509{
Eric Laurent25f43952010-07-28 05:40:18 -07006510// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
6511// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07006512
6513 // only get parameter command is permitted for applications not controlling the effect
6514 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
6515 return INVALID_OPERATION;
6516 }
6517 if (mEffect == 0) return DEAD_OBJECT;
6518
6519 // handle commands that are not forwarded transparently to effect engine
6520 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
6521 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
6522 // no risk to block the whole media server process or mixer threads is we are stuck here
6523 Mutex::Autolock _l(mCblk->lock);
6524 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
6525 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
6526 mCblk->serverIndex = 0;
6527 mCblk->clientIndex = 0;
6528 return BAD_VALUE;
6529 }
6530 status_t status = NO_ERROR;
6531 while (mCblk->serverIndex < mCblk->clientIndex) {
6532 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07006533 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006534 int *p = (int *)(mBuffer + mCblk->serverIndex);
6535 int size = *p++;
6536 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
6537 LOGW("command(): invalid parameter block size");
6538 break;
6539 }
6540 effect_param_t *param = (effect_param_t *)p;
6541 if (param->psize == 0 || param->vsize == 0) {
6542 LOGW("command(): null parameter or value size");
6543 mCblk->serverIndex += size;
6544 continue;
6545 }
Eric Laurent25f43952010-07-28 05:40:18 -07006546 uint32_t psize = sizeof(effect_param_t) +
6547 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
6548 param->vsize;
6549 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
6550 psize,
6551 p,
6552 &rsize,
6553 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006554 // stop at first error encountered
6555 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006556 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006557 *(int *)pReplyData = reply;
6558 break;
6559 } else if (reply != NO_ERROR) {
6560 *(int *)pReplyData = reply;
6561 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006562 }
6563 mCblk->serverIndex += size;
6564 }
6565 mCblk->serverIndex = 0;
6566 mCblk->clientIndex = 0;
6567 return status;
6568 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006569 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006570 return enable();
6571 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006572 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006573 return disable();
6574 }
6575
6576 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6577}
6578
6579sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6580 return mCblkMemory;
6581}
6582
Eric Laurent59255e42011-07-27 19:49:51 -07006583void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal, bool enabled)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006584{
6585 LOGV("setControl %p control %d", this, hasControl);
6586
6587 mHasControl = hasControl;
Eric Laurent59255e42011-07-27 19:49:51 -07006588 mEnabled = enabled;
6589
Mathias Agopian65ab4712010-07-14 17:59:35 -07006590 if (signal && mEffectClient != 0) {
6591 mEffectClient->controlStatusChanged(hasControl);
6592 }
6593}
6594
Eric Laurent25f43952010-07-28 05:40:18 -07006595void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6596 uint32_t cmdSize,
6597 void *pCmdData,
6598 uint32_t replySize,
6599 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006600{
6601 if (mEffectClient != 0) {
6602 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6603 }
6604}
6605
6606
6607
6608void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6609{
6610 if (mEffectClient != 0) {
6611 mEffectClient->enableStatusChanged(enabled);
6612 }
6613}
6614
6615status_t AudioFlinger::EffectHandle::onTransact(
6616 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6617{
6618 return BnEffect::onTransact(code, data, reply, flags);
6619}
6620
6621
6622void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6623{
6624 bool locked = tryLock(mCblk->lock);
6625
6626 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6627 (mClient == NULL) ? getpid() : mClient->pid(),
6628 mPriority,
6629 mHasControl,
6630 !locked,
6631 mCblk->clientIndex,
6632 mCblk->serverIndex
6633 );
6634
6635 if (locked) {
6636 mCblk->lock.unlock();
6637 }
6638}
6639
6640#undef LOG_TAG
6641#define LOG_TAG "AudioFlinger::EffectChain"
6642
6643AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6644 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006645 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6646 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6647 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006648{
Dima Zavinfce7a472011-04-19 22:30:36 -07006649 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006650}
6651
6652AudioFlinger::EffectChain::~EffectChain()
6653{
6654 if (mOwnInBuffer) {
6655 delete mInBuffer;
6656 }
6657
6658}
6659
Eric Laurent59255e42011-07-27 19:49:51 -07006660// getEffectFromDesc_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07006661sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006662{
6663 sp<EffectModule> effect;
6664 size_t size = mEffects.size();
6665
6666 for (size_t i = 0; i < size; i++) {
6667 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6668 effect = mEffects[i];
6669 break;
6670 }
6671 }
6672 return effect;
6673}
6674
Eric Laurent59255e42011-07-27 19:49:51 -07006675// getEffectFromId_l() must be called with ThreadBase::mLock held
Eric Laurentcab11242010-07-15 12:50:15 -07006676sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006677{
6678 sp<EffectModule> effect;
6679 size_t size = mEffects.size();
6680
6681 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006682 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6683 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006684 effect = mEffects[i];
6685 break;
6686 }
6687 }
6688 return effect;
6689}
6690
Eric Laurent59255e42011-07-27 19:49:51 -07006691// getEffectFromType_l() must be called with ThreadBase::mLock held
6692sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromType_l(
6693 const effect_uuid_t *type)
6694{
6695 sp<EffectModule> effect;
6696 size_t size = mEffects.size();
6697
6698 for (size_t i = 0; i < size; i++) {
6699 if (memcmp(&mEffects[i]->desc().type, type, sizeof(effect_uuid_t)) == 0) {
6700 effect = mEffects[i];
6701 break;
6702 }
6703 }
6704 return effect;
6705}
6706
Mathias Agopian65ab4712010-07-14 17:59:35 -07006707// Must be called with EffectChain::mLock locked
6708void AudioFlinger::EffectChain::process_l()
6709{
Eric Laurentdac69112010-09-28 14:09:57 -07006710 sp<ThreadBase> thread = mThread.promote();
6711 if (thread == 0) {
6712 LOGW("process_l(): cannot promote mixer thread");
6713 return;
6714 }
Dima Zavinfce7a472011-04-19 22:30:36 -07006715 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6716 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07006717 bool tracksOnSession = false;
6718 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07006719 tracksOnSession = (trackCnt() != 0);
6720 }
6721
6722 // if no track is active, input buffer must be cleared here as the mixer process
6723 // will not do it
6724 if (tracksOnSession &&
6725 activeTrackCnt() == 0) {
Eric Laurent7c7f10b2011-06-17 21:29:58 -07006726 size_t numSamples = thread->frameCount() * thread->channelCount();
Eric Laurentb469b942011-05-09 12:09:06 -07006727 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07006728 }
6729
Mathias Agopian65ab4712010-07-14 17:59:35 -07006730 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006731 // do not process effect if no track is present in same audio session
6732 if (isGlobalSession || tracksOnSession) {
6733 for (size_t i = 0; i < size; i++) {
6734 mEffects[i]->process();
6735 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006736 }
6737 for (size_t i = 0; i < size; i++) {
6738 mEffects[i]->updateState();
6739 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006740}
6741
Eric Laurentcab11242010-07-15 12:50:15 -07006742// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006743status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006744{
6745 effect_descriptor_t desc = effect->desc();
6746 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6747
6748 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006749 effect->setChain(this);
6750 sp<ThreadBase> thread = mThread.promote();
6751 if (thread == 0) {
6752 return NO_INIT;
6753 }
6754 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006755
6756 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6757 // Auxiliary effects are inserted at the beginning of mEffects vector as
6758 // they are processed first and accumulated in chain input buffer
6759 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006760
Mathias Agopian65ab4712010-07-14 17:59:35 -07006761 // the input buffer for auxiliary effect contains mono samples in
6762 // 32 bit format. This is to avoid saturation in AudoMixer
6763 // accumulation stage. Saturation is done in EffectModule::process() before
6764 // calling the process in effect engine
6765 size_t numSamples = thread->frameCount();
6766 int32_t *buffer = new int32_t[numSamples];
6767 memset(buffer, 0, numSamples * sizeof(int32_t));
6768 effect->setInBuffer((int16_t *)buffer);
6769 // auxiliary effects output samples to chain input buffer for further processing
6770 // by insert effects
6771 effect->setOutBuffer(mInBuffer);
6772 } else {
6773 // Insert effects are inserted at the end of mEffects vector as they are processed
6774 // after track and auxiliary effects.
6775 // Insert effect order as a function of indicated preference:
6776 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6777 // another effect is present
6778 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6779 // last effect claiming first position
6780 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6781 // first effect claiming last position
6782 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6783 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6784 // already present
6785
6786 int size = (int)mEffects.size();
6787 int idx_insert = size;
6788 int idx_insert_first = -1;
6789 int idx_insert_last = -1;
6790
6791 for (int i = 0; i < size; i++) {
6792 effect_descriptor_t d = mEffects[i]->desc();
6793 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6794 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6795 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6796 // check invalid effect chaining combinations
6797 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6798 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006799 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006800 return INVALID_OPERATION;
6801 }
6802 // remember position of first insert effect and by default
6803 // select this as insert position for new effect
6804 if (idx_insert == size) {
6805 idx_insert = i;
6806 }
6807 // remember position of last insert effect claiming
6808 // first position
6809 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6810 idx_insert_first = i;
6811 }
6812 // remember position of first insert effect claiming
6813 // last position
6814 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6815 idx_insert_last == -1) {
6816 idx_insert_last = i;
6817 }
6818 }
6819 }
6820
6821 // modify idx_insert from first position if needed
6822 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6823 if (idx_insert_last != -1) {
6824 idx_insert = idx_insert_last;
6825 } else {
6826 idx_insert = size;
6827 }
6828 } else {
6829 if (idx_insert_first != -1) {
6830 idx_insert = idx_insert_first + 1;
6831 }
6832 }
6833
6834 // always read samples from chain input buffer
6835 effect->setInBuffer(mInBuffer);
6836
6837 // if last effect in the chain, output samples to chain
6838 // output buffer, otherwise to chain input buffer
6839 if (idx_insert == size) {
6840 if (idx_insert != 0) {
6841 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6842 mEffects[idx_insert-1]->configure();
6843 }
6844 effect->setOutBuffer(mOutBuffer);
6845 } else {
6846 effect->setOutBuffer(mInBuffer);
6847 }
6848 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006849
Eric Laurentcab11242010-07-15 12:50:15 -07006850 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006851 }
6852 effect->configure();
6853 return NO_ERROR;
6854}
6855
Eric Laurentcab11242010-07-15 12:50:15 -07006856// removeEffect_l() must be called with PlaybackThread::mLock held
6857size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006858{
6859 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006860 int size = (int)mEffects.size();
6861 int i;
6862 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6863
6864 for (i = 0; i < size; i++) {
6865 if (effect == mEffects[i]) {
Eric Laurentec437d82011-07-26 20:54:46 -07006866 // calling stop here will remove pre-processing effect from the audio HAL.
6867 // This is safe as we hold the EffectChain mutex which guarantees that we are not in
6868 // the middle of a read from audio HAL
6869 mEffects[i]->stop();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006870 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6871 delete[] effect->inBuffer();
6872 } else {
6873 if (i == size - 1 && i != 0) {
6874 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6875 mEffects[i - 1]->configure();
6876 }
6877 }
6878 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006879 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006880 break;
6881 }
6882 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006883
6884 return mEffects.size();
6885}
6886
Eric Laurentcab11242010-07-15 12:50:15 -07006887// setDevice_l() must be called with PlaybackThread::mLock held
6888void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006889{
6890 size_t size = mEffects.size();
6891 for (size_t i = 0; i < size; i++) {
6892 mEffects[i]->setDevice(device);
6893 }
6894}
6895
Eric Laurentcab11242010-07-15 12:50:15 -07006896// setMode_l() must be called with PlaybackThread::mLock held
6897void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006898{
6899 size_t size = mEffects.size();
6900 for (size_t i = 0; i < size; i++) {
6901 mEffects[i]->setMode(mode);
6902 }
6903}
6904
Eric Laurentcab11242010-07-15 12:50:15 -07006905// setVolume_l() must be called with PlaybackThread::mLock held
6906bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006907{
6908 uint32_t newLeft = *left;
6909 uint32_t newRight = *right;
6910 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006911 int ctrlIdx = -1;
6912 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006913
Eric Laurentcab11242010-07-15 12:50:15 -07006914 // first update volume controller
6915 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006916 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006917 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6918 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006919 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006920 break;
6921 }
6922 }
6923
6924 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006925 if (hasControl) {
6926 *left = mNewLeftVolume;
6927 *right = mNewRightVolume;
6928 }
6929 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006930 }
6931
6932 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006933 mLeftVolume = newLeft;
6934 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006935
6936 // second get volume update from volume controller
6937 if (ctrlIdx >= 0) {
6938 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006939 mNewLeftVolume = newLeft;
6940 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006941 }
6942 // then indicate volume to all other effects in chain.
6943 // Pass altered volume to effects before volume controller
6944 // and requested volume to effects after controller
6945 uint32_t lVol = newLeft;
6946 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006947
Mathias Agopian65ab4712010-07-14 17:59:35 -07006948 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006949 if ((int)i == ctrlIdx) continue;
6950 // this also works for ctrlIdx == -1 when there is no volume controller
6951 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006952 lVol = *left;
6953 rVol = *right;
6954 }
6955 mEffects[i]->setVolume(&lVol, &rVol, false);
6956 }
6957 *left = newLeft;
6958 *right = newRight;
6959
6960 return hasControl;
6961}
6962
Mathias Agopian65ab4712010-07-14 17:59:35 -07006963status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6964{
6965 const size_t SIZE = 256;
6966 char buffer[SIZE];
6967 String8 result;
6968
6969 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6970 result.append(buffer);
6971
6972 bool locked = tryLock(mLock);
6973 // failed to lock - AudioFlinger is probably deadlocked
6974 if (!locked) {
6975 result.append("\tCould not lock mutex:\n");
6976 }
6977
Eric Laurentcab11242010-07-15 12:50:15 -07006978 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6979 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006980 mEffects.size(),
6981 (uint32_t)mInBuffer,
6982 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006983 mActiveTrackCnt);
6984 result.append(buffer);
6985 write(fd, result.string(), result.size());
6986
6987 for (size_t i = 0; i < mEffects.size(); ++i) {
6988 sp<EffectModule> effect = mEffects[i];
6989 if (effect != 0) {
6990 effect->dump(fd, args);
6991 }
6992 }
6993
6994 if (locked) {
6995 mLock.unlock();
6996 }
6997
6998 return NO_ERROR;
6999}
7000
Eric Laurent59255e42011-07-27 19:49:51 -07007001// must be called with ThreadBase::mLock held
7002void AudioFlinger::EffectChain::setEffectSuspended_l(
7003 const effect_uuid_t *type, bool suspend)
7004{
7005 sp<SuspendedEffectDesc> desc;
7006 // use effect type UUID timelow as key as there is no real risk of identical
7007 // timeLow fields among effect type UUIDs.
7008 int index = mSuspendedEffects.indexOfKey(type->timeLow);
7009 if (suspend) {
7010 if (index >= 0) {
7011 desc = mSuspendedEffects.valueAt(index);
7012 } else {
7013 desc = new SuspendedEffectDesc();
7014 memcpy(&desc->mType, type, sizeof(effect_uuid_t));
7015 mSuspendedEffects.add(type->timeLow, desc);
7016 LOGV("setEffectSuspended_l() add entry for %08x", type->timeLow);
7017 }
7018 if (desc->mRefCount++ == 0) {
7019 sp<EffectModule> effect = getEffectIfEnabled(type);
7020 if (effect != 0) {
7021 desc->mEffect = effect;
7022 effect->setSuspended(true);
7023 effect->setEnabled(false);
7024 }
7025 }
7026 } else {
7027 if (index < 0) {
7028 return;
7029 }
7030 desc = mSuspendedEffects.valueAt(index);
7031 if (desc->mRefCount <= 0) {
7032 LOGW("setEffectSuspended_l() restore refcount should not be 0 %d", desc->mRefCount);
7033 desc->mRefCount = 1;
7034 }
7035 if (--desc->mRefCount == 0) {
7036 LOGV("setEffectSuspended_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7037 if (desc->mEffect != 0) {
7038 sp<EffectModule> effect = desc->mEffect.promote();
7039 if (effect != 0) {
7040 effect->setSuspended(false);
7041 sp<EffectHandle> handle = effect->controlHandle();
7042 if (handle != 0) {
7043 effect->setEnabled(handle->enabled());
7044 }
7045 }
7046 desc->mEffect.clear();
7047 }
7048 mSuspendedEffects.removeItemsAt(index);
7049 }
7050 }
7051}
7052
7053// must be called with ThreadBase::mLock held
7054void AudioFlinger::EffectChain::setEffectSuspendedAll_l(bool suspend)
7055{
7056 sp<SuspendedEffectDesc> desc;
7057
7058 int index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7059 if (suspend) {
7060 if (index >= 0) {
7061 desc = mSuspendedEffects.valueAt(index);
7062 } else {
7063 desc = new SuspendedEffectDesc();
7064 mSuspendedEffects.add((int)kKeyForSuspendAll, desc);
7065 LOGV("setEffectSuspendedAll_l() add entry for 0");
7066 }
7067 if (desc->mRefCount++ == 0) {
7068 Vector< sp<EffectModule> > effects = getSuspendEligibleEffects();
7069 for (size_t i = 0; i < effects.size(); i++) {
7070 setEffectSuspended_l(&effects[i]->desc().type, true);
7071 }
7072 }
7073 } else {
7074 if (index < 0) {
7075 return;
7076 }
7077 desc = mSuspendedEffects.valueAt(index);
7078 if (desc->mRefCount <= 0) {
7079 LOGW("setEffectSuspendedAll_l() restore refcount should not be 0 %d", desc->mRefCount);
7080 desc->mRefCount = 1;
7081 }
7082 if (--desc->mRefCount == 0) {
7083 Vector<const effect_uuid_t *> types;
7084 for (size_t i = 0; i < mSuspendedEffects.size(); i++) {
7085 if (mSuspendedEffects.keyAt(i) == (int)kKeyForSuspendAll) {
7086 continue;
7087 }
7088 types.add(&mSuspendedEffects.valueAt(i)->mType);
7089 }
7090 for (size_t i = 0; i < types.size(); i++) {
7091 setEffectSuspended_l(types[i], false);
7092 }
7093 LOGV("setEffectSuspendedAll_l() remove entry for %08x", mSuspendedEffects.keyAt(index));
7094 mSuspendedEffects.removeItem((int)kKeyForSuspendAll);
7095 }
7096 }
7097}
7098
7099Vector< sp<AudioFlinger::EffectModule> > AudioFlinger::EffectChain::getSuspendEligibleEffects()
7100{
7101 Vector< sp<EffectModule> > effects;
7102 for (size_t i = 0; i < mEffects.size(); i++) {
7103 effect_descriptor_t desc = mEffects[i]->desc();
7104 // auxiliary effects and vizualizer are never suspended on output mix
7105 if ((mSessionId == AUDIO_SESSION_OUTPUT_MIX) && (
7106 ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) ||
7107 (memcmp(&desc.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0))) {
7108 continue;
7109 }
7110 effects.add(mEffects[i]);
7111 }
7112 return effects;
7113}
7114
7115sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectIfEnabled(
7116 const effect_uuid_t *type)
7117{
7118 sp<EffectModule> effect;
7119 effect = getEffectFromType_l(type);
7120 if (effect != 0 && !effect->isEnabled()) {
7121 effect.clear();
7122 }
7123 return effect;
7124}
7125
7126void AudioFlinger::EffectChain::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
7127 bool enabled)
7128{
7129 int index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7130 if (enabled) {
7131 if (index < 0) {
7132 // if the effect is not suspend check if all effects are suspended
7133 index = mSuspendedEffects.indexOfKey((int)kKeyForSuspendAll);
7134 if (index < 0) {
7135 return;
7136 }
7137 setEffectSuspended_l(&effect->desc().type, enabled);
7138 index = mSuspendedEffects.indexOfKey(effect->desc().type.timeLow);
7139 }
7140 LOGV("checkSuspendOnEffectEnabled() enable suspending fx %08x",
7141 effect->desc().type.timeLow);
7142 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7143 // if effect is requested to suspended but was not yet enabled, supend it now.
7144 if (desc->mEffect == 0) {
7145 desc->mEffect = effect;
7146 effect->setEnabled(false);
7147 effect->setSuspended(true);
7148 }
7149 } else {
7150 if (index < 0) {
7151 return;
7152 }
7153 LOGV("checkSuspendOnEffectEnabled() disable restoring fx %08x",
7154 effect->desc().type.timeLow);
7155 sp<SuspendedEffectDesc> desc = mSuspendedEffects.valueAt(index);
7156 desc->mEffect.clear();
7157 effect->setSuspended(false);
7158 }
7159}
7160
Mathias Agopian65ab4712010-07-14 17:59:35 -07007161#undef LOG_TAG
7162#define LOG_TAG "AudioFlinger"
7163
7164// ----------------------------------------------------------------------------
7165
7166status_t AudioFlinger::onTransact(
7167 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
7168{
7169 return BnAudioFlinger::onTransact(code, data, reply, flags);
7170}
7171
Mathias Agopian65ab4712010-07-14 17:59:35 -07007172}; // namespace android