blob: f8066240d6e2dc4b4e9325e88bf44cd0a032b392 [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 Zavinfce7a472011-04-19 22:30:36 -070047#include <hardware/audio_hal.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>
53#include <media/EffectVisualizerApi.h>
54
55// ----------------------------------------------------------------------------
56// the sim build doesn't have gettid
57
58#ifndef HAVE_GETTID
59# define gettid getpid
60#endif
61
62// ----------------------------------------------------------------------------
63
Eric Laurentde070132010-07-13 04:45:46 -070064
Mathias Agopian65ab4712010-07-14 17:59:35 -070065namespace android {
66
67static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
68static const char* kHardwareLockedString = "Hardware lock is taken\n";
69
70//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
71static const float MAX_GAIN = 4096.0f;
72static const float MAX_GAIN_INT = 0x1000;
73
74// retry counts for buffer fill timeout
75// 50 * ~20msecs = 1 second
76static const int8_t kMaxTrackRetries = 50;
77static const int8_t kMaxTrackStartupRetries = 50;
78// allow less retry attempts on direct output thread.
79// direct outputs can be a scarce resource in audio hardware and should
80// be released as quickly as possible.
81static const int8_t kMaxTrackRetriesDirect = 2;
82
83static const int kDumpLockRetries = 50;
84static const int kDumpLockSleep = 20000;
85
86static const nsecs_t kWarningThrottle = seconds(5);
87
88
Mathias Agopian65ab4712010-07-14 17:59:35 -070089// ----------------------------------------------------------------------------
90
91static bool recordingAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070092 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
93 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
94 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
95 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -070096}
97
98static bool settingsAllowed() {
Mathias Agopian65ab4712010-07-14 17:59:35 -070099 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
100 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
101 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
102 return ok;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700103}
104
Gloria Wang9ee159b2011-02-24 14:51:45 -0800105// To collect the amplifier usage
106static void addBatteryData(uint32_t params) {
107 sp<IBinder> binder =
108 defaultServiceManager()->getService(String16("media.player"));
109 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder);
110 if (service.get() == NULL) {
111 LOGW("Cannot connect to the MediaPlayerService for battery tracking");
112 return;
113 }
114
115 service->addBatteryData(params);
116}
117
Dima Zavin799a70e2011-04-18 16:57:27 -0700118static int load_audio_interface(const char *if_name, const hw_module_t **mod,
119 audio_hw_device_t **dev)
120{
121 int rc;
122
123 rc = hw_get_module_by_class(AUDIO_HARDWARE_MODULE_ID, if_name, mod);
124 if (rc)
125 goto out;
126
127 rc = audio_hw_device_open(*mod, dev);
128 LOGE_IF(rc, "couldn't open audio hw device in %s.%s (%s)",
129 AUDIO_HARDWARE_MODULE_ID, if_name, strerror(-rc));
130 if (rc)
131 goto out;
132
133 return 0;
134
135out:
136 *mod = NULL;
137 *dev = NULL;
138 return rc;
139}
140
141static const char *audio_interfaces[] = {
142 "primary",
143 "a2dp",
144 "usb",
145};
146#define ARRAY_SIZE(x) (sizeof((x))/sizeof(((x)[0])))
147
Mathias Agopian65ab4712010-07-14 17:59:35 -0700148// ----------------------------------------------------------------------------
149
150AudioFlinger::AudioFlinger()
151 : BnAudioFlinger(),
Dima Zavin799a70e2011-04-18 16:57:27 -0700152 mPrimaryHardwareDev(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700153{
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700154}
155
156void AudioFlinger::onFirstRef()
157{
Dima Zavin799a70e2011-04-18 16:57:27 -0700158 int rc = 0;
Dima Zavinfce7a472011-04-19 22:30:36 -0700159
Eric Laurent93575202011-01-18 18:39:02 -0800160 Mutex::Autolock _l(mLock);
161
Dima Zavin799a70e2011-04-18 16:57:27 -0700162 /* TODO: move all this work into an Init() function */
Mathias Agopian65ab4712010-07-14 17:59:35 -0700163 mHardwareStatus = AUDIO_HW_IDLE;
164
Dima Zavin799a70e2011-04-18 16:57:27 -0700165 for (size_t i = 0; i < ARRAY_SIZE(audio_interfaces); i++) {
166 const hw_module_t *mod;
167 audio_hw_device_t *dev;
Dima Zavinfce7a472011-04-19 22:30:36 -0700168
Dima Zavin799a70e2011-04-18 16:57:27 -0700169 rc = load_audio_interface(audio_interfaces[i], &mod, &dev);
170 if (rc)
171 continue;
172
173 LOGI("Loaded %s audio interface from %s (%s)", audio_interfaces[i],
174 mod->name, mod->id);
175 mAudioHwDevs.push(dev);
176
177 if (!mPrimaryHardwareDev) {
178 mPrimaryHardwareDev = dev;
179 LOGI("Using '%s' (%s.%s) as the primary audio interface",
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700180 mod->name, mod->id, audio_interfaces[i]);
Dima Zavin799a70e2011-04-18 16:57:27 -0700181 }
182 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700183
184 mHardwareStatus = AUDIO_HW_INIT;
Dima Zavinfce7a472011-04-19 22:30:36 -0700185
Dima Zavin799a70e2011-04-18 16:57:27 -0700186 if (!mPrimaryHardwareDev || mAudioHwDevs.size() == 0) {
187 LOGE("Primary audio interface not found");
188 return;
189 }
190
191 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
192 audio_hw_device_t *dev = mAudioHwDevs[i];
193
194 mHardwareStatus = AUDIO_HW_INIT;
195 rc = dev->init_check(dev);
196 if (rc == 0) {
197 AutoMutex lock(mHardwareLock);
198
199 mMode = AUDIO_MODE_NORMAL;
200 mHardwareStatus = AUDIO_HW_SET_MODE;
201 dev->set_mode(dev, mMode);
202 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
203 dev->set_master_volume(dev, 1.0f);
204 mHardwareStatus = AUDIO_HW_IDLE;
205 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700206 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700207}
208
Dima Zavin5a61d2f2011-04-19 19:04:32 -0700209status_t AudioFlinger::initCheck() const
210{
211 Mutex::Autolock _l(mLock);
212 if (mPrimaryHardwareDev == NULL || mAudioHwDevs.size() == 0)
213 return NO_INIT;
214 return NO_ERROR;
215}
216
Mathias Agopian65ab4712010-07-14 17:59:35 -0700217AudioFlinger::~AudioFlinger()
218{
Dima Zavin799a70e2011-04-18 16:57:27 -0700219 int num_devs = mAudioHwDevs.size();
220
Mathias Agopian65ab4712010-07-14 17:59:35 -0700221 while (!mRecordThreads.isEmpty()) {
222 // closeInput() will remove first entry from mRecordThreads
223 closeInput(mRecordThreads.keyAt(0));
224 }
225 while (!mPlaybackThreads.isEmpty()) {
226 // closeOutput() will remove first entry from mPlaybackThreads
227 closeOutput(mPlaybackThreads.keyAt(0));
228 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700229
230 for (int i = 0; i < num_devs; i++) {
231 audio_hw_device_t *dev = mAudioHwDevs[i];
232 audio_hw_device_close(dev);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700233 }
Dima Zavin799a70e2011-04-18 16:57:27 -0700234 mAudioHwDevs.clear();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700235}
236
Dima Zavin799a70e2011-04-18 16:57:27 -0700237audio_hw_device_t* AudioFlinger::findSuitableHwDev_l(uint32_t devices)
238{
239 /* first matching HW device is returned */
240 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
241 audio_hw_device_t *dev = mAudioHwDevs[i];
242 if ((dev->get_supported_devices(dev) & devices) == devices)
243 return dev;
244 }
245 return NULL;
246}
Mathias Agopian65ab4712010-07-14 17:59:35 -0700247
248status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
249{
250 const size_t SIZE = 256;
251 char buffer[SIZE];
252 String8 result;
253
254 result.append("Clients:\n");
255 for (size_t i = 0; i < mClients.size(); ++i) {
256 wp<Client> wClient = mClients.valueAt(i);
257 if (wClient != 0) {
258 sp<Client> client = wClient.promote();
259 if (client != 0) {
260 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
261 result.append(buffer);
262 }
263 }
264 }
265 write(fd, result.string(), result.size());
266 return NO_ERROR;
267}
268
269
270status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
271{
272 const size_t SIZE = 256;
273 char buffer[SIZE];
274 String8 result;
275 int hardwareStatus = mHardwareStatus;
276
277 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
278 result.append(buffer);
279 write(fd, result.string(), result.size());
280 return NO_ERROR;
281}
282
283status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
284{
285 const size_t SIZE = 256;
286 char buffer[SIZE];
287 String8 result;
288 snprintf(buffer, SIZE, "Permission Denial: "
289 "can't dump AudioFlinger from pid=%d, uid=%d\n",
290 IPCThreadState::self()->getCallingPid(),
291 IPCThreadState::self()->getCallingUid());
292 result.append(buffer);
293 write(fd, result.string(), result.size());
294 return NO_ERROR;
295}
296
297static bool tryLock(Mutex& mutex)
298{
299 bool locked = false;
300 for (int i = 0; i < kDumpLockRetries; ++i) {
301 if (mutex.tryLock() == NO_ERROR) {
302 locked = true;
303 break;
304 }
305 usleep(kDumpLockSleep);
306 }
307 return locked;
308}
309
310status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
311{
312 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
313 dumpPermissionDenial(fd, args);
314 } else {
315 // get state of hardware lock
316 bool hardwareLocked = tryLock(mHardwareLock);
317 if (!hardwareLocked) {
318 String8 result(kHardwareLockedString);
319 write(fd, result.string(), result.size());
320 } else {
321 mHardwareLock.unlock();
322 }
323
324 bool locked = tryLock(mLock);
325
326 // failed to lock - AudioFlinger is probably deadlocked
327 if (!locked) {
328 String8 result(kDeadlockedString);
329 write(fd, result.string(), result.size());
330 }
331
332 dumpClients(fd, args);
333 dumpInternals(fd, args);
334
335 // dump playback threads
336 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
337 mPlaybackThreads.valueAt(i)->dump(fd, args);
338 }
339
340 // dump record threads
341 for (size_t i = 0; i < mRecordThreads.size(); i++) {
342 mRecordThreads.valueAt(i)->dump(fd, args);
343 }
344
Dima Zavin799a70e2011-04-18 16:57:27 -0700345 // dump all hardware devs
346 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
347 audio_hw_device_t *dev = mAudioHwDevs[i];
348 dev->dump(dev, fd);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700349 }
350 if (locked) mLock.unlock();
351 }
352 return NO_ERROR;
353}
354
355
356// IAudioFlinger interface
357
358
359sp<IAudioTrack> AudioFlinger::createTrack(
360 pid_t pid,
361 int streamType,
362 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700363 uint32_t format,
364 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365 int frameCount,
366 uint32_t flags,
367 const sp<IMemory>& sharedBuffer,
368 int output,
369 int *sessionId,
370 status_t *status)
371{
372 sp<PlaybackThread::Track> track;
373 sp<TrackHandle> trackHandle;
374 sp<Client> client;
375 wp<Client> wclient;
376 status_t lStatus;
377 int lSessionId;
378
Dima Zavinfce7a472011-04-19 22:30:36 -0700379 if (streamType >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380 LOGE("invalid stream type");
381 lStatus = BAD_VALUE;
382 goto Exit;
383 }
384
385 {
386 Mutex::Autolock _l(mLock);
387 PlaybackThread *thread = checkPlaybackThread_l(output);
Eric Laurent39e94f82010-07-28 01:32:47 -0700388 PlaybackThread *effectThread = NULL;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700389 if (thread == NULL) {
390 LOGE("unknown output thread");
391 lStatus = BAD_VALUE;
392 goto Exit;
393 }
394
395 wclient = mClients.valueFor(pid);
396
397 if (wclient != NULL) {
398 client = wclient.promote();
399 } else {
400 client = new Client(this, pid);
401 mClients.add(pid, client);
402 }
403
Mathias Agopian65ab4712010-07-14 17:59:35 -0700404 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
Dima Zavinfce7a472011-04-19 22:30:36 -0700405 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -0700406 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent39e94f82010-07-28 01:32:47 -0700407 sp<PlaybackThread> t = mPlaybackThreads.valueAt(i);
408 if (mPlaybackThreads.keyAt(i) != output) {
409 // prevent same audio session on different output threads
410 uint32_t sessions = t->hasAudioSession(*sessionId);
411 if (sessions & PlaybackThread::TRACK_SESSION) {
412 lStatus = BAD_VALUE;
413 goto Exit;
414 }
415 // check if an effect with same session ID is waiting for a track to be created
416 if (sessions & PlaybackThread::EFFECT_SESSION) {
417 effectThread = t.get();
418 }
Eric Laurentde070132010-07-13 04:45:46 -0700419 }
420 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700421 lSessionId = *sessionId;
422 } else {
Eric Laurentde070132010-07-13 04:45:46 -0700423 // if no audio session id is provided, create one here
Eric Laurentf5aafb22010-11-18 08:40:16 -0800424 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700425 if (sessionId != NULL) {
426 *sessionId = lSessionId;
427 }
428 }
429 LOGV("createTrack() lSessionId: %d", lSessionId);
430
431 track = thread->createTrack_l(client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700432 channelMask, frameCount, sharedBuffer, lSessionId, &lStatus);
Eric Laurent39e94f82010-07-28 01:32:47 -0700433
434 // move effect chain to this output thread if an effect on same session was waiting
435 // for a track to be created
436 if (lStatus == NO_ERROR && effectThread != NULL) {
437 Mutex::Autolock _dl(thread->mLock);
438 Mutex::Autolock _sl(effectThread->mLock);
439 moveEffectChain_l(lSessionId, effectThread, thread, true);
440 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700441 }
442 if (lStatus == NO_ERROR) {
443 trackHandle = new TrackHandle(track);
444 } else {
445 // remove local strong reference to Client before deleting the Track so that the Client
446 // destructor is called by the TrackBase destructor with mLock held
447 client.clear();
448 track.clear();
449 }
450
451Exit:
452 if(status) {
453 *status = lStatus;
454 }
455 return trackHandle;
456}
457
458uint32_t AudioFlinger::sampleRate(int output) const
459{
460 Mutex::Autolock _l(mLock);
461 PlaybackThread *thread = checkPlaybackThread_l(output);
462 if (thread == NULL) {
463 LOGW("sampleRate() unknown thread %d", output);
464 return 0;
465 }
466 return thread->sampleRate();
467}
468
469int AudioFlinger::channelCount(int output) const
470{
471 Mutex::Autolock _l(mLock);
472 PlaybackThread *thread = checkPlaybackThread_l(output);
473 if (thread == NULL) {
474 LOGW("channelCount() unknown thread %d", output);
475 return 0;
476 }
477 return thread->channelCount();
478}
479
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700480uint32_t AudioFlinger::format(int output) const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700481{
482 Mutex::Autolock _l(mLock);
483 PlaybackThread *thread = checkPlaybackThread_l(output);
484 if (thread == NULL) {
485 LOGW("format() unknown thread %d", output);
486 return 0;
487 }
488 return thread->format();
489}
490
491size_t AudioFlinger::frameCount(int output) const
492{
493 Mutex::Autolock _l(mLock);
494 PlaybackThread *thread = checkPlaybackThread_l(output);
495 if (thread == NULL) {
496 LOGW("frameCount() unknown thread %d", output);
497 return 0;
498 }
499 return thread->frameCount();
500}
501
502uint32_t AudioFlinger::latency(int output) const
503{
504 Mutex::Autolock _l(mLock);
505 PlaybackThread *thread = checkPlaybackThread_l(output);
506 if (thread == NULL) {
507 LOGW("latency() unknown thread %d", output);
508 return 0;
509 }
510 return thread->latency();
511}
512
513status_t AudioFlinger::setMasterVolume(float value)
514{
515 // check calling permissions
516 if (!settingsAllowed()) {
517 return PERMISSION_DENIED;
518 }
519
520 // when hw supports master volume, don't scale in sw mixer
Eric Laurent93575202011-01-18 18:39:02 -0800521 { // scope for the lock
522 AutoMutex lock(mHardwareLock);
523 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700524 if (mPrimaryHardwareDev->set_master_volume(mPrimaryHardwareDev, value) == NO_ERROR) {
Eric Laurent93575202011-01-18 18:39:02 -0800525 value = 1.0f;
526 }
527 mHardwareStatus = AUDIO_HW_IDLE;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700528 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700529
Eric Laurent93575202011-01-18 18:39:02 -0800530 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700531 mMasterVolume = value;
532 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
533 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
534
535 return NO_ERROR;
536}
537
538status_t AudioFlinger::setMode(int mode)
539{
540 status_t ret;
541
542 // check calling permissions
543 if (!settingsAllowed()) {
544 return PERMISSION_DENIED;
545 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700546 if ((mode < 0) || (mode >= AUDIO_MODE_CNT)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547 LOGW("Illegal value: setMode(%d)", mode);
548 return BAD_VALUE;
549 }
550
551 { // scope for the lock
552 AutoMutex lock(mHardwareLock);
553 mHardwareStatus = AUDIO_HW_SET_MODE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700554 ret = mPrimaryHardwareDev->set_mode(mPrimaryHardwareDev, mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700555 mHardwareStatus = AUDIO_HW_IDLE;
556 }
557
558 if (NO_ERROR == ret) {
559 Mutex::Autolock _l(mLock);
560 mMode = mode;
561 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
562 mPlaybackThreads.valueAt(i)->setMode(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700563 }
564
565 return ret;
566}
567
568status_t AudioFlinger::setMicMute(bool state)
569{
570 // check calling permissions
571 if (!settingsAllowed()) {
572 return PERMISSION_DENIED;
573 }
574
575 AutoMutex lock(mHardwareLock);
576 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700577 status_t ret = mPrimaryHardwareDev->set_mic_mute(mPrimaryHardwareDev, state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700578 mHardwareStatus = AUDIO_HW_IDLE;
579 return ret;
580}
581
582bool AudioFlinger::getMicMute() const
583{
Dima Zavinfce7a472011-04-19 22:30:36 -0700584 bool state = AUDIO_MODE_INVALID;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700585 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700586 mPrimaryHardwareDev->get_mic_mute(mPrimaryHardwareDev, &state);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700587 mHardwareStatus = AUDIO_HW_IDLE;
588 return state;
589}
590
591status_t AudioFlinger::setMasterMute(bool muted)
592{
593 // check calling permissions
594 if (!settingsAllowed()) {
595 return PERMISSION_DENIED;
596 }
597
Eric Laurent93575202011-01-18 18:39:02 -0800598 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700599 mMasterMute = muted;
600 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
601 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
602
603 return NO_ERROR;
604}
605
606float AudioFlinger::masterVolume() const
607{
608 return mMasterVolume;
609}
610
611bool AudioFlinger::masterMute() const
612{
613 return mMasterMute;
614}
615
616status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
617{
618 // check calling permissions
619 if (!settingsAllowed()) {
620 return PERMISSION_DENIED;
621 }
622
Dima Zavinfce7a472011-04-19 22:30:36 -0700623 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700624 return BAD_VALUE;
625 }
626
627 AutoMutex lock(mLock);
628 PlaybackThread *thread = NULL;
629 if (output) {
630 thread = checkPlaybackThread_l(output);
631 if (thread == NULL) {
632 return BAD_VALUE;
633 }
634 }
635
636 mStreamTypes[stream].volume = value;
637
638 if (thread == NULL) {
639 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
640 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
641 }
642 } else {
643 thread->setStreamVolume(stream, value);
644 }
645
646 return NO_ERROR;
647}
648
649status_t AudioFlinger::setStreamMute(int stream, bool muted)
650{
651 // check calling permissions
652 if (!settingsAllowed()) {
653 return PERMISSION_DENIED;
654 }
655
Dima Zavinfce7a472011-04-19 22:30:36 -0700656 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT ||
657 uint32_t(stream) == AUDIO_STREAM_ENFORCED_AUDIBLE) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700658 return BAD_VALUE;
659 }
660
Eric Laurent93575202011-01-18 18:39:02 -0800661 AutoMutex lock(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700662 mStreamTypes[stream].mute = muted;
663 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
664 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
665
666 return NO_ERROR;
667}
668
669float AudioFlinger::streamVolume(int stream, int output) const
670{
Dima Zavinfce7a472011-04-19 22:30:36 -0700671 if (stream < 0 || uint32_t(stream) >= AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700672 return 0.0f;
673 }
674
675 AutoMutex lock(mLock);
676 float volume;
677 if (output) {
678 PlaybackThread *thread = checkPlaybackThread_l(output);
679 if (thread == NULL) {
680 return 0.0f;
681 }
682 volume = thread->streamVolume(stream);
683 } else {
684 volume = mStreamTypes[stream].volume;
685 }
686
687 return volume;
688}
689
690bool AudioFlinger::streamMute(int stream) const
691{
Dima Zavinfce7a472011-04-19 22:30:36 -0700692 if (stream < 0 || stream >= (int)AUDIO_STREAM_CNT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -0700693 return true;
694 }
695
696 return mStreamTypes[stream].mute;
697}
698
Mathias Agopian65ab4712010-07-14 17:59:35 -0700699status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
700{
701 status_t result;
702
703 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
704 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
705 // check calling permissions
706 if (!settingsAllowed()) {
707 return PERMISSION_DENIED;
708 }
709
Mathias Agopian65ab4712010-07-14 17:59:35 -0700710 // ioHandle == 0 means the parameters are global to the audio hardware interface
711 if (ioHandle == 0) {
712 AutoMutex lock(mHardwareLock);
713 mHardwareStatus = AUDIO_SET_PARAMETER;
Dima Zavin799a70e2011-04-18 16:57:27 -0700714 status_t final_result = NO_ERROR;
715 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
716 audio_hw_device_t *dev = mAudioHwDevs[i];
717 result = dev->set_parameters(dev, keyValuePairs.string());
718 final_result = result ?: final_result;
719 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700720 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -0700721 return final_result;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700722 }
723
724 // hold a strong ref on thread in case closeOutput() or closeInput() is called
725 // and the thread is exited once the lock is released
726 sp<ThreadBase> thread;
727 {
728 Mutex::Autolock _l(mLock);
729 thread = checkPlaybackThread_l(ioHandle);
730 if (thread == NULL) {
731 thread = checkRecordThread_l(ioHandle);
732 }
733 }
734 if (thread != NULL) {
735 result = thread->setParameters(keyValuePairs);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700736 return result;
737 }
738 return BAD_VALUE;
739}
740
741String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
742{
743// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
744// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
745
746 if (ioHandle == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -0700747 String8 out_s8;
748
Dima Zavin799a70e2011-04-18 16:57:27 -0700749 for (size_t i = 0; i < mAudioHwDevs.size(); i++) {
750 audio_hw_device_t *dev = mAudioHwDevs[i];
751 char *s = dev->get_parameters(dev, keys.string());
752 out_s8 += String8(s);
753 free(s);
754 }
Dima Zavinfce7a472011-04-19 22:30:36 -0700755 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700756 }
757
758 Mutex::Autolock _l(mLock);
759
760 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
761 if (playbackThread != NULL) {
762 return playbackThread->getParameters(keys);
763 }
764 RecordThread *recordThread = checkRecordThread_l(ioHandle);
765 if (recordThread != NULL) {
766 return recordThread->getParameters(keys);
767 }
768 return String8("");
769}
770
771size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
772{
Dima Zavin799a70e2011-04-18 16:57:27 -0700773 return mPrimaryHardwareDev->get_input_buffer_size(mPrimaryHardwareDev, sampleRate, format, channelCount);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700774}
775
776unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
777{
778 if (ioHandle == 0) {
779 return 0;
780 }
781
782 Mutex::Autolock _l(mLock);
783
784 RecordThread *recordThread = checkRecordThread_l(ioHandle);
785 if (recordThread != NULL) {
786 return recordThread->getInputFramesLost();
787 }
788 return 0;
789}
790
791status_t AudioFlinger::setVoiceVolume(float value)
792{
793 // check calling permissions
794 if (!settingsAllowed()) {
795 return PERMISSION_DENIED;
796 }
797
798 AutoMutex lock(mHardwareLock);
799 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Dima Zavin799a70e2011-04-18 16:57:27 -0700800 status_t ret = mPrimaryHardwareDev->set_voice_volume(mPrimaryHardwareDev, value);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700801 mHardwareStatus = AUDIO_HW_IDLE;
802
803 return ret;
804}
805
806status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
807{
808 status_t status;
809
810 Mutex::Autolock _l(mLock);
811
812 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
813 if (playbackThread != NULL) {
814 return playbackThread->getRenderPosition(halFrames, dspFrames);
815 }
816
817 return BAD_VALUE;
818}
819
820void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
821{
822
823 Mutex::Autolock _l(mLock);
824
825 int pid = IPCThreadState::self()->getCallingPid();
826 if (mNotificationClients.indexOfKey(pid) < 0) {
827 sp<NotificationClient> notificationClient = new NotificationClient(this,
828 client,
829 pid);
830 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
831
832 mNotificationClients.add(pid, notificationClient);
833
834 sp<IBinder> binder = client->asBinder();
835 binder->linkToDeath(notificationClient);
836
837 // the config change is always sent from playback or record threads to avoid deadlock
838 // with AudioSystem::gLock
839 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
840 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
841 }
842
843 for (size_t i = 0; i < mRecordThreads.size(); i++) {
844 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
845 }
846 }
847}
848
849void AudioFlinger::removeNotificationClient(pid_t pid)
850{
851 Mutex::Autolock _l(mLock);
852
853 int index = mNotificationClients.indexOfKey(pid);
854 if (index >= 0) {
855 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
856 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700857 mNotificationClients.removeItem(pid);
858 }
859}
860
861// audioConfigChanged_l() must be called with AudioFlinger::mLock held
862void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
863{
864 size_t size = mNotificationClients.size();
865 for (size_t i = 0; i < size; i++) {
866 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
867 }
868}
869
870// removeClient_l() must be called with AudioFlinger::mLock held
871void AudioFlinger::removeClient_l(pid_t pid)
872{
873 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
874 mClients.removeItem(pid);
875}
876
877
878// ----------------------------------------------------------------------------
879
880AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
881 : Thread(false),
882 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
883 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
884{
885}
886
887AudioFlinger::ThreadBase::~ThreadBase()
888{
889 mParamCond.broadcast();
890 mNewParameters.clear();
891}
892
893void AudioFlinger::ThreadBase::exit()
894{
895 // keep a strong ref on ourself so that we wont get
896 // destroyed in the middle of requestExitAndWait()
897 sp <ThreadBase> strongMe = this;
898
899 LOGV("ThreadBase::exit");
900 {
901 AutoMutex lock(&mLock);
902 mExiting = true;
903 requestExit();
904 mWaitWorkCV.signal();
905 }
906 requestExitAndWait();
907}
908
909uint32_t AudioFlinger::ThreadBase::sampleRate() const
910{
911 return mSampleRate;
912}
913
914int AudioFlinger::ThreadBase::channelCount() const
915{
916 return (int)mChannelCount;
917}
918
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -0700919uint32_t AudioFlinger::ThreadBase::format() const
Mathias Agopian65ab4712010-07-14 17:59:35 -0700920{
921 return mFormat;
922}
923
924size_t AudioFlinger::ThreadBase::frameCount() const
925{
926 return mFrameCount;
927}
928
929status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
930{
931 status_t status;
932
933 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
934 Mutex::Autolock _l(mLock);
935
936 mNewParameters.add(keyValuePairs);
937 mWaitWorkCV.signal();
938 // wait condition with timeout in case the thread loop has exited
939 // before the request could be processed
940 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
941 status = mParamStatus;
942 mWaitWorkCV.signal();
943 } else {
944 status = TIMED_OUT;
945 }
946 return status;
947}
948
949void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
950{
951 Mutex::Autolock _l(mLock);
952 sendConfigEvent_l(event, param);
953}
954
955// sendConfigEvent_l() must be called with ThreadBase::mLock held
956void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
957{
958 ConfigEvent *configEvent = new ConfigEvent();
959 configEvent->mEvent = event;
960 configEvent->mParam = param;
961 mConfigEvents.add(configEvent);
962 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
963 mWaitWorkCV.signal();
964}
965
966void AudioFlinger::ThreadBase::processConfigEvents()
967{
968 mLock.lock();
969 while(!mConfigEvents.isEmpty()) {
970 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
971 ConfigEvent *configEvent = mConfigEvents[0];
972 mConfigEvents.removeAt(0);
973 // release mLock before locking AudioFlinger mLock: lock order is always
974 // AudioFlinger then ThreadBase to avoid cross deadlock
975 mLock.unlock();
976 mAudioFlinger->mLock.lock();
977 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
978 mAudioFlinger->mLock.unlock();
979 delete configEvent;
980 mLock.lock();
981 }
982 mLock.unlock();
983}
984
985status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
986{
987 const size_t SIZE = 256;
988 char buffer[SIZE];
989 String8 result;
990
991 bool locked = tryLock(mLock);
992 if (!locked) {
993 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
994 write(fd, buffer, strlen(buffer));
995 }
996
997 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
998 result.append(buffer);
999 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
1000 result.append(buffer);
1001 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
1002 result.append(buffer);
1003 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
1004 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001005 snprintf(buffer, SIZE, "Channel Mask: 0x%08x\n", mChannelMask);
1006 result.append(buffer);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
1008 result.append(buffer);
1009 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
1010 result.append(buffer);
1011
1012 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
1013 result.append(buffer);
1014 result.append(" Index Command");
1015 for (size_t i = 0; i < mNewParameters.size(); ++i) {
1016 snprintf(buffer, SIZE, "\n %02d ", i);
1017 result.append(buffer);
1018 result.append(mNewParameters[i]);
1019 }
1020
1021 snprintf(buffer, SIZE, "\n\nPending config events: \n");
1022 result.append(buffer);
1023 snprintf(buffer, SIZE, " Index event param\n");
1024 result.append(buffer);
1025 for (size_t i = 0; i < mConfigEvents.size(); i++) {
1026 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
1027 result.append(buffer);
1028 }
1029 result.append("\n");
1030
1031 write(fd, result.string(), result.size());
1032
1033 if (locked) {
1034 mLock.unlock();
1035 }
1036 return NO_ERROR;
1037}
1038
1039
1040// ----------------------------------------------------------------------------
1041
Dima Zavin799a70e2011-04-18 16:57:27 -07001042AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 : ThreadBase(audioFlinger, id),
1044 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
1045 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
1046 mDevice(device)
1047{
1048 readOutputParameters();
1049
1050 mMasterVolume = mAudioFlinger->masterVolume();
1051 mMasterMute = mAudioFlinger->masterMute();
1052
Dima Zavinfce7a472011-04-19 22:30:36 -07001053 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001054 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
1055 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
1056 }
1057}
1058
1059AudioFlinger::PlaybackThread::~PlaybackThread()
1060{
1061 delete [] mMixBuffer;
1062}
1063
1064status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
1065{
1066 dumpInternals(fd, args);
1067 dumpTracks(fd, args);
1068 dumpEffectChains(fd, args);
1069 return NO_ERROR;
1070}
1071
1072status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
1073{
1074 const size_t SIZE = 256;
1075 char buffer[SIZE];
1076 String8 result;
1077
1078 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
1079 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001080 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 -07001081 for (size_t i = 0; i < mTracks.size(); ++i) {
1082 sp<Track> track = mTracks[i];
1083 if (track != 0) {
1084 track->dump(buffer, SIZE);
1085 result.append(buffer);
1086 }
1087 }
1088
1089 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
1090 result.append(buffer);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001091 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 -07001092 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
1093 wp<Track> wTrack = mActiveTracks[i];
1094 if (wTrack != 0) {
1095 sp<Track> track = wTrack.promote();
1096 if (track != 0) {
1097 track->dump(buffer, SIZE);
1098 result.append(buffer);
1099 }
1100 }
1101 }
1102 write(fd, result.string(), result.size());
1103 return NO_ERROR;
1104}
1105
1106status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1107{
1108 const size_t SIZE = 256;
1109 char buffer[SIZE];
1110 String8 result;
1111
1112 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1113 write(fd, buffer, strlen(buffer));
1114
1115 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1116 sp<EffectChain> chain = mEffectChains[i];
1117 if (chain != 0) {
1118 chain->dump(fd, args);
1119 }
1120 }
1121 return NO_ERROR;
1122}
1123
1124status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
1125{
1126 const size_t SIZE = 256;
1127 char buffer[SIZE];
1128 String8 result;
1129
1130 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
1131 result.append(buffer);
1132 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1133 result.append(buffer);
1134 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1135 result.append(buffer);
1136 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1137 result.append(buffer);
1138 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1139 result.append(buffer);
1140 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1141 result.append(buffer);
1142 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1143 result.append(buffer);
1144 write(fd, result.string(), result.size());
1145
1146 dumpBase(fd, args);
1147
1148 return NO_ERROR;
1149}
1150
1151// Thread virtuals
1152status_t AudioFlinger::PlaybackThread::readyToRun()
1153{
1154 if (mSampleRate == 0) {
1155 LOGE("No working audio driver found.");
1156 return NO_INIT;
1157 }
1158 LOGI("AudioFlinger's thread %p ready to run", this);
1159 return NO_ERROR;
1160}
1161
1162void AudioFlinger::PlaybackThread::onFirstRef()
1163{
1164 const size_t SIZE = 256;
1165 char buffer[SIZE];
1166
1167 snprintf(buffer, SIZE, "Playback Thread %p", this);
1168
1169 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1170}
1171
1172// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1173sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1174 const sp<AudioFlinger::Client>& client,
1175 int streamType,
1176 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001177 uint32_t format,
1178 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07001179 int frameCount,
1180 const sp<IMemory>& sharedBuffer,
1181 int sessionId,
1182 status_t *status)
1183{
1184 sp<Track> track;
1185 status_t lStatus;
1186
1187 if (mType == DIRECT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001188 if ((format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_PCM) {
1189 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
1190 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelMask 0x%08x \""
1191 "for output %p with format %d",
1192 sampleRate, format, channelMask, mOutput, mFormat);
1193 lStatus = BAD_VALUE;
1194 goto Exit;
1195 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001196 }
1197 } else {
1198 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1199 if (sampleRate > mSampleRate*2) {
1200 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1201 lStatus = BAD_VALUE;
1202 goto Exit;
1203 }
1204 }
1205
1206 if (mOutput == 0) {
1207 LOGE("Audio driver not initialized.");
1208 lStatus = NO_INIT;
1209 goto Exit;
1210 }
1211
1212 { // scope for mLock
1213 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001214
1215 // all tracks in same audio session must share the same routing strategy otherwise
1216 // conflicts will happen when tracks are moved from one output to another by audio policy
1217 // manager
1218 uint32_t strategy =
Dima Zavinfce7a472011-04-19 22:30:36 -07001219 AudioSystem::getStrategyForStream((audio_stream_type_t)streamType);
Eric Laurentde070132010-07-13 04:45:46 -07001220 for (size_t i = 0; i < mTracks.size(); ++i) {
1221 sp<Track> t = mTracks[i];
1222 if (t != 0) {
1223 if (sessionId == t->sessionId() &&
Dima Zavinfce7a472011-04-19 22:30:36 -07001224 strategy != AudioSystem::getStrategyForStream((audio_stream_type_t)t->type())) {
Eric Laurentde070132010-07-13 04:45:46 -07001225 lStatus = BAD_VALUE;
1226 goto Exit;
1227 }
1228 }
1229 }
1230
Mathias Agopian65ab4712010-07-14 17:59:35 -07001231 track = new Track(this, client, streamType, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001232 channelMask, frameCount, sharedBuffer, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001233 if (track->getCblk() == NULL || track->name() < 0) {
1234 lStatus = NO_MEMORY;
1235 goto Exit;
1236 }
1237 mTracks.add(track);
1238
1239 sp<EffectChain> chain = getEffectChain_l(sessionId);
1240 if (chain != 0) {
1241 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1242 track->setMainBuffer(chain->inBuffer());
Dima Zavinfce7a472011-04-19 22:30:36 -07001243 chain->setStrategy(AudioSystem::getStrategyForStream((audio_stream_type_t)track->type()));
Eric Laurentb469b942011-05-09 12:09:06 -07001244 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001245 }
1246 }
1247 lStatus = NO_ERROR;
1248
1249Exit:
1250 if(status) {
1251 *status = lStatus;
1252 }
1253 return track;
1254}
1255
1256uint32_t AudioFlinger::PlaybackThread::latency() const
1257{
1258 if (mOutput) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001259 return mOutput->stream->get_latency(mOutput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 }
1261 else {
1262 return 0;
1263 }
1264}
1265
1266status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
1267{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001268 mMasterVolume = value;
1269 return NO_ERROR;
1270}
1271
1272status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
1273{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001274 mMasterMute = muted;
1275 return NO_ERROR;
1276}
1277
1278float AudioFlinger::PlaybackThread::masterVolume() const
1279{
1280 return mMasterVolume;
1281}
1282
1283bool AudioFlinger::PlaybackThread::masterMute() const
1284{
1285 return mMasterMute;
1286}
1287
1288status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
1289{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001290 mStreamTypes[stream].volume = value;
1291 return NO_ERROR;
1292}
1293
1294status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
1295{
Mathias Agopian65ab4712010-07-14 17:59:35 -07001296 mStreamTypes[stream].mute = muted;
1297 return NO_ERROR;
1298}
1299
1300float AudioFlinger::PlaybackThread::streamVolume(int stream) const
1301{
1302 return mStreamTypes[stream].volume;
1303}
1304
1305bool AudioFlinger::PlaybackThread::streamMute(int stream) const
1306{
1307 return mStreamTypes[stream].mute;
1308}
1309
Mathias Agopian65ab4712010-07-14 17:59:35 -07001310// addTrack_l() must be called with ThreadBase::mLock held
1311status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
1312{
1313 status_t status = ALREADY_EXISTS;
1314
1315 // set retry count for buffer fill
1316 track->mRetryCount = kMaxTrackStartupRetries;
1317 if (mActiveTracks.indexOf(track) < 0) {
1318 // the track is newly added, make sure it fills up all its
1319 // buffers before playing. This is to ensure the client will
1320 // effectively get the latency it requested.
1321 track->mFillingUpStatus = Track::FS_FILLING;
1322 track->mResetDone = false;
1323 mActiveTracks.add(track);
1324 if (track->mainBuffer() != mMixBuffer) {
1325 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1326 if (chain != 0) {
1327 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001328 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001329 }
1330 }
1331
1332 status = NO_ERROR;
1333 }
1334
1335 LOGV("mWaitWorkCV.broadcast");
1336 mWaitWorkCV.broadcast();
1337
1338 return status;
1339}
1340
1341// destroyTrack_l() must be called with ThreadBase::mLock held
1342void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
1343{
1344 track->mState = TrackBase::TERMINATED;
1345 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurentb469b942011-05-09 12:09:06 -07001346 removeTrack_l(track);
1347 }
1348}
1349
1350void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
1351{
1352 mTracks.remove(track);
1353 deleteTrackName_l(track->name());
1354 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1355 if (chain != 0) {
1356 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001357 }
1358}
1359
1360String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
1361{
Dima Zavinfce7a472011-04-19 22:30:36 -07001362 String8 out_s8;
1363 char *s;
1364
Dima Zavin799a70e2011-04-18 16:57:27 -07001365 s = mOutput->stream->common.get_parameters(&mOutput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07001366 out_s8 = String8(s);
1367 free(s);
1368 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001369}
1370
1371// destroyTrack_l() must be called with AudioFlinger::mLock held
1372void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
1373 AudioSystem::OutputDescriptor desc;
1374 void *param2 = 0;
1375
1376 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
1377
1378 switch (event) {
1379 case AudioSystem::OUTPUT_OPENED:
1380 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001381 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001382 desc.samplingRate = mSampleRate;
1383 desc.format = mFormat;
1384 desc.frameCount = mFrameCount;
1385 desc.latency = latency();
1386 param2 = &desc;
1387 break;
1388
1389 case AudioSystem::STREAM_CONFIG_CHANGED:
1390 param2 = &param;
1391 case AudioSystem::OUTPUT_CLOSED:
1392 default:
1393 break;
1394 }
1395 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
1396}
1397
1398void AudioFlinger::PlaybackThread::readOutputParameters()
1399{
Dima Zavin799a70e2011-04-18 16:57:27 -07001400 mSampleRate = mOutput->stream->common.get_sample_rate(&mOutput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001401 mChannelMask = mOutput->stream->common.get_channels(&mOutput->stream->common);
1402 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07001403 mFormat = mOutput->stream->common.get_format(&mOutput->stream->common);
1404 mFrameSize = (uint16_t)audio_stream_frame_size(&mOutput->stream->common);
1405 mFrameCount = mOutput->stream->common.get_buffer_size(&mOutput->stream->common) / mFrameSize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001406
1407 // FIXME - Current mixer implementation only supports stereo output: Always
1408 // Allocate a stereo buffer even if HW output is mono.
1409 if (mMixBuffer != NULL) delete[] mMixBuffer;
1410 mMixBuffer = new int16_t[mFrameCount * 2];
1411 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1412
Eric Laurentde070132010-07-13 04:45:46 -07001413 // force reconfiguration of effect chains and engines to take new buffer size and audio
1414 // parameters into account
1415 // Note that mLock is not held when readOutputParameters() is called from the constructor
1416 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
1417 // matter.
1418 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
1419 Vector< sp<EffectChain> > effectChains = mEffectChains;
1420 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001421 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(), this, this, false);
Eric Laurentde070132010-07-13 04:45:46 -07001422 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423}
1424
1425status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1426{
1427 if (halFrames == 0 || dspFrames == 0) {
1428 return BAD_VALUE;
1429 }
1430 if (mOutput == 0) {
1431 return INVALID_OPERATION;
1432 }
Dima Zavin799a70e2011-04-18 16:57:27 -07001433 *halFrames = mBytesWritten / audio_stream_frame_size(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001434
Dima Zavin799a70e2011-04-18 16:57:27 -07001435 return mOutput->stream->get_render_position(mOutput->stream, dspFrames);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436}
1437
Eric Laurent39e94f82010-07-28 01:32:47 -07001438uint32_t AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439{
1440 Mutex::Autolock _l(mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07001441 uint32_t result = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001442 if (getEffectChain_l(sessionId) != 0) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001443 result = EFFECT_SESSION;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001444 }
1445
1446 for (size_t i = 0; i < mTracks.size(); ++i) {
1447 sp<Track> track = mTracks[i];
Eric Laurentde070132010-07-13 04:45:46 -07001448 if (sessionId == track->sessionId() &&
1449 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Eric Laurent39e94f82010-07-28 01:32:47 -07001450 result |= TRACK_SESSION;
1451 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001452 }
1453 }
1454
Eric Laurent39e94f82010-07-28 01:32:47 -07001455 return result;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001456}
1457
Eric Laurentde070132010-07-13 04:45:46 -07001458uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(int sessionId)
1459{
Dima Zavinfce7a472011-04-19 22:30:36 -07001460 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
Eric Laurentde070132010-07-13 04:45:46 -07001461 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
Dima Zavinfce7a472011-04-19 22:30:36 -07001462 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1463 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001464 }
1465 for (size_t i = 0; i < mTracks.size(); i++) {
1466 sp<Track> track = mTracks[i];
1467 if (sessionId == track->sessionId() &&
1468 !(track->mCblk->flags & CBLK_INVALID_MSK)) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001469 return AudioSystem::getStrategyForStream((audio_stream_type_t) track->type());
Eric Laurentde070132010-07-13 04:45:46 -07001470 }
1471 }
Dima Zavinfce7a472011-04-19 22:30:36 -07001472 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurentde070132010-07-13 04:45:46 -07001473}
1474
Mathias Agopian65ab4712010-07-14 17:59:35 -07001475sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1476{
1477 Mutex::Autolock _l(mLock);
1478 return getEffectChain_l(sessionId);
1479}
1480
1481sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1482{
1483 sp<EffectChain> chain;
1484
1485 size_t size = mEffectChains.size();
1486 for (size_t i = 0; i < size; i++) {
1487 if (mEffectChains[i]->sessionId() == sessionId) {
1488 chain = mEffectChains[i];
1489 break;
1490 }
1491 }
1492 return chain;
1493}
1494
1495void AudioFlinger::PlaybackThread::setMode(uint32_t mode)
1496{
1497 Mutex::Autolock _l(mLock);
1498 size_t size = mEffectChains.size();
1499 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001500 mEffectChains[i]->setMode_l(mode);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001501 }
1502}
1503
1504// ----------------------------------------------------------------------------
1505
Dima Zavin799a70e2011-04-18 16:57:27 -07001506AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001507 : PlaybackThread(audioFlinger, output, id, device),
1508 mAudioMixer(0)
1509{
1510 mType = PlaybackThread::MIXER;
1511 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1512
1513 // FIXME - Current mixer implementation only supports stereo output
1514 if (mChannelCount == 1) {
1515 LOGE("Invalid audio hardware channel count");
1516 }
1517}
1518
1519AudioFlinger::MixerThread::~MixerThread()
1520{
1521 delete mAudioMixer;
1522}
1523
1524bool AudioFlinger::MixerThread::threadLoop()
1525{
1526 Vector< sp<Track> > tracksToRemove;
1527 uint32_t mixerStatus = MIXER_IDLE;
1528 nsecs_t standbyTime = systemTime();
1529 size_t mixBufferSize = mFrameCount * mFrameSize;
1530 // FIXME: Relaxed timing because of a certain device that can't meet latency
1531 // Should be reduced to 2x after the vendor fixes the driver issue
1532 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1533 nsecs_t lastWarning = 0;
1534 bool longStandbyExit = false;
1535 uint32_t activeSleepTime = activeSleepTimeUs();
1536 uint32_t idleSleepTime = idleSleepTimeUs();
1537 uint32_t sleepTime = idleSleepTime;
1538 Vector< sp<EffectChain> > effectChains;
1539
1540 while (!exitPending())
1541 {
1542 processConfigEvents();
1543
1544 mixerStatus = MIXER_IDLE;
1545 { // scope for mLock
1546
1547 Mutex::Autolock _l(mLock);
1548
1549 if (checkForNewParameters_l()) {
1550 mixBufferSize = mFrameCount * mFrameSize;
1551 // FIXME: Relaxed timing because of a certain device that can't meet latency
1552 // Should be reduced to 2x after the vendor fixes the driver issue
1553 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1554 activeSleepTime = activeSleepTimeUs();
1555 idleSleepTime = idleSleepTimeUs();
1556 }
1557
1558 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1559
1560 // put audio hardware into standby after short delay
1561 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1562 mSuspended) {
1563 if (!mStandby) {
1564 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
Dima Zavin799a70e2011-04-18 16:57:27 -07001565 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001566 mStandby = true;
1567 mBytesWritten = 0;
1568 }
1569
1570 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1571 // we're about to wait, flush the binder command buffer
1572 IPCThreadState::self()->flushCommands();
1573
1574 if (exitPending()) break;
1575
1576 // wait until we have something to do...
1577 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1578 mWaitWorkCV.wait(mLock);
1579 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1580
1581 if (mMasterMute == false) {
1582 char value[PROPERTY_VALUE_MAX];
1583 property_get("ro.audio.silent", value, "0");
1584 if (atoi(value)) {
1585 LOGD("Silence is golden");
1586 setMasterMute(true);
1587 }
1588 }
1589
1590 standbyTime = systemTime() + kStandbyTimeInNsecs;
1591 sleepTime = idleSleepTime;
1592 continue;
1593 }
1594 }
1595
1596 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
1597
1598 // prevent any changes in effect chain list and in each effect chain
1599 // during mixing and effect process as the audio buffers could be deleted
1600 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07001601 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001602 }
1603
1604 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
1605 // mix buffers...
1606 mAudioMixer->process();
1607 sleepTime = 0;
1608 standbyTime = systemTime() + kStandbyTimeInNsecs;
1609 //TODO: delay standby when effects have a tail
1610 } else {
1611 // If no tracks are ready, sleep once for the duration of an output
1612 // buffer size, then write 0s to the output
1613 if (sleepTime == 0) {
1614 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1615 sleepTime = activeSleepTime;
1616 } else {
1617 sleepTime = idleSleepTime;
1618 }
1619 } else if (mBytesWritten != 0 ||
1620 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
1621 memset (mMixBuffer, 0, mixBufferSize);
1622 sleepTime = 0;
1623 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
1624 }
1625 // TODO add standby time extension fct of effect tail
1626 }
1627
1628 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07001629 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001630 }
1631 // sleepTime == 0 means we must write to audio hardware
1632 if (sleepTime == 0) {
1633 for (size_t i = 0; i < effectChains.size(); i ++) {
1634 effectChains[i]->process_l();
1635 }
1636 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001637 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001638 mLastWriteTime = systemTime();
1639 mInWrite = true;
1640 mBytesWritten += mixBufferSize;
1641
Dima Zavin799a70e2011-04-18 16:57:27 -07001642 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001643 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
1644 mNumWrites++;
1645 mInWrite = false;
1646 nsecs_t now = systemTime();
1647 nsecs_t delta = now - mLastWriteTime;
1648 if (delta > maxPeriod) {
1649 mNumDelayedWrites++;
1650 if ((now - lastWarning) > kWarningThrottle) {
1651 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1652 ns2ms(delta), mNumDelayedWrites, this);
1653 lastWarning = now;
1654 }
1655 if (mStandby) {
1656 longStandbyExit = true;
1657 }
1658 }
1659 mStandby = false;
1660 } else {
1661 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07001662 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001663 usleep(sleepTime);
1664 }
1665
1666 // finally let go of all our tracks, without the lock held
1667 // since we can't guarantee the destructors won't acquire that
1668 // same lock.
1669 tracksToRemove.clear();
1670
1671 // Effect chains will be actually deleted here if they were removed from
1672 // mEffectChains list during mixing or effects processing
1673 effectChains.clear();
1674 }
1675
1676 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001677 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001678 }
1679
1680 LOGV("MixerThread %p exiting", this);
1681 return false;
1682}
1683
1684// prepareTracks_l() must be called with ThreadBase::mLock held
1685uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1686{
1687
1688 uint32_t mixerStatus = MIXER_IDLE;
1689 // find out which tracks need to be processed
1690 size_t count = activeTracks.size();
1691 size_t mixedTracks = 0;
1692 size_t tracksWithEffect = 0;
1693
1694 float masterVolume = mMasterVolume;
1695 bool masterMute = mMasterMute;
1696
Eric Laurent571d49c2010-08-11 05:20:11 -07001697 if (masterMute) {
1698 masterVolume = 0;
1699 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 // Delegate master volume control to effect in output mix effect chain if needed
Dima Zavinfce7a472011-04-19 22:30:36 -07001701 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001702 if (chain != 0) {
Eric Laurent571d49c2010-08-11 05:20:11 -07001703 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Eric Laurentcab11242010-07-15 12:50:15 -07001704 chain->setVolume_l(&v, &v);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001705 masterVolume = (float)((v + (1 << 23)) >> 24);
1706 chain.clear();
1707 }
1708
1709 for (size_t i=0 ; i<count ; i++) {
1710 sp<Track> t = activeTracks[i].promote();
1711 if (t == 0) continue;
1712
1713 Track* const track = t.get();
1714 audio_track_cblk_t* cblk = track->cblk();
1715
1716 // The first time a track is added we wait
1717 // for all its buffers to be filled before processing it
1718 mAudioMixer->setActiveTrack(track->name());
Eric Laurentaf59ce22010-10-05 14:41:42 -07001719 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07001720 !track->isPaused() && !track->isTerminated())
1721 {
1722 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
1723
1724 mixedTracks++;
1725
1726 // track->mainBuffer() != mMixBuffer means there is an effect chain
1727 // connected to the track
1728 chain.clear();
1729 if (track->mainBuffer() != mMixBuffer) {
1730 chain = getEffectChain_l(track->sessionId());
1731 // Delegate volume control to effect in track effect chain if needed
1732 if (chain != 0) {
1733 tracksWithEffect++;
1734 } else {
1735 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1736 track->name(), track->sessionId());
1737 }
1738 }
1739
1740
1741 int param = AudioMixer::VOLUME;
1742 if (track->mFillingUpStatus == Track::FS_FILLED) {
1743 // no ramp for the first volume setting
1744 track->mFillingUpStatus = Track::FS_ACTIVE;
1745 if (track->mState == TrackBase::RESUMING) {
1746 track->mState = TrackBase::ACTIVE;
1747 param = AudioMixer::RAMP_VOLUME;
1748 }
Eric Laurent243f5f92011-02-28 16:52:51 -08001749 mAudioMixer->setParameter(AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 } else if (cblk->server != 0) {
1751 // If the track is stopped before the first frame was mixed,
1752 // do not apply ramp
1753 param = AudioMixer::RAMP_VOLUME;
1754 }
1755
1756 // compute volume for this track
Eric Laurente0aed6d2010-09-10 17:44:44 -07001757 uint32_t vl, vr, va;
Eric Laurent8569f0d2010-07-29 23:43:43 -07001758 if (track->isMuted() || track->isPausing() ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 mStreamTypes[track->type()].mute) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001760 vl = vr = va = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001761 if (track->isPausing()) {
1762 track->setPaused();
1763 }
1764 } else {
Eric Laurente0aed6d2010-09-10 17:44:44 -07001765
Mathias Agopian65ab4712010-07-14 17:59:35 -07001766 // read original volumes with volume control
1767 float typeVolume = mStreamTypes[track->type()].volume;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001768 float v = masterVolume * typeVolume;
Eric Laurente0aed6d2010-09-10 17:44:44 -07001769 vl = (uint32_t)(v * cblk->volume[0]) << 12;
1770 vr = (uint32_t)(v * cblk->volume[1]) << 12;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771
Eric Laurente0aed6d2010-09-10 17:44:44 -07001772 va = (uint32_t)(v * cblk->sendLevel);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001773 }
Eric Laurente0aed6d2010-09-10 17:44:44 -07001774 // Delegate volume control to effect in track effect chain if needed
1775 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
1776 // Do not ramp volume if volume is controlled by effect
1777 param = AudioMixer::VOLUME;
1778 track->mHasVolumeController = true;
1779 } else {
1780 // force no volume ramp when volume controller was just disabled or removed
1781 // from effect chain to avoid volume spike
1782 if (track->mHasVolumeController) {
1783 param = AudioMixer::VOLUME;
1784 }
1785 track->mHasVolumeController = false;
1786 }
1787
1788 // Convert volumes from 8.24 to 4.12 format
1789 int16_t left, right, aux;
1790 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1791 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1792 left = int16_t(v_clamped);
1793 v_clamped = (vr + (1 << 11)) >> 12;
1794 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1795 right = int16_t(v_clamped);
1796
1797 if (va > MAX_GAIN_INT) va = MAX_GAIN_INT;
1798 aux = int16_t(va);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001799
Mathias Agopian65ab4712010-07-14 17:59:35 -07001800 // XXX: these things DON'T need to be done each time
1801 mAudioMixer->setBufferProvider(track);
1802 mAudioMixer->enable(AudioMixer::MIXING);
1803
1804 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1805 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1806 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
1807 mAudioMixer->setParameter(
1808 AudioMixer::TRACK,
1809 AudioMixer::FORMAT, (void *)track->format());
1810 mAudioMixer->setParameter(
1811 AudioMixer::TRACK,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07001812 AudioMixer::CHANNEL_MASK, (void *)track->channelMask());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001813 mAudioMixer->setParameter(
1814 AudioMixer::RESAMPLE,
1815 AudioMixer::SAMPLE_RATE,
1816 (void *)(cblk->sampleRate));
1817 mAudioMixer->setParameter(
1818 AudioMixer::TRACK,
1819 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1820 mAudioMixer->setParameter(
1821 AudioMixer::TRACK,
1822 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
1823
1824 // reset retry count
1825 track->mRetryCount = kMaxTrackRetries;
1826 mixerStatus = MIXER_TRACKS_READY;
1827 } else {
1828 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
1829 if (track->isStopped()) {
1830 track->reset();
1831 }
1832 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1833 // We have consumed all the buffers of this track.
1834 // Remove it from the list of active tracks.
1835 tracksToRemove->add(track);
1836 } else {
1837 // No buffers for this track. Give it a few chances to
1838 // fill a buffer, then remove it from active list.
1839 if (--(track->mRetryCount) <= 0) {
1840 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
1841 tracksToRemove->add(track);
Eric Laurent44d98482010-09-30 16:12:31 -07001842 // indicate to client process that the track was disabled because of underrun
Eric Laurent38ccae22011-03-28 18:37:07 -07001843 android_atomic_or(CBLK_DISABLED_ON, &cblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001844 } else if (mixerStatus != MIXER_TRACKS_READY) {
1845 mixerStatus = MIXER_TRACKS_ENABLED;
1846 }
1847 }
1848 mAudioMixer->disable(AudioMixer::MIXING);
1849 }
1850 }
1851
1852 // remove all the tracks that need to be...
1853 count = tracksToRemove->size();
1854 if (UNLIKELY(count)) {
1855 for (size_t i=0 ; i<count ; i++) {
1856 const sp<Track>& track = tracksToRemove->itemAt(i);
1857 mActiveTracks.remove(track);
1858 if (track->mainBuffer() != mMixBuffer) {
1859 chain = getEffectChain_l(track->sessionId());
1860 if (chain != 0) {
1861 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07001862 chain->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001863 }
1864 }
1865 if (track->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07001866 removeTrack_l(track);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001867 }
1868 }
1869 }
1870
1871 // mix buffer must be cleared if all tracks are connected to an
1872 // effect chain as in this case the mixer will not write to
1873 // mix buffer and track effects will accumulate into it
1874 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1875 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1876 }
1877
1878 return mixerStatus;
1879}
1880
1881void AudioFlinger::MixerThread::invalidateTracks(int streamType)
1882{
Eric Laurentde070132010-07-13 04:45:46 -07001883 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d",
1884 this, streamType, mTracks.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001885 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07001886
Mathias Agopian65ab4712010-07-14 17:59:35 -07001887 size_t size = mTracks.size();
1888 for (size_t i = 0; i < size; i++) {
1889 sp<Track> t = mTracks[i];
1890 if (t->type() == streamType) {
Eric Laurent38ccae22011-03-28 18:37:07 -07001891 android_atomic_or(CBLK_INVALID_ON, &t->mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001892 t->mCblk->cv.signal();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001893 }
1894 }
1895}
1896
1897
1898// getTrackName_l() must be called with ThreadBase::mLock held
1899int AudioFlinger::MixerThread::getTrackName_l()
1900{
1901 return mAudioMixer->getTrackName();
1902}
1903
1904// deleteTrackName_l() must be called with ThreadBase::mLock held
1905void AudioFlinger::MixerThread::deleteTrackName_l(int name)
1906{
1907 LOGV("remove track (%d) and delete from mixer", name);
1908 mAudioMixer->deleteTrackName(name);
1909}
1910
1911// checkForNewParameters_l() must be called with ThreadBase::mLock held
1912bool AudioFlinger::MixerThread::checkForNewParameters_l()
1913{
1914 bool reconfig = false;
1915
1916 while (!mNewParameters.isEmpty()) {
1917 status_t status = NO_ERROR;
1918 String8 keyValuePair = mNewParameters[0];
1919 AudioParameter param = AudioParameter(keyValuePair);
1920 int value;
1921
1922 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1923 reconfig = true;
1924 }
1925 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001926 if (value != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001927 status = BAD_VALUE;
1928 } else {
1929 reconfig = true;
1930 }
1931 }
1932 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07001933 if (value != AUDIO_CHANNEL_OUT_STEREO) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001934 status = BAD_VALUE;
1935 } else {
1936 reconfig = true;
1937 }
1938 }
1939 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1940 // do not accept frame count changes if tracks are open as the track buffer
1941 // size depends on frame count and correct behavior would not be garantied
1942 // if frame count is changed after track creation
1943 if (!mTracks.isEmpty()) {
1944 status = INVALID_OPERATION;
1945 } else {
1946 reconfig = true;
1947 }
1948 }
1949 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001950 // when changing the audio output device, call addBatteryData to notify
1951 // the change
Eric Laurentb469b942011-05-09 12:09:06 -07001952 if ((int)mDevice != value) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001953 uint32_t params = 0;
1954 // check whether speaker is on
Dima Zavinfce7a472011-04-19 22:30:36 -07001955 if (value & AUDIO_DEVICE_OUT_SPEAKER) {
Gloria Wang9ee159b2011-02-24 14:51:45 -08001956 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
1957 }
1958
1959 int deviceWithoutSpeaker
Dima Zavinfce7a472011-04-19 22:30:36 -07001960 = AUDIO_DEVICE_OUT_ALL & ~AUDIO_DEVICE_OUT_SPEAKER;
Gloria Wang9ee159b2011-02-24 14:51:45 -08001961 // check if any other device (except speaker) is on
1962 if (value & deviceWithoutSpeaker ) {
1963 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
1964 }
1965
1966 if (params != 0) {
1967 addBatteryData(params);
1968 }
1969 }
1970
Mathias Agopian65ab4712010-07-14 17:59:35 -07001971 // forward device change to effects that have requested to be
1972 // aware of attached audio device.
1973 mDevice = (uint32_t)value;
1974 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07001975 mEffectChains[i]->setDevice_l(mDevice);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001976 }
1977 }
1978
1979 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001980 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07001981 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001982 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07001983 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001984 mStandby = true;
1985 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07001986 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07001987 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001988 }
1989 if (status == NO_ERROR && reconfig) {
1990 delete mAudioMixer;
1991 readOutputParameters();
1992 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1993 for (size_t i = 0; i < mTracks.size() ; i++) {
1994 int name = getTrackName_l();
1995 if (name < 0) break;
1996 mTracks[i]->mName = name;
1997 // limit track sample rate to 2 x new output sample rate
1998 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1999 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
2000 }
2001 }
2002 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2003 }
2004 }
2005
2006 mNewParameters.removeAt(0);
2007
2008 mParamStatus = status;
2009 mParamCond.signal();
2010 mWaitWorkCV.wait(mLock);
2011 }
2012 return reconfig;
2013}
2014
2015status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
2016{
2017 const size_t SIZE = 256;
2018 char buffer[SIZE];
2019 String8 result;
2020
2021 PlaybackThread::dumpInternals(fd, args);
2022
2023 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
2024 result.append(buffer);
2025 write(fd, result.string(), result.size());
2026 return NO_ERROR;
2027}
2028
2029uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
2030{
Dima Zavin799a70e2011-04-18 16:57:27 -07002031 return (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002032}
2033
2034uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
2035{
Eric Laurent60e18242010-07-29 06:50:24 -07002036 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002037}
2038
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002039uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs()
2040{
2041 return (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2042}
2043
Mathias Agopian65ab4712010-07-14 17:59:35 -07002044// ----------------------------------------------------------------------------
Dima Zavin799a70e2011-04-18 16:57:27 -07002045AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002046 : PlaybackThread(audioFlinger, output, id, device)
2047{
2048 mType = PlaybackThread::DIRECT;
2049}
2050
2051AudioFlinger::DirectOutputThread::~DirectOutputThread()
2052{
2053}
2054
2055
2056static inline int16_t clamp16(int32_t sample)
2057{
2058 if ((sample>>15) ^ (sample>>31))
2059 sample = 0x7FFF ^ (sample>>31);
2060 return sample;
2061}
2062
2063static inline
2064int32_t mul(int16_t in, int16_t v)
2065{
2066#if defined(__arm__) && !defined(__thumb__)
2067 int32_t out;
2068 asm( "smulbb %[out], %[in], %[v] \n"
2069 : [out]"=r"(out)
2070 : [in]"%r"(in), [v]"r"(v)
2071 : );
2072 return out;
2073#else
2074 return in * int32_t(v);
2075#endif
2076}
2077
2078void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
2079{
2080 // Do not apply volume on compressed audio
Dima Zavinfce7a472011-04-19 22:30:36 -07002081 if (!audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002082 return;
2083 }
2084
2085 // convert to signed 16 bit before volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002086 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002087 size_t count = mFrameCount * mChannelCount;
2088 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
2089 int16_t *dst = mMixBuffer + count-1;
2090 while(count--) {
2091 *dst-- = (int16_t)(*src--^0x80) << 8;
2092 }
2093 }
2094
2095 size_t frameCount = mFrameCount;
2096 int16_t *out = mMixBuffer;
2097 if (ramp) {
2098 if (mChannelCount == 1) {
2099 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2100 int32_t vlInc = d / (int32_t)frameCount;
2101 int32_t vl = ((int32_t)mLeftVolShort << 16);
2102 do {
2103 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2104 out++;
2105 vl += vlInc;
2106 } while (--frameCount);
2107
2108 } else {
2109 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
2110 int32_t vlInc = d / (int32_t)frameCount;
2111 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
2112 int32_t vrInc = d / (int32_t)frameCount;
2113 int32_t vl = ((int32_t)mLeftVolShort << 16);
2114 int32_t vr = ((int32_t)mRightVolShort << 16);
2115 do {
2116 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2117 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2118 out += 2;
2119 vl += vlInc;
2120 vr += vrInc;
2121 } while (--frameCount);
2122 }
2123 } else {
2124 if (mChannelCount == 1) {
2125 do {
2126 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2127 out++;
2128 } while (--frameCount);
2129 } else {
2130 do {
2131 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2132 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2133 out += 2;
2134 } while (--frameCount);
2135 }
2136 }
2137
2138 // convert back to unsigned 8 bit after volume calculation
Dima Zavinfce7a472011-04-19 22:30:36 -07002139 if (mFormat == AUDIO_FORMAT_PCM_8_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002140 size_t count = mFrameCount * mChannelCount;
2141 int16_t *src = mMixBuffer;
2142 uint8_t *dst = (uint8_t *)mMixBuffer;
2143 while(count--) {
2144 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2145 }
2146 }
2147
2148 mLeftVolShort = leftVol;
2149 mRightVolShort = rightVol;
2150}
2151
2152bool AudioFlinger::DirectOutputThread::threadLoop()
2153{
2154 uint32_t mixerStatus = MIXER_IDLE;
2155 sp<Track> trackToRemove;
2156 sp<Track> activeTrack;
2157 nsecs_t standbyTime = systemTime();
2158 int8_t *curBuf;
2159 size_t mixBufferSize = mFrameCount*mFrameSize;
2160 uint32_t activeSleepTime = activeSleepTimeUs();
2161 uint32_t idleSleepTime = idleSleepTimeUs();
2162 uint32_t sleepTime = idleSleepTime;
2163 // use shorter standby delay as on normal output to release
2164 // hardware resources as soon as possible
2165 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
2166
Mathias Agopian65ab4712010-07-14 17:59:35 -07002167 while (!exitPending())
2168 {
2169 bool rampVolume;
2170 uint16_t leftVol;
2171 uint16_t rightVol;
2172 Vector< sp<EffectChain> > effectChains;
2173
2174 processConfigEvents();
2175
2176 mixerStatus = MIXER_IDLE;
2177
2178 { // scope for the mLock
2179
2180 Mutex::Autolock _l(mLock);
2181
2182 if (checkForNewParameters_l()) {
2183 mixBufferSize = mFrameCount*mFrameSize;
2184 activeSleepTime = activeSleepTimeUs();
2185 idleSleepTime = idleSleepTimeUs();
2186 standbyDelay = microseconds(activeSleepTime*2);
2187 }
2188
2189 // put audio hardware into standby after short delay
2190 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2191 mSuspended) {
2192 // wait until we have something to do...
2193 if (!mStandby) {
2194 LOGV("Audio hardware entering standby, mixer %p\n", this);
Dima Zavin799a70e2011-04-18 16:57:27 -07002195 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002196 mStandby = true;
2197 mBytesWritten = 0;
2198 }
2199
2200 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2201 // we're about to wait, flush the binder command buffer
2202 IPCThreadState::self()->flushCommands();
2203
2204 if (exitPending()) break;
2205
2206 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2207 mWaitWorkCV.wait(mLock);
2208 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2209
2210 if (mMasterMute == false) {
2211 char value[PROPERTY_VALUE_MAX];
2212 property_get("ro.audio.silent", value, "0");
2213 if (atoi(value)) {
2214 LOGD("Silence is golden");
2215 setMasterMute(true);
2216 }
2217 }
2218
2219 standbyTime = systemTime() + standbyDelay;
2220 sleepTime = idleSleepTime;
2221 continue;
2222 }
2223 }
2224
2225 effectChains = mEffectChains;
2226
2227 // find out which tracks need to be processed
2228 if (mActiveTracks.size() != 0) {
2229 sp<Track> t = mActiveTracks[0].promote();
2230 if (t == 0) continue;
2231
2232 Track* const track = t.get();
2233 audio_track_cblk_t* cblk = track->cblk();
2234
2235 // The first time a track is added we wait
2236 // for all its buffers to be filled before processing it
Eric Laurentaf59ce22010-10-05 14:41:42 -07002237 if (cblk->framesReady() && track->isReady() &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07002238 !track->isPaused() && !track->isTerminated())
2239 {
2240 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2241
2242 if (track->mFillingUpStatus == Track::FS_FILLED) {
2243 track->mFillingUpStatus = Track::FS_ACTIVE;
2244 mLeftVolFloat = mRightVolFloat = 0;
2245 mLeftVolShort = mRightVolShort = 0;
2246 if (track->mState == TrackBase::RESUMING) {
2247 track->mState = TrackBase::ACTIVE;
2248 rampVolume = true;
2249 }
2250 } else if (cblk->server != 0) {
2251 // If the track is stopped before the first frame was mixed,
2252 // do not apply ramp
2253 rampVolume = true;
2254 }
2255 // compute volume for this track
2256 float left, right;
2257 if (track->isMuted() || mMasterMute || track->isPausing() ||
2258 mStreamTypes[track->type()].mute) {
2259 left = right = 0;
2260 if (track->isPausing()) {
2261 track->setPaused();
2262 }
2263 } else {
2264 float typeVolume = mStreamTypes[track->type()].volume;
2265 float v = mMasterVolume * typeVolume;
2266 float v_clamped = v * cblk->volume[0];
2267 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2268 left = v_clamped/MAX_GAIN;
2269 v_clamped = v * cblk->volume[1];
2270 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2271 right = v_clamped/MAX_GAIN;
2272 }
2273
2274 if (left != mLeftVolFloat || right != mRightVolFloat) {
2275 mLeftVolFloat = left;
2276 mRightVolFloat = right;
2277
2278 // If audio HAL implements volume control,
2279 // force software volume to nominal value
Dima Zavin799a70e2011-04-18 16:57:27 -07002280 if (mOutput->stream->set_volume(mOutput->stream, left, right) == NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002281 left = 1.0f;
2282 right = 1.0f;
2283 }
2284
2285 // Convert volumes from float to 8.24
2286 uint32_t vl = (uint32_t)(left * (1 << 24));
2287 uint32_t vr = (uint32_t)(right * (1 << 24));
2288
2289 // Delegate volume control to effect in track effect chain if needed
2290 // only one effect chain can be present on DirectOutputThread, so if
2291 // there is one, the track is connected to it
2292 if (!effectChains.isEmpty()) {
Eric Laurente0aed6d2010-09-10 17:44:44 -07002293 // Do not ramp volume if volume is controlled by effect
Eric Laurentcab11242010-07-15 12:50:15 -07002294 if(effectChains[0]->setVolume_l(&vl, &vr)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002295 rampVolume = false;
2296 }
2297 }
2298
2299 // Convert volumes from 8.24 to 4.12 format
2300 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2301 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2302 leftVol = (uint16_t)v_clamped;
2303 v_clamped = (vr + (1 << 11)) >> 12;
2304 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2305 rightVol = (uint16_t)v_clamped;
2306 } else {
2307 leftVol = mLeftVolShort;
2308 rightVol = mRightVolShort;
2309 rampVolume = false;
2310 }
2311
2312 // reset retry count
2313 track->mRetryCount = kMaxTrackRetriesDirect;
2314 activeTrack = t;
2315 mixerStatus = MIXER_TRACKS_READY;
2316 } else {
2317 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2318 if (track->isStopped()) {
2319 track->reset();
2320 }
2321 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2322 // We have consumed all the buffers of this track.
2323 // Remove it from the list of active tracks.
2324 trackToRemove = track;
2325 } else {
2326 // No buffers for this track. Give it a few chances to
2327 // fill a buffer, then remove it from active list.
2328 if (--(track->mRetryCount) <= 0) {
2329 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2330 trackToRemove = track;
2331 } else {
2332 mixerStatus = MIXER_TRACKS_ENABLED;
2333 }
2334 }
2335 }
2336 }
2337
2338 // remove all the tracks that need to be...
2339 if (UNLIKELY(trackToRemove != 0)) {
2340 mActiveTracks.remove(trackToRemove);
2341 if (!effectChains.isEmpty()) {
Eric Laurentde070132010-07-13 04:45:46 -07002342 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(),
2343 trackToRemove->sessionId());
Eric Laurentb469b942011-05-09 12:09:06 -07002344 effectChains[0]->decActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002345 }
2346 if (trackToRemove->isTerminated()) {
Eric Laurentb469b942011-05-09 12:09:06 -07002347 removeTrack_l(trackToRemove);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002348 }
2349 }
2350
Eric Laurentde070132010-07-13 04:45:46 -07002351 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002352 }
2353
2354 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2355 AudioBufferProvider::Buffer buffer;
2356 size_t frameCount = mFrameCount;
2357 curBuf = (int8_t *)mMixBuffer;
2358 // output audio to hardware
2359 while (frameCount) {
2360 buffer.frameCount = frameCount;
2361 activeTrack->getNextBuffer(&buffer);
2362 if (UNLIKELY(buffer.raw == 0)) {
2363 memset(curBuf, 0, frameCount * mFrameSize);
2364 break;
2365 }
2366 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2367 frameCount -= buffer.frameCount;
2368 curBuf += buffer.frameCount * mFrameSize;
2369 activeTrack->releaseBuffer(&buffer);
2370 }
2371 sleepTime = 0;
2372 standbyTime = systemTime() + standbyDelay;
2373 } else {
2374 if (sleepTime == 0) {
2375 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2376 sleepTime = activeSleepTime;
2377 } else {
2378 sleepTime = idleSleepTime;
2379 }
Dima Zavinfce7a472011-04-19 22:30:36 -07002380 } else if (mBytesWritten != 0 && audio_is_linear_pcm(mFormat)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07002381 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
2382 sleepTime = 0;
2383 }
2384 }
2385
2386 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002387 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002388 }
2389 // sleepTime == 0 means we must write to audio hardware
2390 if (sleepTime == 0) {
2391 if (mixerStatus == MIXER_TRACKS_READY) {
2392 applyVolume(leftVol, rightVol, rampVolume);
2393 }
2394 for (size_t i = 0; i < effectChains.size(); i ++) {
2395 effectChains[i]->process_l();
2396 }
Eric Laurentde070132010-07-13 04:45:46 -07002397 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002398
2399 mLastWriteTime = systemTime();
2400 mInWrite = true;
2401 mBytesWritten += mixBufferSize;
Dima Zavin799a70e2011-04-18 16:57:27 -07002402 int bytesWritten = (int)mOutput->stream->write(mOutput->stream, mMixBuffer, mixBufferSize);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002403 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
2404 mNumWrites++;
2405 mInWrite = false;
2406 mStandby = false;
2407 } else {
Eric Laurentde070132010-07-13 04:45:46 -07002408 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002409 usleep(sleepTime);
2410 }
2411
2412 // finally let go of removed track, without the lock held
2413 // since we can't guarantee the destructors won't acquire that
2414 // same lock.
2415 trackToRemove.clear();
2416 activeTrack.clear();
2417
2418 // Effect chains will be actually deleted here if they were removed from
2419 // mEffectChains list during mixing or effects processing
2420 effectChains.clear();
2421 }
2422
2423 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002424 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002425 }
2426
2427 LOGV("DirectOutputThread %p exiting", this);
2428 return false;
2429}
2430
2431// getTrackName_l() must be called with ThreadBase::mLock held
2432int AudioFlinger::DirectOutputThread::getTrackName_l()
2433{
2434 return 0;
2435}
2436
2437// deleteTrackName_l() must be called with ThreadBase::mLock held
2438void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2439{
2440}
2441
2442// checkForNewParameters_l() must be called with ThreadBase::mLock held
2443bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2444{
2445 bool reconfig = false;
2446
2447 while (!mNewParameters.isEmpty()) {
2448 status_t status = NO_ERROR;
2449 String8 keyValuePair = mNewParameters[0];
2450 AudioParameter param = AudioParameter(keyValuePair);
2451 int value;
2452
2453 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2454 // do not accept frame count changes if tracks are open as the track buffer
2455 // size depends on frame count and correct behavior would not be garantied
2456 // if frame count is changed after track creation
2457 if (!mTracks.isEmpty()) {
2458 status = INVALID_OPERATION;
2459 } else {
2460 reconfig = true;
2461 }
2462 }
2463 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002464 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002465 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002466 if (!mStandby && status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002467 mOutput->stream->common.standby(&mOutput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002468 mStandby = true;
2469 mBytesWritten = 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07002470 status = mOutput->stream->common.set_parameters(&mOutput->stream->common,
Dima Zavinfce7a472011-04-19 22:30:36 -07002471 keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07002472 }
2473 if (status == NO_ERROR && reconfig) {
2474 readOutputParameters();
2475 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
2476 }
2477 }
2478
2479 mNewParameters.removeAt(0);
2480
2481 mParamStatus = status;
2482 mParamCond.signal();
2483 mWaitWorkCV.wait(mLock);
2484 }
2485 return reconfig;
2486}
2487
2488uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
2489{
2490 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002491 if (audio_is_linear_pcm(mFormat)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07002492 time = (uint32_t)(mOutput->stream->get_latency(mOutput->stream) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002493 } else {
2494 time = 10000;
2495 }
2496 return time;
2497}
2498
2499uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2500{
2501 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002502 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent60e18242010-07-29 06:50:24 -07002503 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002504 } else {
2505 time = 10000;
2506 }
2507 return time;
2508}
2509
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002510uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs()
2511{
2512 uint32_t time;
Dima Zavinfce7a472011-04-19 22:30:36 -07002513 if (audio_is_linear_pcm(mFormat)) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002514 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
2515 } else {
2516 time = 10000;
2517 }
2518 return time;
2519}
2520
2521
Mathias Agopian65ab4712010-07-14 17:59:35 -07002522// ----------------------------------------------------------------------------
2523
2524AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
2525 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
2526{
2527 mType = PlaybackThread::DUPLICATING;
2528 addOutputTrack(mainThread);
2529}
2530
2531AudioFlinger::DuplicatingThread::~DuplicatingThread()
2532{
2533 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2534 mOutputTracks[i]->destroy();
2535 }
2536 mOutputTracks.clear();
2537}
2538
2539bool AudioFlinger::DuplicatingThread::threadLoop()
2540{
2541 Vector< sp<Track> > tracksToRemove;
2542 uint32_t mixerStatus = MIXER_IDLE;
2543 nsecs_t standbyTime = systemTime();
2544 size_t mixBufferSize = mFrameCount*mFrameSize;
2545 SortedVector< sp<OutputTrack> > outputTracks;
2546 uint32_t writeFrames = 0;
2547 uint32_t activeSleepTime = activeSleepTimeUs();
2548 uint32_t idleSleepTime = idleSleepTimeUs();
2549 uint32_t sleepTime = idleSleepTime;
2550 Vector< sp<EffectChain> > effectChains;
2551
2552 while (!exitPending())
2553 {
2554 processConfigEvents();
2555
2556 mixerStatus = MIXER_IDLE;
2557 { // scope for the mLock
2558
2559 Mutex::Autolock _l(mLock);
2560
2561 if (checkForNewParameters_l()) {
2562 mixBufferSize = mFrameCount*mFrameSize;
2563 updateWaitTime();
2564 activeSleepTime = activeSleepTimeUs();
2565 idleSleepTime = idleSleepTimeUs();
2566 }
2567
2568 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2569
2570 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2571 outputTracks.add(mOutputTracks[i]);
2572 }
2573
2574 // put audio hardware into standby after short delay
2575 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2576 mSuspended) {
2577 if (!mStandby) {
2578 for (size_t i = 0; i < outputTracks.size(); i++) {
2579 outputTracks[i]->stop();
2580 }
2581 mStandby = true;
2582 mBytesWritten = 0;
2583 }
2584
2585 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2586 // we're about to wait, flush the binder command buffer
2587 IPCThreadState::self()->flushCommands();
2588 outputTracks.clear();
2589
2590 if (exitPending()) break;
2591
2592 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2593 mWaitWorkCV.wait(mLock);
2594 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2595 if (mMasterMute == false) {
2596 char value[PROPERTY_VALUE_MAX];
2597 property_get("ro.audio.silent", value, "0");
2598 if (atoi(value)) {
2599 LOGD("Silence is golden");
2600 setMasterMute(true);
2601 }
2602 }
2603
2604 standbyTime = systemTime() + kStandbyTimeInNsecs;
2605 sleepTime = idleSleepTime;
2606 continue;
2607 }
2608 }
2609
2610 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
2611
2612 // prevent any changes in effect chain list and in each effect chain
2613 // during mixing and effect process as the audio buffers could be deleted
2614 // or modified if an effect is created or deleted
Eric Laurentde070132010-07-13 04:45:46 -07002615 lockEffectChains_l(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002616 }
2617
2618 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
2619 // mix buffers...
2620 if (outputsReady(outputTracks)) {
2621 mAudioMixer->process();
2622 } else {
2623 memset(mMixBuffer, 0, mixBufferSize);
2624 }
2625 sleepTime = 0;
2626 writeFrames = mFrameCount;
2627 } else {
2628 if (sleepTime == 0) {
2629 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2630 sleepTime = activeSleepTime;
2631 } else {
2632 sleepTime = idleSleepTime;
2633 }
2634 } else if (mBytesWritten != 0) {
2635 // flush remaining overflow buffers in output tracks
2636 for (size_t i = 0; i < outputTracks.size(); i++) {
2637 if (outputTracks[i]->isActive()) {
2638 sleepTime = 0;
2639 writeFrames = 0;
2640 memset(mMixBuffer, 0, mixBufferSize);
2641 break;
2642 }
2643 }
2644 }
2645 }
2646
2647 if (mSuspended) {
Eric Laurent25cbe0e2010-08-18 18:13:17 -07002648 sleepTime = suspendSleepTimeUs();
Mathias Agopian65ab4712010-07-14 17:59:35 -07002649 }
2650 // sleepTime == 0 means we must write to audio hardware
2651 if (sleepTime == 0) {
2652 for (size_t i = 0; i < effectChains.size(); i ++) {
2653 effectChains[i]->process_l();
2654 }
2655 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002656 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002657
2658 standbyTime = systemTime() + kStandbyTimeInNsecs;
2659 for (size_t i = 0; i < outputTracks.size(); i++) {
2660 outputTracks[i]->write(mMixBuffer, writeFrames);
2661 }
2662 mStandby = false;
2663 mBytesWritten += mixBufferSize;
2664 } else {
2665 // enable changes in effect chain
Eric Laurentde070132010-07-13 04:45:46 -07002666 unlockEffectChains(effectChains);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002667 usleep(sleepTime);
2668 }
2669
2670 // finally let go of all our tracks, without the lock held
2671 // since we can't guarantee the destructors won't acquire that
2672 // same lock.
2673 tracksToRemove.clear();
2674 outputTracks.clear();
2675
2676 // Effect chains will be actually deleted here if they were removed from
2677 // mEffectChains list during mixing or effects processing
2678 effectChains.clear();
2679 }
2680
2681 return false;
2682}
2683
2684void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2685{
2686 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2687 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2688 this,
2689 mSampleRate,
2690 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002691 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002692 frameCount);
2693 if (outputTrack->cblk() != NULL) {
Dima Zavinfce7a472011-04-19 22:30:36 -07002694 thread->setStreamVolume(AUDIO_STREAM_CNT, 1.0f);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002695 mOutputTracks.add(outputTrack);
2696 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2697 updateWaitTime();
2698 }
2699}
2700
2701void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2702{
2703 Mutex::Autolock _l(mLock);
2704 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2705 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
2706 mOutputTracks[i]->destroy();
2707 mOutputTracks.removeAt(i);
2708 updateWaitTime();
2709 return;
2710 }
2711 }
2712 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2713}
2714
2715void AudioFlinger::DuplicatingThread::updateWaitTime()
2716{
2717 mWaitTimeMs = UINT_MAX;
2718 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2719 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2720 if (strong != NULL) {
2721 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2722 if (waitTimeMs < mWaitTimeMs) {
2723 mWaitTimeMs = waitTimeMs;
2724 }
2725 }
2726 }
2727}
2728
2729
2730bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2731{
2732 for (size_t i = 0; i < outputTracks.size(); i++) {
2733 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2734 if (thread == 0) {
2735 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2736 return false;
2737 }
2738 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2739 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2740 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2741 return false;
2742 }
2743 }
2744 return true;
2745}
2746
2747uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2748{
2749 return (mWaitTimeMs * 1000) / 2;
2750}
2751
2752// ----------------------------------------------------------------------------
2753
2754// TrackBase constructor must be called with AudioFlinger::mLock held
2755AudioFlinger::ThreadBase::TrackBase::TrackBase(
2756 const wp<ThreadBase>& thread,
2757 const sp<Client>& client,
2758 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002759 uint32_t format,
2760 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002761 int frameCount,
2762 uint32_t flags,
2763 const sp<IMemory>& sharedBuffer,
2764 int sessionId)
2765 : RefBase(),
2766 mThread(thread),
2767 mClient(client),
2768 mCblk(0),
2769 mFrameCount(0),
2770 mState(IDLE),
2771 mClientTid(-1),
2772 mFormat(format),
2773 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2774 mSessionId(sessionId)
2775{
2776 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2777
2778 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
2779 size_t size = sizeof(audio_track_cblk_t);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002780 uint8_t channelCount = popcount(channelMask);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002781 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2782 if (sharedBuffer == 0) {
2783 size += bufferSize;
2784 }
2785
2786 if (client != NULL) {
2787 mCblkMemory = client->heap()->allocate(size);
2788 if (mCblkMemory != 0) {
2789 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2790 if (mCblk) { // construct the shared structure in-place.
2791 new(mCblk) audio_track_cblk_t();
2792 // clear all buffers
2793 mCblk->frameCount = frameCount;
2794 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002795 mChannelCount = channelCount;
2796 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002797 if (sharedBuffer == 0) {
2798 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2799 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2800 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002801 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002802 mCblk->flags = CBLK_UNDERRUN_ON;
2803 } else {
2804 mBuffer = sharedBuffer->pointer();
2805 }
2806 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2807 }
2808 } else {
2809 LOGE("not enough memory for AudioTrack size=%u", size);
2810 client->heap()->dump("AudioTrack");
2811 return;
2812 }
2813 } else {
2814 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2815 if (mCblk) { // construct the shared structure in-place.
2816 new(mCblk) audio_track_cblk_t();
2817 // clear all buffers
2818 mCblk->frameCount = frameCount;
2819 mCblk->sampleRate = sampleRate;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002820 mChannelCount = channelCount;
2821 mChannelMask = channelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002822 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2823 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2824 // Force underrun condition to avoid false underrun callback until first data is
Eric Laurent44d98482010-09-30 16:12:31 -07002825 // written to buffer (other flags are cleared)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002826 mCblk->flags = CBLK_UNDERRUN_ON;
2827 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2828 }
2829 }
2830}
2831
2832AudioFlinger::ThreadBase::TrackBase::~TrackBase()
2833{
2834 if (mCblk) {
2835 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2836 if (mClient == NULL) {
2837 delete mCblk;
2838 }
2839 }
2840 mCblkMemory.clear(); // and free the shared memory
2841 if (mClient != NULL) {
2842 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2843 mClient.clear();
2844 }
2845}
2846
2847void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
2848{
2849 buffer->raw = 0;
2850 mFrameCount = buffer->frameCount;
2851 step();
2852 buffer->frameCount = 0;
2853}
2854
2855bool AudioFlinger::ThreadBase::TrackBase::step() {
2856 bool result;
2857 audio_track_cblk_t* cblk = this->cblk();
2858
2859 result = cblk->stepServer(mFrameCount);
2860 if (!result) {
2861 LOGV("stepServer failed acquiring cblk mutex");
2862 mFlags |= STEPSERVER_FAILED;
2863 }
2864 return result;
2865}
2866
2867void AudioFlinger::ThreadBase::TrackBase::reset() {
2868 audio_track_cblk_t* cblk = this->cblk();
2869
2870 cblk->user = 0;
2871 cblk->server = 0;
2872 cblk->userBase = 0;
2873 cblk->serverBase = 0;
2874 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
2875 LOGV("TrackBase::reset");
2876}
2877
2878sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
2879{
2880 return mCblkMemory;
2881}
2882
2883int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
2884 return (int)mCblk->sampleRate;
2885}
2886
2887int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002888 return (const int)mChannelCount;
2889}
2890
2891uint32_t AudioFlinger::ThreadBase::TrackBase::channelMask() const {
2892 return mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002893}
2894
2895void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
2896 audio_track_cblk_t* cblk = this->cblk();
2897 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2898 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
2899
2900 // Check validity of returned pointer in case the track control block would have been corrupted.
2901 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2902 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
2903 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 -07002904 server %d, serverBase %d, user %d, userBase %d",
Mathias Agopian65ab4712010-07-14 17:59:35 -07002905 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002906 cblk->server, cblk->serverBase, cblk->user, cblk->userBase);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002907 return 0;
2908 }
2909
2910 return bufferStart;
2911}
2912
2913// ----------------------------------------------------------------------------
2914
2915// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2916AudioFlinger::PlaybackThread::Track::Track(
2917 const wp<ThreadBase>& thread,
2918 const sp<Client>& client,
2919 int streamType,
2920 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002921 uint32_t format,
2922 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07002923 int frameCount,
2924 const sp<IMemory>& sharedBuffer,
2925 int sessionId)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002926 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, 0, sharedBuffer, sessionId),
Eric Laurent8f45bd72010-08-31 13:50:07 -07002927 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL),
2928 mAuxEffectId(0), mHasVolumeController(false)
Mathias Agopian65ab4712010-07-14 17:59:35 -07002929{
2930 if (mCblk != NULL) {
2931 sp<ThreadBase> baseThread = thread.promote();
2932 if (baseThread != 0) {
2933 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2934 mName = playbackThread->getTrackName_l();
2935 mMainBuffer = playbackThread->mixBuffer();
2936 }
2937 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2938 if (mName < 0) {
2939 LOGE("no more track names available");
2940 }
2941 mVolume[0] = 1.0f;
2942 mVolume[1] = 1.0f;
2943 mStreamType = streamType;
2944 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2945 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002946 mCblk->frameSize = audio_is_linear_pcm(format) ? mChannelCount * sizeof(int16_t) : sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002947 }
2948}
2949
2950AudioFlinger::PlaybackThread::Track::~Track()
2951{
2952 LOGV("PlaybackThread::Track destructor");
2953 sp<ThreadBase> thread = mThread.promote();
2954 if (thread != 0) {
2955 Mutex::Autolock _l(thread->mLock);
2956 mState = TERMINATED;
2957 }
2958}
2959
2960void AudioFlinger::PlaybackThread::Track::destroy()
2961{
2962 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2963 // by removing it from mTracks vector, so there is a risk that this Tracks's
2964 // desctructor is called. As the destructor needs to lock mLock,
2965 // we must acquire a strong reference on this Track before locking mLock
2966 // here so that the destructor is called only when exiting this function.
2967 // On the other hand, as long as Track::destroy() is only called by
2968 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2969 // this Track with its member mTrack.
2970 sp<Track> keep(this);
2971 { // scope for mLock
2972 sp<ThreadBase> thread = mThread.promote();
2973 if (thread != 0) {
2974 if (!isOutputTrack()) {
2975 if (mState == ACTIVE || mState == RESUMING) {
Eric Laurentde070132010-07-13 04:45:46 -07002976 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07002977 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07002978 mSessionId);
Gloria Wang9ee159b2011-02-24 14:51:45 -08002979
2980 // to track the speaker usage
2981 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07002982 }
2983 AudioSystem::releaseOutput(thread->id());
2984 }
2985 Mutex::Autolock _l(thread->mLock);
2986 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2987 playbackThread->destroyTrack_l(this);
2988 }
2989 }
2990}
2991
2992void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
2993{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002994 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 -07002995 mName - AudioMixer::TRACK0,
2996 (mClient == NULL) ? getpid() : mClient->pid(),
2997 mStreamType,
2998 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07002999 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003000 mSessionId,
3001 mFrameCount,
3002 mState,
3003 mMute,
3004 mFillingUpStatus,
3005 mCblk->sampleRate,
3006 mCblk->volume[0],
3007 mCblk->volume[1],
3008 mCblk->server,
3009 mCblk->user,
3010 (int)mMainBuffer,
3011 (int)mAuxBuffer);
3012}
3013
3014status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3015{
3016 audio_track_cblk_t* cblk = this->cblk();
3017 uint32_t framesReady;
3018 uint32_t framesReq = buffer->frameCount;
3019
3020 // Check if last stepServer failed, try to step now
3021 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3022 if (!step()) goto getNextBuffer_exit;
3023 LOGV("stepServer recovered");
3024 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3025 }
3026
3027 framesReady = cblk->framesReady();
3028
3029 if (LIKELY(framesReady)) {
3030 uint32_t s = cblk->server;
3031 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3032
3033 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
3034 if (framesReq > framesReady) {
3035 framesReq = framesReady;
3036 }
3037 if (s + framesReq > bufferEnd) {
3038 framesReq = bufferEnd - s;
3039 }
3040
3041 buffer->raw = getBuffer(s, framesReq);
3042 if (buffer->raw == 0) goto getNextBuffer_exit;
3043
3044 buffer->frameCount = framesReq;
3045 return NO_ERROR;
3046 }
3047
3048getNextBuffer_exit:
3049 buffer->raw = 0;
3050 buffer->frameCount = 0;
3051 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
3052 return NOT_ENOUGH_DATA;
3053}
3054
3055bool AudioFlinger::PlaybackThread::Track::isReady() const {
Eric Laurentaf59ce22010-10-05 14:41:42 -07003056 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) return true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003057
3058 if (mCblk->framesReady() >= mCblk->frameCount ||
3059 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
3060 mFillingUpStatus = FS_FILLED;
Eric Laurent38ccae22011-03-28 18:37:07 -07003061 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003062 return true;
3063 }
3064 return false;
3065}
3066
3067status_t AudioFlinger::PlaybackThread::Track::start()
3068{
3069 status_t status = NO_ERROR;
Eric Laurentf997cab2010-07-19 06:24:46 -07003070 LOGV("start(%d), calling thread %d session %d",
3071 mName, IPCThreadState::self()->getCallingPid(), mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003072 sp<ThreadBase> thread = mThread.promote();
3073 if (thread != 0) {
3074 Mutex::Autolock _l(thread->mLock);
3075 int state = mState;
3076 // here the track could be either new, or restarted
3077 // in both cases "unstop" the track
3078 if (mState == PAUSED) {
3079 mState = TrackBase::RESUMING;
3080 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
3081 } else {
3082 mState = TrackBase::ACTIVE;
3083 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
3084 }
3085
3086 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
3087 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003088 status = AudioSystem::startOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003089 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003090 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003091 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003092
3093 // to track the speaker usage
3094 if (status == NO_ERROR) {
3095 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
3096 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003097 }
3098 if (status == NO_ERROR) {
3099 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3100 playbackThread->addTrack_l(this);
3101 } else {
3102 mState = state;
3103 }
3104 } else {
3105 status = BAD_VALUE;
3106 }
3107 return status;
3108}
3109
3110void AudioFlinger::PlaybackThread::Track::stop()
3111{
3112 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3113 sp<ThreadBase> thread = mThread.promote();
3114 if (thread != 0) {
3115 Mutex::Autolock _l(thread->mLock);
3116 int state = mState;
3117 if (mState > STOPPED) {
3118 mState = STOPPED;
3119 // If the track is not active (PAUSED and buffers full), flush buffers
3120 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3121 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3122 reset();
3123 }
3124 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
3125 }
3126 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
3127 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003128 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003129 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003130 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003131 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003132
3133 // to track the speaker usage
3134 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003135 }
3136 }
3137}
3138
3139void AudioFlinger::PlaybackThread::Track::pause()
3140{
3141 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
3142 sp<ThreadBase> thread = mThread.promote();
3143 if (thread != 0) {
3144 Mutex::Autolock _l(thread->mLock);
3145 if (mState == ACTIVE || mState == RESUMING) {
3146 mState = PAUSING;
3147 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
3148 if (!isOutputTrack()) {
3149 thread->mLock.unlock();
Eric Laurentde070132010-07-13 04:45:46 -07003150 AudioSystem::stopOutput(thread->id(),
Dima Zavinfce7a472011-04-19 22:30:36 -07003151 (audio_stream_type_t)mStreamType,
Eric Laurentde070132010-07-13 04:45:46 -07003152 mSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003153 thread->mLock.lock();
Gloria Wang9ee159b2011-02-24 14:51:45 -08003154
3155 // to track the speaker usage
3156 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003157 }
3158 }
3159 }
3160}
3161
3162void AudioFlinger::PlaybackThread::Track::flush()
3163{
3164 LOGV("flush(%d)", mName);
3165 sp<ThreadBase> thread = mThread.promote();
3166 if (thread != 0) {
3167 Mutex::Autolock _l(thread->mLock);
3168 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3169 return;
3170 }
3171 // No point remaining in PAUSED state after a flush => go to
3172 // STOPPED state
3173 mState = STOPPED;
3174
Eric Laurent38ccae22011-03-28 18:37:07 -07003175 // do not reset the track if it is still in the process of being stopped or paused.
3176 // this will be done by prepareTracks_l() when the track is stopped.
3177 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3178 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
3179 reset();
3180 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003181 }
3182}
3183
3184void AudioFlinger::PlaybackThread::Track::reset()
3185{
3186 // Do not reset twice to avoid discarding data written just after a flush and before
3187 // the audioflinger thread detects the track is stopped.
3188 if (!mResetDone) {
3189 TrackBase::reset();
3190 // Force underrun condition to avoid false underrun callback until first data is
3191 // written to buffer
Eric Laurent38ccae22011-03-28 18:37:07 -07003192 android_atomic_and(~CBLK_FORCEREADY_MSK, &mCblk->flags);
3193 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003194 mFillingUpStatus = FS_FILLING;
3195 mResetDone = true;
3196 }
3197}
3198
3199void AudioFlinger::PlaybackThread::Track::mute(bool muted)
3200{
3201 mMute = muted;
3202}
3203
3204void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
3205{
3206 mVolume[0] = left;
3207 mVolume[1] = right;
3208}
3209
3210status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3211{
3212 status_t status = DEAD_OBJECT;
3213 sp<ThreadBase> thread = mThread.promote();
3214 if (thread != 0) {
3215 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3216 status = playbackThread->attachAuxEffect(this, EffectId);
3217 }
3218 return status;
3219}
3220
3221void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3222{
3223 mAuxEffectId = EffectId;
3224 mAuxBuffer = buffer;
3225}
3226
3227// ----------------------------------------------------------------------------
3228
3229// RecordTrack constructor must be called with AudioFlinger::mLock held
3230AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3231 const wp<ThreadBase>& thread,
3232 const sp<Client>& client,
3233 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003234 uint32_t format,
3235 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003236 int frameCount,
3237 uint32_t flags,
3238 int sessionId)
3239 : TrackBase(thread, client, sampleRate, format,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003240 channelMask, frameCount, flags, 0, sessionId),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003241 mOverflow(false)
3242{
3243 if (mCblk != NULL) {
3244 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07003245 if (format == AUDIO_FORMAT_PCM_16_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003246 mCblk->frameSize = mChannelCount * sizeof(int16_t);
Dima Zavinfce7a472011-04-19 22:30:36 -07003247 } else if (format == AUDIO_FORMAT_PCM_8_BIT) {
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003248 mCblk->frameSize = mChannelCount * sizeof(int8_t);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003249 } else {
3250 mCblk->frameSize = sizeof(int8_t);
3251 }
3252 }
3253}
3254
3255AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
3256{
3257 sp<ThreadBase> thread = mThread.promote();
3258 if (thread != 0) {
3259 AudioSystem::releaseInput(thread->id());
3260 }
3261}
3262
3263status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3264{
3265 audio_track_cblk_t* cblk = this->cblk();
3266 uint32_t framesAvail;
3267 uint32_t framesReq = buffer->frameCount;
3268
3269 // Check if last stepServer failed, try to step now
3270 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3271 if (!step()) goto getNextBuffer_exit;
3272 LOGV("stepServer recovered");
3273 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3274 }
3275
3276 framesAvail = cblk->framesAvailable_l();
3277
3278 if (LIKELY(framesAvail)) {
3279 uint32_t s = cblk->server;
3280 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3281
3282 if (framesReq > framesAvail) {
3283 framesReq = framesAvail;
3284 }
3285 if (s + framesReq > bufferEnd) {
3286 framesReq = bufferEnd - s;
3287 }
3288
3289 buffer->raw = getBuffer(s, framesReq);
3290 if (buffer->raw == 0) goto getNextBuffer_exit;
3291
3292 buffer->frameCount = framesReq;
3293 return NO_ERROR;
3294 }
3295
3296getNextBuffer_exit:
3297 buffer->raw = 0;
3298 buffer->frameCount = 0;
3299 return NOT_ENOUGH_DATA;
3300}
3301
3302status_t AudioFlinger::RecordThread::RecordTrack::start()
3303{
3304 sp<ThreadBase> thread = mThread.promote();
3305 if (thread != 0) {
3306 RecordThread *recordThread = (RecordThread *)thread.get();
3307 return recordThread->start(this);
3308 } else {
3309 return BAD_VALUE;
3310 }
3311}
3312
3313void AudioFlinger::RecordThread::RecordTrack::stop()
3314{
3315 sp<ThreadBase> thread = mThread.promote();
3316 if (thread != 0) {
3317 RecordThread *recordThread = (RecordThread *)thread.get();
3318 recordThread->stop(this);
Eric Laurent38ccae22011-03-28 18:37:07 -07003319 TrackBase::reset();
3320 // Force overerrun condition to avoid false overrun callback until first data is
3321 // read from buffer
3322 android_atomic_or(CBLK_UNDERRUN_ON, &mCblk->flags);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003323 }
3324}
3325
3326void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3327{
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003328 snprintf(buffer, size, " %05d %03u 0x%08x %05d %04u %01d %05u %08x %08x\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329 (mClient == NULL) ? getpid() : mClient->pid(),
3330 mFormat,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003331 mChannelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332 mSessionId,
3333 mFrameCount,
3334 mState,
3335 mCblk->sampleRate,
3336 mCblk->server,
3337 mCblk->user);
3338}
3339
3340
3341// ----------------------------------------------------------------------------
3342
3343AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3344 const wp<ThreadBase>& thread,
3345 DuplicatingThread *sourceThread,
3346 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003347 uint32_t format,
3348 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003349 int frameCount)
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003350 : Track(thread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, NULL, 0),
Mathias Agopian65ab4712010-07-14 17:59:35 -07003351 mActive(false), mSourceThread(sourceThread)
3352{
3353
3354 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
3355 if (mCblk != NULL) {
3356 mCblk->flags |= CBLK_DIRECTION_OUT;
3357 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3358 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3359 mOutBuffer.frameCount = 0;
3360 playbackThread->mTracks.add(this);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003361 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, " \
3362 "mCblk->frameCount %d, mCblk->sampleRate %d, mChannelMask 0x%08x mBufferEnd %p",
3363 mCblk, mBuffer, mCblk->buffers,
3364 mCblk->frameCount, mCblk->sampleRate, mChannelMask, mBufferEnd);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003365 } else {
3366 LOGW("Error creating output track on thread %p", playbackThread);
3367 }
3368}
3369
3370AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
3371{
3372 clearBufferQueue();
3373}
3374
3375status_t AudioFlinger::PlaybackThread::OutputTrack::start()
3376{
3377 status_t status = Track::start();
3378 if (status != NO_ERROR) {
3379 return status;
3380 }
3381
3382 mActive = true;
3383 mRetryCount = 127;
3384 return status;
3385}
3386
3387void AudioFlinger::PlaybackThread::OutputTrack::stop()
3388{
3389 Track::stop();
3390 clearBufferQueue();
3391 mOutBuffer.frameCount = 0;
3392 mActive = false;
3393}
3394
3395bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
3396{
3397 Buffer *pInBuffer;
3398 Buffer inBuffer;
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003399 uint32_t channelCount = mChannelCount;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003400 bool outputBufferFull = false;
3401 inBuffer.frameCount = frames;
3402 inBuffer.i16 = data;
3403
3404 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
3405
3406 if (!mActive && frames != 0) {
3407 start();
3408 sp<ThreadBase> thread = mThread.promote();
3409 if (thread != 0) {
3410 MixerThread *mixerThread = (MixerThread *)thread.get();
3411 if (mCblk->frameCount > frames){
3412 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3413 uint32_t startFrames = (mCblk->frameCount - frames);
3414 pInBuffer = new Buffer;
3415 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
3416 pInBuffer->frameCount = startFrames;
3417 pInBuffer->i16 = pInBuffer->mBuffer;
3418 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
3419 mBufferQueue.add(pInBuffer);
3420 } else {
3421 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3422 }
3423 }
3424 }
3425 }
3426
3427 while (waitTimeLeftMs) {
3428 // First write pending buffers, then new data
3429 if (mBufferQueue.size()) {
3430 pInBuffer = mBufferQueue.itemAt(0);
3431 } else {
3432 pInBuffer = &inBuffer;
3433 }
3434
3435 if (pInBuffer->frameCount == 0) {
3436 break;
3437 }
3438
3439 if (mOutBuffer.frameCount == 0) {
3440 mOutBuffer.frameCount = pInBuffer->frameCount;
3441 nsecs_t startTime = systemTime();
3442 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
3443 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
3444 outputBufferFull = true;
3445 break;
3446 }
3447 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
3448 if (waitTimeLeftMs >= waitTimeMs) {
3449 waitTimeLeftMs -= waitTimeMs;
3450 } else {
3451 waitTimeLeftMs = 0;
3452 }
3453 }
3454
3455 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
3456 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
3457 mCblk->stepUser(outFrames);
3458 pInBuffer->frameCount -= outFrames;
3459 pInBuffer->i16 += outFrames * channelCount;
3460 mOutBuffer.frameCount -= outFrames;
3461 mOutBuffer.i16 += outFrames * channelCount;
3462
3463 if (pInBuffer->frameCount == 0) {
3464 if (mBufferQueue.size()) {
3465 mBufferQueue.removeAt(0);
3466 delete [] pInBuffer->mBuffer;
3467 delete pInBuffer;
3468 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3469 } else {
3470 break;
3471 }
3472 }
3473 }
3474
3475 // If we could not write all frames, allocate a buffer and queue it for next time.
3476 if (inBuffer.frameCount) {
3477 sp<ThreadBase> thread = mThread.promote();
3478 if (thread != 0 && !thread->standby()) {
3479 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3480 pInBuffer = new Buffer;
3481 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
3482 pInBuffer->frameCount = inBuffer.frameCount;
3483 pInBuffer->i16 = pInBuffer->mBuffer;
3484 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
3485 mBufferQueue.add(pInBuffer);
3486 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3487 } else {
3488 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3489 }
3490 }
3491 }
3492
3493 // Calling write() with a 0 length buffer, means that no more data will be written:
3494 // If no more buffers are pending, fill output track buffer to make sure it is started
3495 // by output mixer.
3496 if (frames == 0 && mBufferQueue.size() == 0) {
3497 if (mCblk->user < mCblk->frameCount) {
3498 frames = mCblk->frameCount - mCblk->user;
3499 pInBuffer = new Buffer;
3500 pInBuffer->mBuffer = new int16_t[frames * channelCount];
3501 pInBuffer->frameCount = frames;
3502 pInBuffer->i16 = pInBuffer->mBuffer;
3503 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
3504 mBufferQueue.add(pInBuffer);
3505 } else if (mActive) {
3506 stop();
3507 }
3508 }
3509
3510 return outputBufferFull;
3511}
3512
3513status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
3514{
3515 int active;
3516 status_t result;
3517 audio_track_cblk_t* cblk = mCblk;
3518 uint32_t framesReq = buffer->frameCount;
3519
3520// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
3521 buffer->frameCount = 0;
3522
3523 uint32_t framesAvail = cblk->framesAvailable();
3524
3525
3526 if (framesAvail == 0) {
3527 Mutex::Autolock _l(cblk->lock);
3528 goto start_loop_here;
3529 while (framesAvail == 0) {
3530 active = mActive;
3531 if (UNLIKELY(!active)) {
3532 LOGV("Not active and NO_MORE_BUFFERS");
3533 return AudioTrack::NO_MORE_BUFFERS;
3534 }
3535 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3536 if (result != NO_ERROR) {
3537 return AudioTrack::NO_MORE_BUFFERS;
3538 }
3539 // read the server count again
3540 start_loop_here:
3541 framesAvail = cblk->framesAvailable_l();
3542 }
3543 }
3544
3545// if (framesAvail < framesReq) {
3546// return AudioTrack::NO_MORE_BUFFERS;
3547// }
3548
3549 if (framesReq > framesAvail) {
3550 framesReq = framesAvail;
3551 }
3552
3553 uint32_t u = cblk->user;
3554 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3555
3556 if (u + framesReq > bufferEnd) {
3557 framesReq = bufferEnd - u;
3558 }
3559
3560 buffer->frameCount = framesReq;
3561 buffer->raw = (void *)cblk->buffer(u);
3562 return NO_ERROR;
3563}
3564
3565
3566void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
3567{
3568 size_t size = mBufferQueue.size();
3569 Buffer *pBuffer;
3570
3571 for (size_t i = 0; i < size; i++) {
3572 pBuffer = mBufferQueue.itemAt(i);
3573 delete [] pBuffer->mBuffer;
3574 delete pBuffer;
3575 }
3576 mBufferQueue.clear();
3577}
3578
3579// ----------------------------------------------------------------------------
3580
3581AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3582 : RefBase(),
3583 mAudioFlinger(audioFlinger),
3584 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
3585 mPid(pid)
3586{
3587 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3588}
3589
3590// Client destructor must be called with AudioFlinger::mLock held
3591AudioFlinger::Client::~Client()
3592{
3593 mAudioFlinger->removeClient_l(mPid);
3594}
3595
3596const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3597{
3598 return mMemoryDealer;
3599}
3600
3601// ----------------------------------------------------------------------------
3602
3603AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3604 const sp<IAudioFlingerClient>& client,
3605 pid_t pid)
3606 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3607{
3608}
3609
3610AudioFlinger::NotificationClient::~NotificationClient()
3611{
3612 mClient.clear();
3613}
3614
3615void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3616{
3617 sp<NotificationClient> keep(this);
3618 {
3619 mAudioFlinger->removeNotificationClient(mPid);
3620 }
3621}
3622
3623// ----------------------------------------------------------------------------
3624
3625AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
3626 : BnAudioTrack(),
3627 mTrack(track)
3628{
3629}
3630
3631AudioFlinger::TrackHandle::~TrackHandle() {
3632 // just stop the track on deletion, associated resources
3633 // will be freed from the main thread once all pending buffers have
3634 // been played. Unless it's not in the active track list, in which
3635 // case we free everything now...
3636 mTrack->destroy();
3637}
3638
3639status_t AudioFlinger::TrackHandle::start() {
3640 return mTrack->start();
3641}
3642
3643void AudioFlinger::TrackHandle::stop() {
3644 mTrack->stop();
3645}
3646
3647void AudioFlinger::TrackHandle::flush() {
3648 mTrack->flush();
3649}
3650
3651void AudioFlinger::TrackHandle::mute(bool e) {
3652 mTrack->mute(e);
3653}
3654
3655void AudioFlinger::TrackHandle::pause() {
3656 mTrack->pause();
3657}
3658
3659void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3660 mTrack->setVolume(left, right);
3661}
3662
3663sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3664 return mTrack->getCblk();
3665}
3666
3667status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3668{
3669 return mTrack->attachAuxEffect(EffectId);
3670}
3671
3672status_t AudioFlinger::TrackHandle::onTransact(
3673 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3674{
3675 return BnAudioTrack::onTransact(code, data, reply, flags);
3676}
3677
3678// ----------------------------------------------------------------------------
3679
3680sp<IAudioRecord> AudioFlinger::openRecord(
3681 pid_t pid,
3682 int input,
3683 uint32_t sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003684 uint32_t format,
3685 uint32_t channelMask,
Mathias Agopian65ab4712010-07-14 17:59:35 -07003686 int frameCount,
3687 uint32_t flags,
3688 int *sessionId,
3689 status_t *status)
3690{
3691 sp<RecordThread::RecordTrack> recordTrack;
3692 sp<RecordHandle> recordHandle;
3693 sp<Client> client;
3694 wp<Client> wclient;
3695 status_t lStatus;
3696 RecordThread *thread;
3697 size_t inFrameCount;
3698 int lSessionId;
3699
3700 // check calling permissions
3701 if (!recordingAllowed()) {
3702 lStatus = PERMISSION_DENIED;
3703 goto Exit;
3704 }
3705
3706 // add client to list
3707 { // scope for mLock
3708 Mutex::Autolock _l(mLock);
3709 thread = checkRecordThread_l(input);
3710 if (thread == NULL) {
3711 lStatus = BAD_VALUE;
3712 goto Exit;
3713 }
3714
3715 wclient = mClients.valueFor(pid);
3716 if (wclient != NULL) {
3717 client = wclient.promote();
3718 } else {
3719 client = new Client(this, pid);
3720 mClients.add(pid, client);
3721 }
3722
3723 // If no audio session id is provided, create one here
Dima Zavinfce7a472011-04-19 22:30:36 -07003724 if (sessionId != NULL && *sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003725 lSessionId = *sessionId;
3726 } else {
Eric Laurentf5aafb22010-11-18 08:40:16 -08003727 lSessionId = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003728 if (sessionId != NULL) {
3729 *sessionId = lSessionId;
3730 }
3731 }
3732 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
3733 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07003734 format, channelMask, frameCount, flags, lSessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003735 }
3736 if (recordTrack->getCblk() == NULL) {
3737 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3738 // destructor is called by the TrackBase destructor with mLock held
3739 client.clear();
3740 recordTrack.clear();
3741 lStatus = NO_MEMORY;
3742 goto Exit;
3743 }
3744
3745 // return to handle to client
3746 recordHandle = new RecordHandle(recordTrack);
3747 lStatus = NO_ERROR;
3748
3749Exit:
3750 if (status) {
3751 *status = lStatus;
3752 }
3753 return recordHandle;
3754}
3755
3756// ----------------------------------------------------------------------------
3757
3758AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
3759 : BnAudioRecord(),
3760 mRecordTrack(recordTrack)
3761{
3762}
3763
3764AudioFlinger::RecordHandle::~RecordHandle() {
3765 stop();
3766}
3767
3768status_t AudioFlinger::RecordHandle::start() {
3769 LOGV("RecordHandle::start()");
3770 return mRecordTrack->start();
3771}
3772
3773void AudioFlinger::RecordHandle::stop() {
3774 LOGV("RecordHandle::stop()");
3775 mRecordTrack->stop();
3776}
3777
3778sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3779 return mRecordTrack->getCblk();
3780}
3781
3782status_t AudioFlinger::RecordHandle::onTransact(
3783 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3784{
3785 return BnAudioRecord::onTransact(code, data, reply, flags);
3786}
3787
3788// ----------------------------------------------------------------------------
3789
Dima Zavin799a70e2011-04-18 16:57:27 -07003790AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
Mathias Agopian65ab4712010-07-14 17:59:35 -07003791 ThreadBase(audioFlinger, id),
3792 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
3793{
Dima Zavinfce7a472011-04-19 22:30:36 -07003794 mReqChannelCount = popcount(channels);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003795 mReqSampleRate = sampleRate;
3796 readInputParameters();
3797}
3798
3799
3800AudioFlinger::RecordThread::~RecordThread()
3801{
3802 delete[] mRsmpInBuffer;
3803 if (mResampler != 0) {
3804 delete mResampler;
3805 delete[] mRsmpOutBuffer;
3806 }
3807}
3808
3809void AudioFlinger::RecordThread::onFirstRef()
3810{
3811 const size_t SIZE = 256;
3812 char buffer[SIZE];
3813
3814 snprintf(buffer, SIZE, "Record Thread %p", this);
3815
3816 run(buffer, PRIORITY_URGENT_AUDIO);
3817}
3818
3819bool AudioFlinger::RecordThread::threadLoop()
3820{
3821 AudioBufferProvider::Buffer buffer;
3822 sp<RecordTrack> activeTrack;
3823
Eric Laurent44d98482010-09-30 16:12:31 -07003824 nsecs_t lastWarning = 0;
3825
Mathias Agopian65ab4712010-07-14 17:59:35 -07003826 // start recording
3827 while (!exitPending()) {
3828
3829 processConfigEvents();
3830
3831 { // scope for mLock
3832 Mutex::Autolock _l(mLock);
3833 checkForNewParameters_l();
3834 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3835 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003836 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837 mStandby = true;
3838 }
3839
3840 if (exitPending()) break;
3841
3842 LOGV("RecordThread: loop stopping");
3843 // go to sleep
3844 mWaitWorkCV.wait(mLock);
3845 LOGV("RecordThread: loop starting");
3846 continue;
3847 }
3848 if (mActiveTrack != 0) {
3849 if (mActiveTrack->mState == TrackBase::PAUSING) {
3850 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003851 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852 mStandby = true;
3853 }
3854 mActiveTrack.clear();
3855 mStartStopCond.broadcast();
3856 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3857 if (mReqChannelCount != mActiveTrack->channelCount()) {
3858 mActiveTrack.clear();
3859 mStartStopCond.broadcast();
3860 } else if (mBytesRead != 0) {
3861 // record start succeeds only if first read from audio input
3862 // succeeds
3863 if (mBytesRead > 0) {
3864 mActiveTrack->mState = TrackBase::ACTIVE;
3865 } else {
3866 mActiveTrack.clear();
3867 }
3868 mStartStopCond.broadcast();
3869 }
3870 mStandby = false;
3871 }
3872 }
3873 }
3874
3875 if (mActiveTrack != 0) {
3876 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3877 mActiveTrack->mState != TrackBase::RESUMING) {
3878 usleep(5000);
3879 continue;
3880 }
3881 buffer.frameCount = mFrameCount;
3882 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3883 size_t framesOut = buffer.frameCount;
3884 if (mResampler == 0) {
3885 // no resampling
3886 while (framesOut) {
3887 size_t framesIn = mFrameCount - mRsmpInIndex;
3888 if (framesIn) {
3889 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3890 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3891 if (framesIn > framesOut)
3892 framesIn = framesOut;
3893 mRsmpInIndex += framesIn;
3894 framesOut -= framesIn;
3895 if ((int)mChannelCount == mReqChannelCount ||
Dima Zavinfce7a472011-04-19 22:30:36 -07003896 mFormat != AUDIO_FORMAT_PCM_16_BIT) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003897 memcpy(dst, src, framesIn * mFrameSize);
3898 } else {
3899 int16_t *src16 = (int16_t *)src;
3900 int16_t *dst16 = (int16_t *)dst;
3901 if (mChannelCount == 1) {
3902 while (framesIn--) {
3903 *dst16++ = *src16;
3904 *dst16++ = *src16++;
3905 }
3906 } else {
3907 while (framesIn--) {
3908 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3909 src16 += 2;
3910 }
3911 }
3912 }
3913 }
3914 if (framesOut && mFrameCount == mRsmpInIndex) {
3915 if (framesOut == mFrameCount &&
Dima Zavinfce7a472011-04-19 22:30:36 -07003916 ((int)mChannelCount == mReqChannelCount || mFormat != AUDIO_FORMAT_PCM_16_BIT)) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003917 mBytesRead = mInput->stream->read(mInput->stream, buffer.raw, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003918 framesOut = 0;
3919 } else {
Dima Zavin799a70e2011-04-18 16:57:27 -07003920 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921 mRsmpInIndex = 0;
3922 }
3923 if (mBytesRead < 0) {
3924 LOGE("Error reading audio input");
3925 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3926 // Force input into standby so that it tries to
3927 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07003928 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929 usleep(5000);
3930 }
3931 mRsmpInIndex = mFrameCount;
3932 framesOut = 0;
3933 buffer.frameCount = 0;
3934 }
3935 }
3936 }
3937 } else {
3938 // resampling
3939
3940 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3941 // alter output frame count as if we were expecting stereo samples
3942 if (mChannelCount == 1 && mReqChannelCount == 1) {
3943 framesOut >>= 1;
3944 }
3945 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3946 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3947 // are 32 bit aligned which should be always true.
3948 if (mChannelCount == 2 && mReqChannelCount == 1) {
3949 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3950 // the resampler always outputs stereo samples: do post stereo to mono conversion
3951 int16_t *src = (int16_t *)mRsmpOutBuffer;
3952 int16_t *dst = buffer.i16;
3953 while (framesOut--) {
3954 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3955 src += 2;
3956 }
3957 } else {
3958 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3959 }
3960
3961 }
3962 mActiveTrack->releaseBuffer(&buffer);
3963 mActiveTrack->overflow();
3964 }
3965 // client isn't retrieving buffers fast enough
3966 else {
Eric Laurent44d98482010-09-30 16:12:31 -07003967 if (!mActiveTrack->setOverflow()) {
3968 nsecs_t now = systemTime();
3969 if ((now - lastWarning) > kWarningThrottle) {
3970 LOGW("RecordThread: buffer overflow");
3971 lastWarning = now;
3972 }
3973 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 // Release the processor for a while before asking for a new buffer.
3975 // This will give the application more chance to read from the buffer and
3976 // clear the overflow.
3977 usleep(5000);
3978 }
3979 }
3980 }
3981
3982 if (!mStandby) {
Dima Zavin799a70e2011-04-18 16:57:27 -07003983 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984 }
3985 mActiveTrack.clear();
3986
3987 mStartStopCond.broadcast();
3988
3989 LOGV("RecordThread %p exiting", this);
3990 return false;
3991}
3992
3993status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
3994{
3995 LOGV("RecordThread::start");
3996 sp <ThreadBase> strongMe = this;
3997 status_t status = NO_ERROR;
3998 {
3999 AutoMutex lock(&mLock);
4000 if (mActiveTrack != 0) {
4001 if (recordTrack != mActiveTrack.get()) {
4002 status = -EBUSY;
4003 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
4004 mActiveTrack->mState = TrackBase::ACTIVE;
4005 }
4006 return status;
4007 }
4008
4009 recordTrack->mState = TrackBase::IDLE;
4010 mActiveTrack = recordTrack;
4011 mLock.unlock();
4012 status_t status = AudioSystem::startInput(mId);
4013 mLock.lock();
4014 if (status != NO_ERROR) {
4015 mActiveTrack.clear();
4016 return status;
4017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018 mRsmpInIndex = mFrameCount;
4019 mBytesRead = 0;
Eric Laurent243f5f92011-02-28 16:52:51 -08004020 if (mResampler != NULL) {
4021 mResampler->reset();
4022 }
4023 mActiveTrack->mState = TrackBase::RESUMING;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024 // signal thread to start
4025 LOGV("Signal record thread");
4026 mWaitWorkCV.signal();
4027 // do not wait for mStartStopCond if exiting
4028 if (mExiting) {
4029 mActiveTrack.clear();
4030 status = INVALID_OPERATION;
4031 goto startError;
4032 }
4033 mStartStopCond.wait(mLock);
4034 if (mActiveTrack == 0) {
4035 LOGV("Record failed to start");
4036 status = BAD_VALUE;
4037 goto startError;
4038 }
4039 LOGV("Record started OK");
4040 return status;
4041 }
4042startError:
4043 AudioSystem::stopInput(mId);
4044 return status;
4045}
4046
4047void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
4048 LOGV("RecordThread::stop");
4049 sp <ThreadBase> strongMe = this;
4050 {
4051 AutoMutex lock(&mLock);
4052 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
4053 mActiveTrack->mState = TrackBase::PAUSING;
4054 // do not wait for mStartStopCond if exiting
4055 if (mExiting) {
4056 return;
4057 }
4058 mStartStopCond.wait(mLock);
4059 // if we have been restarted, recordTrack == mActiveTrack.get() here
4060 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
4061 mLock.unlock();
4062 AudioSystem::stopInput(mId);
4063 mLock.lock();
4064 LOGV("Record stopped OK");
4065 }
4066 }
4067 }
4068}
4069
4070status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
4071{
4072 const size_t SIZE = 256;
4073 char buffer[SIZE];
4074 String8 result;
4075 pid_t pid = 0;
4076
4077 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
4078 result.append(buffer);
4079
4080 if (mActiveTrack != 0) {
4081 result.append("Active Track:\n");
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004082 result.append(" Clien Fmt Chn mask Session Buf S SRate Serv User\n");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 mActiveTrack->dump(buffer, SIZE);
4084 result.append(buffer);
4085
4086 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
4087 result.append(buffer);
4088 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
4089 result.append(buffer);
4090 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
4091 result.append(buffer);
4092 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
4093 result.append(buffer);
4094 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
4095 result.append(buffer);
4096
4097
4098 } else {
4099 result.append("No record client\n");
4100 }
4101 write(fd, result.string(), result.size());
4102
4103 dumpBase(fd, args);
4104
4105 return NO_ERROR;
4106}
4107
4108status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
4109{
4110 size_t framesReq = buffer->frameCount;
4111 size_t framesReady = mFrameCount - mRsmpInIndex;
4112 int channelCount;
4113
4114 if (framesReady == 0) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004115 mBytesRead = mInput->stream->read(mInput->stream, mRsmpInBuffer, mInputBytes);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 if (mBytesRead < 0) {
4117 LOGE("RecordThread::getNextBuffer() Error reading audio input");
4118 if (mActiveTrack->mState == TrackBase::ACTIVE) {
4119 // Force input into standby so that it tries to
4120 // recover at next read attempt
Dima Zavin799a70e2011-04-18 16:57:27 -07004121 mInput->stream->common.standby(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 usleep(5000);
4123 }
4124 buffer->raw = 0;
4125 buffer->frameCount = 0;
4126 return NOT_ENOUGH_DATA;
4127 }
4128 mRsmpInIndex = 0;
4129 framesReady = mFrameCount;
4130 }
4131
4132 if (framesReq > framesReady) {
4133 framesReq = framesReady;
4134 }
4135
4136 if (mChannelCount == 1 && mReqChannelCount == 2) {
4137 channelCount = 1;
4138 } else {
4139 channelCount = 2;
4140 }
4141 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
4142 buffer->frameCount = framesReq;
4143 return NO_ERROR;
4144}
4145
4146void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
4147{
4148 mRsmpInIndex += buffer->frameCount;
4149 buffer->frameCount = 0;
4150}
4151
4152bool AudioFlinger::RecordThread::checkForNewParameters_l()
4153{
4154 bool reconfig = false;
4155
4156 while (!mNewParameters.isEmpty()) {
4157 status_t status = NO_ERROR;
4158 String8 keyValuePair = mNewParameters[0];
4159 AudioParameter param = AudioParameter(keyValuePair);
4160 int value;
4161 int reqFormat = mFormat;
4162 int reqSamplingRate = mReqSampleRate;
4163 int reqChannelCount = mReqChannelCount;
4164
4165 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
4166 reqSamplingRate = value;
4167 reconfig = true;
4168 }
4169 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4170 reqFormat = value;
4171 reconfig = true;
4172 }
4173 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004174 reqChannelCount = popcount(value);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004175 reconfig = true;
4176 }
4177 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4178 // do not accept frame count changes if tracks are open as the track buffer
4179 // size depends on frame count and correct behavior would not be garantied
4180 // if frame count is changed after track creation
4181 if (mActiveTrack != 0) {
4182 status = INVALID_OPERATION;
4183 } else {
4184 reconfig = true;
4185 }
4186 }
4187 if (status == NO_ERROR) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004188 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004189 if (status == INVALID_OPERATION) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004190 mInput->stream->common.standby(&mInput->stream->common);
4191 status = mInput->stream->common.set_parameters(&mInput->stream->common, keyValuePair.string());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004192 }
4193 if (reconfig) {
4194 if (status == BAD_VALUE &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004195 reqFormat == mInput->stream->common.get_format(&mInput->stream->common) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004196 reqFormat == AUDIO_FORMAT_PCM_16_BIT &&
Dima Zavin799a70e2011-04-18 16:57:27 -07004197 ((int)mInput->stream->common.get_sample_rate(&mInput->stream->common) <= (2 * reqSamplingRate)) &&
4198 (popcount(mInput->stream->common.get_channels(&mInput->stream->common)) < 3) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004199 (reqChannelCount < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004200 status = NO_ERROR;
4201 }
4202 if (status == NO_ERROR) {
4203 readInputParameters();
4204 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
4205 }
4206 }
4207 }
4208
4209 mNewParameters.removeAt(0);
4210
4211 mParamStatus = status;
4212 mParamCond.signal();
4213 mWaitWorkCV.wait(mLock);
4214 }
4215 return reconfig;
4216}
4217
4218String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4219{
Dima Zavinfce7a472011-04-19 22:30:36 -07004220 char *s;
4221 String8 out_s8;
4222
Dima Zavin799a70e2011-04-18 16:57:27 -07004223 s = mInput->stream->common.get_parameters(&mInput->stream->common, keys.string());
Dima Zavinfce7a472011-04-19 22:30:36 -07004224 out_s8 = String8(s);
4225 free(s);
4226 return out_s8;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004227}
4228
4229void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
4230 AudioSystem::OutputDescriptor desc;
4231 void *param2 = 0;
4232
4233 switch (event) {
4234 case AudioSystem::INPUT_OPENED:
4235 case AudioSystem::INPUT_CONFIG_CHANGED:
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004236 desc.channels = mChannelMask;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 desc.samplingRate = mSampleRate;
4238 desc.format = mFormat;
4239 desc.frameCount = mFrameCount;
4240 desc.latency = 0;
4241 param2 = &desc;
4242 break;
4243
4244 case AudioSystem::INPUT_CLOSED:
4245 default:
4246 break;
4247 }
4248 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
4249}
4250
4251void AudioFlinger::RecordThread::readInputParameters()
4252{
4253 if (mRsmpInBuffer) delete mRsmpInBuffer;
4254 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4255 if (mResampler) delete mResampler;
4256 mResampler = 0;
4257
Dima Zavin799a70e2011-04-18 16:57:27 -07004258 mSampleRate = mInput->stream->common.get_sample_rate(&mInput->stream->common);
Jean-Michel Trivi0d255b22011-05-24 15:53:33 -07004259 mChannelMask = mInput->stream->common.get_channels(&mInput->stream->common);
4260 mChannelCount = (uint16_t)popcount(mChannelMask);
Dima Zavin799a70e2011-04-18 16:57:27 -07004261 mFormat = mInput->stream->common.get_format(&mInput->stream->common);
4262 mFrameSize = (uint16_t)audio_stream_frame_size(&mInput->stream->common);
4263 mInputBytes = mInput->stream->common.get_buffer_size(&mInput->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004264 mFrameCount = mInputBytes / mFrameSize;
4265 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4266
4267 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4268 {
4269 int channelCount;
4270 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4271 // stereo to mono post process as the resampler always outputs stereo.
4272 if (mChannelCount == 1 && mReqChannelCount == 2) {
4273 channelCount = 1;
4274 } else {
4275 channelCount = 2;
4276 }
4277 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4278 mResampler->setSampleRate(mSampleRate);
4279 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4280 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4281
4282 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4283 if (mChannelCount == 1 && mReqChannelCount == 1) {
4284 mFrameCount >>= 1;
4285 }
4286
4287 }
4288 mRsmpInIndex = mFrameCount;
4289}
4290
4291unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4292{
Dima Zavin799a70e2011-04-18 16:57:27 -07004293 return mInput->stream->get_input_frames_lost(mInput->stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004294}
4295
4296// ----------------------------------------------------------------------------
4297
4298int AudioFlinger::openOutput(uint32_t *pDevices,
4299 uint32_t *pSamplingRate,
4300 uint32_t *pFormat,
4301 uint32_t *pChannels,
4302 uint32_t *pLatencyMs,
4303 uint32_t flags)
4304{
4305 status_t status;
4306 PlaybackThread *thread = NULL;
4307 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4308 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4309 uint32_t format = pFormat ? *pFormat : 0;
4310 uint32_t channels = pChannels ? *pChannels : 0;
4311 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
Dima Zavin799a70e2011-04-18 16:57:27 -07004312 audio_stream_out_t *outStream;
4313 audio_hw_device_t *outHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004314
4315 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4316 pDevices ? *pDevices : 0,
4317 samplingRate,
4318 format,
4319 channels,
4320 flags);
4321
4322 if (pDevices == NULL || *pDevices == 0) {
4323 return 0;
4324 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004325
Mathias Agopian65ab4712010-07-14 17:59:35 -07004326 Mutex::Autolock _l(mLock);
4327
Dima Zavin799a70e2011-04-18 16:57:27 -07004328 outHwDev = findSuitableHwDev_l(*pDevices);
4329 if (outHwDev == NULL)
4330 return 0;
4331
4332 status = outHwDev->open_output_stream(outHwDev, *pDevices, (int *)&format,
4333 &channels, &samplingRate, &outStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004334 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004335 outStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004336 samplingRate,
4337 format,
4338 channels,
4339 status);
4340
4341 mHardwareStatus = AUDIO_HW_IDLE;
Dima Zavin799a70e2011-04-18 16:57:27 -07004342 if (outStream != NULL) {
4343 AudioStreamOut *output = new AudioStreamOut(outHwDev, outStream);
Eric Laurentf5aafb22010-11-18 08:40:16 -08004344 int id = nextUniqueId_l();
Dima Zavin799a70e2011-04-18 16:57:27 -07004345
Dima Zavinfce7a472011-04-19 22:30:36 -07004346 if ((flags & AUDIO_POLICY_OUTPUT_FLAG_DIRECT) ||
4347 (format != AUDIO_FORMAT_PCM_16_BIT) ||
4348 (channels != AUDIO_CHANNEL_OUT_STEREO)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004349 thread = new DirectOutputThread(this, output, id, *pDevices);
4350 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
4351 } else {
4352 thread = new MixerThread(this, output, id, *pDevices);
4353 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004354 }
4355 mPlaybackThreads.add(id, thread);
4356
4357 if (pSamplingRate) *pSamplingRate = samplingRate;
4358 if (pFormat) *pFormat = format;
4359 if (pChannels) *pChannels = channels;
4360 if (pLatencyMs) *pLatencyMs = thread->latency();
4361
4362 // notify client processes of the new output creation
4363 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4364 return id;
4365 }
4366
4367 return 0;
4368}
4369
4370int AudioFlinger::openDuplicateOutput(int output1, int output2)
4371{
4372 Mutex::Autolock _l(mLock);
4373 MixerThread *thread1 = checkMixerThread_l(output1);
4374 MixerThread *thread2 = checkMixerThread_l(output2);
4375
4376 if (thread1 == NULL || thread2 == NULL) {
4377 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4378 return 0;
4379 }
4380
Eric Laurentf5aafb22010-11-18 08:40:16 -08004381 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004382 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
4383 thread->addOutputTrack(thread2);
4384 mPlaybackThreads.add(id, thread);
4385 // notify client processes of the new output creation
4386 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
4387 return id;
4388}
4389
4390status_t AudioFlinger::closeOutput(int output)
4391{
4392 // keep strong reference on the playback thread so that
4393 // it is not destroyed while exit() is executed
4394 sp <PlaybackThread> thread;
4395 {
4396 Mutex::Autolock _l(mLock);
4397 thread = checkPlaybackThread_l(output);
4398 if (thread == NULL) {
4399 return BAD_VALUE;
4400 }
4401
4402 LOGV("closeOutput() %d", output);
4403
4404 if (thread->type() == PlaybackThread::MIXER) {
4405 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4406 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4407 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
4408 dupThread->removeOutputTrack((MixerThread *)thread.get());
4409 }
4410 }
4411 }
4412 void *param2 = 0;
4413 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
4414 mPlaybackThreads.removeItem(output);
4415 }
4416 thread->exit();
4417
4418 if (thread->type() != PlaybackThread::DUPLICATING) {
Dima Zavin799a70e2011-04-18 16:57:27 -07004419 AudioStreamOut *out = thread->getOutput();
4420 out->hwDev->close_output_stream(out->hwDev, out->stream);
4421 delete out;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004422 }
4423 return NO_ERROR;
4424}
4425
4426status_t AudioFlinger::suspendOutput(int output)
4427{
4428 Mutex::Autolock _l(mLock);
4429 PlaybackThread *thread = checkPlaybackThread_l(output);
4430
4431 if (thread == NULL) {
4432 return BAD_VALUE;
4433 }
4434
4435 LOGV("suspendOutput() %d", output);
4436 thread->suspend();
4437
4438 return NO_ERROR;
4439}
4440
4441status_t AudioFlinger::restoreOutput(int output)
4442{
4443 Mutex::Autolock _l(mLock);
4444 PlaybackThread *thread = checkPlaybackThread_l(output);
4445
4446 if (thread == NULL) {
4447 return BAD_VALUE;
4448 }
4449
4450 LOGV("restoreOutput() %d", output);
4451
4452 thread->restore();
4453
4454 return NO_ERROR;
4455}
4456
4457int AudioFlinger::openInput(uint32_t *pDevices,
4458 uint32_t *pSamplingRate,
4459 uint32_t *pFormat,
4460 uint32_t *pChannels,
4461 uint32_t acoustics)
4462{
4463 status_t status;
4464 RecordThread *thread = NULL;
4465 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4466 uint32_t format = pFormat ? *pFormat : 0;
4467 uint32_t channels = pChannels ? *pChannels : 0;
4468 uint32_t reqSamplingRate = samplingRate;
4469 uint32_t reqFormat = format;
4470 uint32_t reqChannels = channels;
Dima Zavin799a70e2011-04-18 16:57:27 -07004471 audio_stream_in_t *inStream;
4472 audio_hw_device_t *inHwDev;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004473
4474 if (pDevices == NULL || *pDevices == 0) {
4475 return 0;
4476 }
Dima Zavin799a70e2011-04-18 16:57:27 -07004477
Mathias Agopian65ab4712010-07-14 17:59:35 -07004478 Mutex::Autolock _l(mLock);
4479
Dima Zavin799a70e2011-04-18 16:57:27 -07004480 inHwDev = findSuitableHwDev_l(*pDevices);
4481 if (inHwDev == NULL)
4482 return 0;
4483
4484 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4485 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004486 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004487 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004488 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
Dima Zavin799a70e2011-04-18 16:57:27 -07004489 inStream,
Mathias Agopian65ab4712010-07-14 17:59:35 -07004490 samplingRate,
4491 format,
4492 channels,
4493 acoustics,
4494 status);
4495
4496 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4497 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4498 // or stereo to mono conversions on 16 bit PCM inputs.
Dima Zavin799a70e2011-04-18 16:57:27 -07004499 if (inStream == NULL && status == BAD_VALUE &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004500 reqFormat == format && format == AUDIO_FORMAT_PCM_16_BIT &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004501 (samplingRate <= 2 * reqSamplingRate) &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004502 (popcount(channels) < 3) && (popcount(reqChannels) < 3)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503 LOGV("openInput() reopening with proposed sampling rate and channels");
Dima Zavin799a70e2011-04-18 16:57:27 -07004504 status = inHwDev->open_input_stream(inHwDev, *pDevices, (int *)&format,
4505 &channels, &samplingRate,
Dima Zavinfce7a472011-04-19 22:30:36 -07004506 (audio_in_acoustics_t)acoustics,
Dima Zavin799a70e2011-04-18 16:57:27 -07004507 &inStream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004508 }
4509
Dima Zavin799a70e2011-04-18 16:57:27 -07004510 if (inStream != NULL) {
4511 AudioStreamIn *input = new AudioStreamIn(inHwDev, inStream);
4512
Eric Laurentf5aafb22010-11-18 08:40:16 -08004513 int id = nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004514 // Start record thread
4515 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4516 mRecordThreads.add(id, thread);
4517 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
4518 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4519 if (pFormat) *pFormat = format;
4520 if (pChannels) *pChannels = reqChannels;
4521
Dima Zavin799a70e2011-04-18 16:57:27 -07004522 input->stream->common.standby(&input->stream->common);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004523
4524 // notify client processes of the new input creation
4525 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
4526 return id;
4527 }
4528
4529 return 0;
4530}
4531
4532status_t AudioFlinger::closeInput(int input)
4533{
4534 // keep strong reference on the record thread so that
4535 // it is not destroyed while exit() is executed
4536 sp <RecordThread> thread;
4537 {
4538 Mutex::Autolock _l(mLock);
4539 thread = checkRecordThread_l(input);
4540 if (thread == NULL) {
4541 return BAD_VALUE;
4542 }
4543
4544 LOGV("closeInput() %d", input);
4545 void *param2 = 0;
4546 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
4547 mRecordThreads.removeItem(input);
4548 }
4549 thread->exit();
4550
Dima Zavin799a70e2011-04-18 16:57:27 -07004551 AudioStreamIn *in = thread->getInput();
4552 in->hwDev->close_input_stream(in->hwDev, in->stream);
4553 delete in;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004554
4555 return NO_ERROR;
4556}
4557
4558status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
4559{
4560 Mutex::Autolock _l(mLock);
4561 MixerThread *dstThread = checkMixerThread_l(output);
4562 if (dstThread == NULL) {
4563 LOGW("setStreamOutput() bad output id %d", output);
4564 return BAD_VALUE;
4565 }
4566
4567 LOGV("setStreamOutput() stream %d to output %d", stream, output);
4568 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
4569
4570 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4571 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
4572 if (thread != dstThread &&
4573 thread->type() != PlaybackThread::DIRECT) {
4574 MixerThread *srcThread = (MixerThread *)thread;
4575 srcThread->invalidateTracks(stream);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576 }
Eric Laurentde070132010-07-13 04:45:46 -07004577 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004578
4579 return NO_ERROR;
4580}
4581
4582
4583int AudioFlinger::newAudioSessionId()
4584{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004585 AutoMutex _l(mLock);
4586 return nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004587}
4588
4589// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
4590AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
4591{
4592 PlaybackThread *thread = NULL;
4593 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4594 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
4595 }
4596 return thread;
4597}
4598
4599// checkMixerThread_l() must be called with AudioFlinger::mLock held
4600AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
4601{
4602 PlaybackThread *thread = checkPlaybackThread_l(output);
4603 if (thread != NULL) {
4604 if (thread->type() == PlaybackThread::DIRECT) {
4605 thread = NULL;
4606 }
4607 }
4608 return (MixerThread *)thread;
4609}
4610
4611// checkRecordThread_l() must be called with AudioFlinger::mLock held
4612AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
4613{
4614 RecordThread *thread = NULL;
4615 if (mRecordThreads.indexOfKey(input) >= 0) {
4616 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
4617 }
4618 return thread;
4619}
4620
Eric Laurentf5aafb22010-11-18 08:40:16 -08004621// nextUniqueId_l() must be called with AudioFlinger::mLock held
4622int AudioFlinger::nextUniqueId_l()
Mathias Agopian65ab4712010-07-14 17:59:35 -07004623{
Eric Laurentf5aafb22010-11-18 08:40:16 -08004624 return mNextUniqueId++;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004625}
4626
4627// ----------------------------------------------------------------------------
4628// Effect management
4629// ----------------------------------------------------------------------------
4630
4631
Mathias Agopian65ab4712010-07-14 17:59:35 -07004632status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4633{
4634 Mutex::Autolock _l(mLock);
4635 return EffectQueryNumberEffects(numEffects);
4636}
4637
4638status_t AudioFlinger::queryEffect(uint32_t index, effect_descriptor_t *descriptor)
4639{
4640 Mutex::Autolock _l(mLock);
4641 return EffectQueryEffect(index, descriptor);
4642}
4643
4644status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4645{
4646 Mutex::Autolock _l(mLock);
4647 return EffectGetDescriptor(pUuid, descriptor);
4648}
4649
4650
4651// this UUID must match the one defined in media/libeffects/EffectVisualizer.cpp
4652static const effect_uuid_t VISUALIZATION_UUID_ =
4653 {0xd069d9e0, 0x8329, 0x11df, 0x9168, {0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b}};
4654
4655sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4656 effect_descriptor_t *pDesc,
4657 const sp<IEffectClient>& effectClient,
4658 int32_t priority,
4659 int output,
4660 int sessionId,
4661 status_t *status,
4662 int *id,
4663 int *enabled)
4664{
4665 status_t lStatus = NO_ERROR;
4666 sp<EffectHandle> handle;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004667 effect_descriptor_t desc;
4668 sp<Client> client;
4669 wp<Client> wclient;
4670
Eric Laurentde070132010-07-13 04:45:46 -07004671 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d",
4672 pid, effectClient.get(), priority, sessionId, output);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004673
4674 if (pDesc == NULL) {
4675 lStatus = BAD_VALUE;
4676 goto Exit;
4677 }
4678
Eric Laurent84e9a102010-09-23 16:10:16 -07004679 // check audio settings permission for global effects
Dima Zavinfce7a472011-04-19 22:30:36 -07004680 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && !settingsAllowed()) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004681 lStatus = PERMISSION_DENIED;
4682 goto Exit;
4683 }
4684
Dima Zavinfce7a472011-04-19 22:30:36 -07004685 // Session AUDIO_SESSION_OUTPUT_STAGE is reserved for output stage effects
Eric Laurent84e9a102010-09-23 16:10:16 -07004686 // that can only be created by audio policy manager (running in same process)
Dima Zavinfce7a472011-04-19 22:30:36 -07004687 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE && getpid() != pid) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004688 lStatus = PERMISSION_DENIED;
4689 goto Exit;
4690 }
4691
4692 // check recording permission for visualizer
4693 if ((memcmp(&pDesc->type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0 ||
4694 memcmp(&pDesc->uuid, &VISUALIZATION_UUID_, sizeof(effect_uuid_t)) == 0) &&
4695 !recordingAllowed()) {
4696 lStatus = PERMISSION_DENIED;
4697 goto Exit;
4698 }
4699
4700 if (output == 0) {
Dima Zavinfce7a472011-04-19 22:30:36 -07004701 if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004702 // output must be specified by AudioPolicyManager when using session
Dima Zavinfce7a472011-04-19 22:30:36 -07004703 // AUDIO_SESSION_OUTPUT_STAGE
Eric Laurent84e9a102010-09-23 16:10:16 -07004704 lStatus = BAD_VALUE;
4705 goto Exit;
Dima Zavinfce7a472011-04-19 22:30:36 -07004706 } else if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004707 // if the output returned by getOutputForEffect() is removed before we lock the
4708 // mutex below, the call to checkPlaybackThread_l(output) below will detect it
4709 // and we will exit safely
4710 output = AudioSystem::getOutputForEffect(&desc);
4711 }
4712 }
4713
Mathias Agopian65ab4712010-07-14 17:59:35 -07004714 {
4715 Mutex::Autolock _l(mLock);
4716
Mathias Agopian65ab4712010-07-14 17:59:35 -07004717
4718 if (!EffectIsNullUuid(&pDesc->uuid)) {
4719 // if uuid is specified, request effect descriptor
4720 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4721 if (lStatus < 0) {
4722 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4723 goto Exit;
4724 }
4725 } else {
4726 // if uuid is not specified, look for an available implementation
4727 // of the required type in effect factory
4728 if (EffectIsNullUuid(&pDesc->type)) {
4729 LOGW("createEffect() no effect type");
4730 lStatus = BAD_VALUE;
4731 goto Exit;
4732 }
4733 uint32_t numEffects = 0;
4734 effect_descriptor_t d;
4735 bool found = false;
4736
4737 lStatus = EffectQueryNumberEffects(&numEffects);
4738 if (lStatus < 0) {
4739 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4740 goto Exit;
4741 }
4742 for (uint32_t i = 0; i < numEffects; i++) {
4743 lStatus = EffectQueryEffect(i, &desc);
4744 if (lStatus < 0) {
4745 LOGW("createEffect() error %d from EffectQueryEffect", lStatus);
4746 continue;
4747 }
4748 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4749 // If matching type found save effect descriptor. If the session is
4750 // 0 and the effect is not auxiliary, continue enumeration in case
4751 // an auxiliary version of this effect type is available
4752 found = true;
4753 memcpy(&d, &desc, sizeof(effect_descriptor_t));
Dima Zavinfce7a472011-04-19 22:30:36 -07004754 if (sessionId != AUDIO_SESSION_OUTPUT_MIX ||
Mathias Agopian65ab4712010-07-14 17:59:35 -07004755 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4756 break;
4757 }
4758 }
4759 }
4760 if (!found) {
4761 lStatus = BAD_VALUE;
4762 LOGW("createEffect() effect not found");
4763 goto Exit;
4764 }
4765 // For same effect type, chose auxiliary version over insert version if
4766 // connect to output mix (Compliance to OpenSL ES)
Dima Zavinfce7a472011-04-19 22:30:36 -07004767 if (sessionId == AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004768 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4769 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4770 }
4771 }
4772
4773 // Do not allow auxiliary effects on a session different from 0 (output mix)
Dima Zavinfce7a472011-04-19 22:30:36 -07004774 if (sessionId != AUDIO_SESSION_OUTPUT_MIX &&
Mathias Agopian65ab4712010-07-14 17:59:35 -07004775 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4776 lStatus = INVALID_OPERATION;
4777 goto Exit;
4778 }
4779
Mathias Agopian65ab4712010-07-14 17:59:35 -07004780 // return effect descriptor
4781 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4782
4783 // If output is not specified try to find a matching audio session ID in one of the
4784 // output threads.
Eric Laurent84e9a102010-09-23 16:10:16 -07004785 // If output is 0 here, sessionId is neither SESSION_OUTPUT_STAGE nor SESSION_OUTPUT_MIX
4786 // because of code checking output when entering the function.
Mathias Agopian65ab4712010-07-14 17:59:35 -07004787 if (output == 0) {
Eric Laurent84e9a102010-09-23 16:10:16 -07004788 // look for the thread where the specified audio session is present
4789 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4790 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId) != 0) {
4791 output = mPlaybackThreads.keyAt(i);
4792 break;
Eric Laurent39e94f82010-07-28 01:32:47 -07004793 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004794 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004795 // If no output thread contains the requested session ID, default to
4796 // first output. The effect chain will be moved to the correct output
4797 // thread when a track with the same session ID is created
4798 if (output == 0 && mPlaybackThreads.size()) {
4799 output = mPlaybackThreads.keyAt(0);
4800 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004801 }
Eric Laurent84e9a102010-09-23 16:10:16 -07004802 LOGV("createEffect() got output %d for effect %s", output, desc.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004803 PlaybackThread *thread = checkPlaybackThread_l(output);
4804 if (thread == NULL) {
Eric Laurentde070132010-07-13 04:45:46 -07004805 LOGE("createEffect() unknown output thread");
Mathias Agopian65ab4712010-07-14 17:59:35 -07004806 lStatus = BAD_VALUE;
4807 goto Exit;
4808 }
4809
Eric Laurent84e9a102010-09-23 16:10:16 -07004810 // TODO: allow attachment of effect to inputs
4811
Mathias Agopian65ab4712010-07-14 17:59:35 -07004812 wclient = mClients.valueFor(pid);
4813
4814 if (wclient != NULL) {
4815 client = wclient.promote();
4816 } else {
4817 client = new Client(this, pid);
4818 mClients.add(pid, client);
4819 }
4820
4821 // create effect on selected output trhead
Eric Laurentde070132010-07-13 04:45:46 -07004822 handle = thread->createEffect_l(client, effectClient, priority, sessionId,
4823 &desc, enabled, &lStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004824 if (handle != 0 && id != NULL) {
4825 *id = handle->id();
4826 }
4827 }
4828
4829Exit:
4830 if(status) {
4831 *status = lStatus;
4832 }
4833 return handle;
4834}
4835
Eric Laurentde070132010-07-13 04:45:46 -07004836status_t AudioFlinger::moveEffects(int session, int srcOutput, int dstOutput)
4837{
4838 LOGV("moveEffects() session %d, srcOutput %d, dstOutput %d",
4839 session, srcOutput, dstOutput);
4840 Mutex::Autolock _l(mLock);
4841 if (srcOutput == dstOutput) {
4842 LOGW("moveEffects() same dst and src outputs %d", dstOutput);
4843 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004844 }
Eric Laurentde070132010-07-13 04:45:46 -07004845 PlaybackThread *srcThread = checkPlaybackThread_l(srcOutput);
4846 if (srcThread == NULL) {
4847 LOGW("moveEffects() bad srcOutput %d", srcOutput);
4848 return BAD_VALUE;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004849 }
Eric Laurentde070132010-07-13 04:45:46 -07004850 PlaybackThread *dstThread = checkPlaybackThread_l(dstOutput);
4851 if (dstThread == NULL) {
4852 LOGW("moveEffects() bad dstOutput %d", dstOutput);
4853 return BAD_VALUE;
4854 }
4855
4856 Mutex::Autolock _dl(dstThread->mLock);
4857 Mutex::Autolock _sl(srcThread->mLock);
Eric Laurent39e94f82010-07-28 01:32:47 -07004858 moveEffectChain_l(session, srcThread, dstThread, false);
Eric Laurentde070132010-07-13 04:45:46 -07004859
Mathias Agopian65ab4712010-07-14 17:59:35 -07004860 return NO_ERROR;
4861}
4862
Eric Laurentde070132010-07-13 04:45:46 -07004863// moveEffectChain_l mustbe called with both srcThread and dstThread mLocks held
4864status_t AudioFlinger::moveEffectChain_l(int session,
4865 AudioFlinger::PlaybackThread *srcThread,
Eric Laurent39e94f82010-07-28 01:32:47 -07004866 AudioFlinger::PlaybackThread *dstThread,
4867 bool reRegister)
Eric Laurentde070132010-07-13 04:45:46 -07004868{
4869 LOGV("moveEffectChain_l() session %d from thread %p to thread %p",
4870 session, srcThread, dstThread);
4871
4872 sp<EffectChain> chain = srcThread->getEffectChain_l(session);
4873 if (chain == 0) {
4874 LOGW("moveEffectChain_l() effect chain for session %d not on source thread %p",
4875 session, srcThread);
4876 return INVALID_OPERATION;
4877 }
4878
Eric Laurent39e94f82010-07-28 01:32:47 -07004879 // remove chain first. This is useful only if reconfiguring effect chain on same output thread,
Eric Laurentde070132010-07-13 04:45:46 -07004880 // so that a new chain is created with correct parameters when first effect is added. This is
4881 // otherwise unecessary as removeEffect_l() will remove the chain when last effect is
4882 // removed.
4883 srcThread->removeEffectChain_l(chain);
4884
4885 // transfer all effects one by one so that new effect chain is created on new thread with
4886 // correct buffer sizes and audio parameters and effect engines reconfigured accordingly
Eric Laurent39e94f82010-07-28 01:32:47 -07004887 int dstOutput = dstThread->id();
4888 sp<EffectChain> dstChain;
4889 uint32_t strategy;
Eric Laurentde070132010-07-13 04:45:46 -07004890 sp<EffectModule> effect = chain->getEffectFromId_l(0);
4891 while (effect != 0) {
4892 srcThread->removeEffect_l(effect);
4893 dstThread->addEffect_l(effect);
Eric Laurent39e94f82010-07-28 01:32:47 -07004894 // if the move request is not received from audio policy manager, the effect must be
4895 // re-registered with the new strategy and output
4896 if (dstChain == 0) {
4897 dstChain = effect->chain().promote();
4898 if (dstChain == 0) {
4899 LOGW("moveEffectChain_l() cannot get chain from effect %p", effect.get());
4900 srcThread->addEffect_l(effect);
4901 return NO_INIT;
4902 }
4903 strategy = dstChain->strategy();
4904 }
4905 if (reRegister) {
4906 AudioSystem::unregisterEffect(effect->id());
4907 AudioSystem::registerEffect(&effect->desc(),
4908 dstOutput,
4909 strategy,
4910 session,
4911 effect->id());
4912 }
Eric Laurentde070132010-07-13 04:45:46 -07004913 effect = chain->getEffectFromId_l(0);
4914 }
4915
4916 return NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004917}
4918
4919// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4920sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4921 const sp<AudioFlinger::Client>& client,
4922 const sp<IEffectClient>& effectClient,
4923 int32_t priority,
4924 int sessionId,
4925 effect_descriptor_t *desc,
4926 int *enabled,
4927 status_t *status
4928 )
4929{
4930 sp<EffectModule> effect;
4931 sp<EffectHandle> handle;
4932 status_t lStatus;
4933 sp<Track> track;
4934 sp<EffectChain> chain;
Eric Laurentde070132010-07-13 04:45:46 -07004935 bool chainCreated = false;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004936 bool effectCreated = false;
4937 bool effectRegistered = false;
4938
4939 if (mOutput == 0) {
4940 LOGW("createEffect_l() Audio driver not initialized.");
4941 lStatus = NO_INIT;
4942 goto Exit;
4943 }
4944
4945 // Do not allow auxiliary effect on session other than 0
4946 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
Dima Zavinfce7a472011-04-19 22:30:36 -07004947 sessionId != AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentde070132010-07-13 04:45:46 -07004948 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4949 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950 lStatus = BAD_VALUE;
4951 goto Exit;
4952 }
4953
4954 // Do not allow effects with session ID 0 on direct output or duplicating threads
4955 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
Dima Zavinfce7a472011-04-19 22:30:36 -07004956 if (sessionId == AUDIO_SESSION_OUTPUT_MIX && mType != MIXER) {
Eric Laurentde070132010-07-13 04:45:46 -07004957 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d",
4958 desc->name, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004959 lStatus = BAD_VALUE;
4960 goto Exit;
4961 }
4962
4963 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4964
4965 { // scope for mLock
4966 Mutex::Autolock _l(mLock);
4967
4968 // check for existing effect chain with the requested audio session
4969 chain = getEffectChain_l(sessionId);
4970 if (chain == 0) {
4971 // create a new chain for this session
4972 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4973 chain = new EffectChain(this, sessionId);
4974 addEffectChain_l(chain);
Eric Laurentde070132010-07-13 04:45:46 -07004975 chain->setStrategy(getStrategyForSession_l(sessionId));
4976 chainCreated = true;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 } else {
Eric Laurentcab11242010-07-15 12:50:15 -07004978 effect = chain->getEffectFromDesc_l(desc);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 }
4980
4981 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4982
4983 if (effect == 0) {
Eric Laurentf5aafb22010-11-18 08:40:16 -08004984 int id = mAudioFlinger->nextUniqueId_l();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004985 // Check CPU and memory usage
Eric Laurentde070132010-07-13 04:45:46 -07004986 lStatus = AudioSystem::registerEffect(desc, mId, chain->strategy(), sessionId, id);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004987 if (lStatus != NO_ERROR) {
4988 goto Exit;
4989 }
4990 effectRegistered = true;
4991 // create a new effect module if none present in the chain
Eric Laurentde070132010-07-13 04:45:46 -07004992 effect = new EffectModule(this, chain, desc, id, sessionId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004993 lStatus = effect->status();
4994 if (lStatus != NO_ERROR) {
4995 goto Exit;
4996 }
Eric Laurentcab11242010-07-15 12:50:15 -07004997 lStatus = chain->addEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004998 if (lStatus != NO_ERROR) {
4999 goto Exit;
5000 }
5001 effectCreated = true;
5002
5003 effect->setDevice(mDevice);
5004 effect->setMode(mAudioFlinger->getMode());
5005 }
5006 // create effect handle and connect it to effect module
5007 handle = new EffectHandle(effect, client, effectClient, priority);
5008 lStatus = effect->addHandle(handle);
5009 if (enabled) {
5010 *enabled = (int)effect->isEnabled();
5011 }
5012 }
5013
5014Exit:
5015 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurentde070132010-07-13 04:45:46 -07005016 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005017 if (effectCreated) {
Eric Laurentde070132010-07-13 04:45:46 -07005018 chain->removeEffect_l(effect);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005019 }
5020 if (effectRegistered) {
Eric Laurentde070132010-07-13 04:45:46 -07005021 AudioSystem::unregisterEffect(effect->id());
5022 }
5023 if (chainCreated) {
5024 removeEffectChain_l(chain);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005025 }
5026 handle.clear();
5027 }
5028
5029 if(status) {
5030 *status = lStatus;
5031 }
5032 return handle;
5033}
5034
Eric Laurentde070132010-07-13 04:45:46 -07005035// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
5036// PlaybackThread::mLock held
5037status_t AudioFlinger::PlaybackThread::addEffect_l(const sp<EffectModule>& effect)
5038{
5039 // check for existing effect chain with the requested audio session
5040 int sessionId = effect->sessionId();
5041 sp<EffectChain> chain = getEffectChain_l(sessionId);
5042 bool chainCreated = false;
5043
5044 if (chain == 0) {
5045 // create a new chain for this session
5046 LOGV("addEffect_l() new effect chain for session %d", sessionId);
5047 chain = new EffectChain(this, sessionId);
5048 addEffectChain_l(chain);
5049 chain->setStrategy(getStrategyForSession_l(sessionId));
5050 chainCreated = true;
5051 }
5052 LOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
5053
5054 if (chain->getEffectFromId_l(effect->id()) != 0) {
5055 LOGW("addEffect_l() %p effect %s already present in chain %p",
5056 this, effect->desc().name, chain.get());
5057 return BAD_VALUE;
5058 }
5059
5060 status_t status = chain->addEffect_l(effect);
5061 if (status != NO_ERROR) {
5062 if (chainCreated) {
5063 removeEffectChain_l(chain);
5064 }
5065 return status;
5066 }
5067
5068 effect->setDevice(mDevice);
5069 effect->setMode(mAudioFlinger->getMode());
5070 return NO_ERROR;
5071}
5072
5073void AudioFlinger::PlaybackThread::removeEffect_l(const sp<EffectModule>& effect) {
5074
5075 LOGV("removeEffect_l() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005076 effect_descriptor_t desc = effect->desc();
Eric Laurentde070132010-07-13 04:45:46 -07005077 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5078 detachAuxEffect_l(effect->id());
5079 }
5080
5081 sp<EffectChain> chain = effect->chain().promote();
5082 if (chain != 0) {
5083 // remove effect chain if removing last effect
5084 if (chain->removeEffect_l(effect) == 0) {
5085 removeEffectChain_l(chain);
5086 }
5087 } else {
5088 LOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
5089 }
5090}
5091
5092void AudioFlinger::PlaybackThread::disconnectEffect(const sp<EffectModule>& effect,
5093 const wp<EffectHandle>& handle) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005094 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07005095 LOGV("disconnectEffect() %p effect %p", this, effect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005096 // delete the effect module if removing last handle on it
5097 if (effect->removeHandle(handle) == 0) {
Eric Laurentde070132010-07-13 04:45:46 -07005098 removeEffect_l(effect);
5099 AudioSystem::unregisterEffect(effect->id());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005100 }
5101}
5102
5103status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
5104{
5105 int session = chain->sessionId();
5106 int16_t *buffer = mMixBuffer;
5107 bool ownsBuffer = false;
5108
5109 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
5110 if (session > 0) {
5111 // Only one effect chain can be present in direct output thread and it uses
5112 // the mix buffer as input
5113 if (mType != DIRECT) {
5114 size_t numSamples = mFrameCount * mChannelCount;
5115 buffer = new int16_t[numSamples];
5116 memset(buffer, 0, numSamples * sizeof(int16_t));
5117 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
5118 ownsBuffer = true;
5119 }
5120
5121 // Attach all tracks with same session ID to this chain.
5122 for (size_t i = 0; i < mTracks.size(); ++i) {
5123 sp<Track> track = mTracks[i];
5124 if (session == track->sessionId()) {
5125 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
5126 track->setMainBuffer(buffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005127 chain->incTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005128 }
5129 }
5130
5131 // indicate all active tracks in the chain
5132 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5133 sp<Track> track = mActiveTracks[i].promote();
5134 if (track == 0) continue;
5135 if (session == track->sessionId()) {
5136 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
Eric Laurentb469b942011-05-09 12:09:06 -07005137 chain->incActiveTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005138 }
5139 }
5140 }
5141
5142 chain->setInBuffer(buffer, ownsBuffer);
5143 chain->setOutBuffer(mMixBuffer);
Dima Zavinfce7a472011-04-19 22:30:36 -07005144 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Eric Laurentde070132010-07-13 04:45:46 -07005145 // chains list in order to be processed last as it contains output stage effects
Dima Zavinfce7a472011-04-19 22:30:36 -07005146 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
5147 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Mathias Agopian65ab4712010-07-14 17:59:35 -07005148 // after track specific effects and before output stage
Dima Zavinfce7a472011-04-19 22:30:36 -07005149 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
5150 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX
Eric Laurentde070132010-07-13 04:45:46 -07005151 // Effect chain for other sessions are inserted at beginning of effect
5152 // chains list to be processed before output mix effects. Relative order between other
5153 // sessions is not important
Mathias Agopian65ab4712010-07-14 17:59:35 -07005154 size_t size = mEffectChains.size();
5155 size_t i = 0;
5156 for (i = 0; i < size; i++) {
5157 if (mEffectChains[i]->sessionId() < session) break;
5158 }
5159 mEffectChains.insertAt(chain, i);
5160
5161 return NO_ERROR;
5162}
5163
5164size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
5165{
5166 int session = chain->sessionId();
5167
5168 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
5169
5170 for (size_t i = 0; i < mEffectChains.size(); i++) {
5171 if (chain == mEffectChains[i]) {
5172 mEffectChains.removeAt(i);
Eric Laurentb469b942011-05-09 12:09:06 -07005173 // detach all active tracks from the chain
5174 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
5175 sp<Track> track = mActiveTracks[i].promote();
5176 if (track == 0) continue;
5177 if (session == track->sessionId()) {
5178 LOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
5179 chain.get(), session);
5180 chain->decActiveTrackCnt();
5181 }
5182 }
5183
Mathias Agopian65ab4712010-07-14 17:59:35 -07005184 // detach all tracks with same session ID from this chain
5185 for (size_t i = 0; i < mTracks.size(); ++i) {
5186 sp<Track> track = mTracks[i];
5187 if (session == track->sessionId()) {
5188 track->setMainBuffer(mMixBuffer);
Eric Laurentb469b942011-05-09 12:09:06 -07005189 chain->decTrackCnt();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005190 }
5191 }
Eric Laurentde070132010-07-13 04:45:46 -07005192 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005193 }
5194 }
5195 return mEffectChains.size();
5196}
5197
Eric Laurentde070132010-07-13 04:45:46 -07005198void AudioFlinger::PlaybackThread::lockEffectChains_l(
5199 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005200{
Eric Laurentde070132010-07-13 04:45:46 -07005201 effectChains = mEffectChains;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005202 for (size_t i = 0; i < mEffectChains.size(); i++) {
5203 mEffectChains[i]->lock();
5204 }
5205}
5206
Eric Laurentde070132010-07-13 04:45:46 -07005207void AudioFlinger::PlaybackThread::unlockEffectChains(
5208 Vector<sp <AudioFlinger::EffectChain> >& effectChains)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005209{
Eric Laurentde070132010-07-13 04:45:46 -07005210 for (size_t i = 0; i < effectChains.size(); i++) {
5211 effectChains[i]->unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212 }
5213}
5214
Eric Laurentde070132010-07-13 04:45:46 -07005215
Mathias Agopian65ab4712010-07-14 17:59:35 -07005216sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
5217{
5218 sp<EffectModule> effect;
5219
5220 sp<EffectChain> chain = getEffectChain_l(sessionId);
5221 if (chain != 0) {
Eric Laurentcab11242010-07-15 12:50:15 -07005222 effect = chain->getEffectFromId_l(effectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005223 }
5224 return effect;
5225}
5226
Eric Laurentde070132010-07-13 04:45:46 -07005227status_t AudioFlinger::PlaybackThread::attachAuxEffect(
5228 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005229{
5230 Mutex::Autolock _l(mLock);
5231 return attachAuxEffect_l(track, EffectId);
5232}
5233
Eric Laurentde070132010-07-13 04:45:46 -07005234status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
5235 const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005236{
5237 status_t status = NO_ERROR;
5238
5239 if (EffectId == 0) {
5240 track->setAuxBuffer(0, NULL);
5241 } else {
Dima Zavinfce7a472011-04-19 22:30:36 -07005242 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
5243 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005244 if (effect != 0) {
5245 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5246 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
5247 } else {
5248 status = INVALID_OPERATION;
5249 }
5250 } else {
5251 status = BAD_VALUE;
5252 }
5253 }
5254 return status;
5255}
5256
5257void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
5258{
5259 for (size_t i = 0; i < mTracks.size(); ++i) {
5260 sp<Track> track = mTracks[i];
5261 if (track->auxEffectId() == effectId) {
5262 attachAuxEffect_l(track, 0);
5263 }
5264 }
5265}
5266
5267// ----------------------------------------------------------------------------
5268// EffectModule implementation
5269// ----------------------------------------------------------------------------
5270
5271#undef LOG_TAG
5272#define LOG_TAG "AudioFlinger::EffectModule"
5273
5274AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
5275 const wp<AudioFlinger::EffectChain>& chain,
5276 effect_descriptor_t *desc,
5277 int id,
5278 int sessionId)
5279 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
5280 mStatus(NO_INIT), mState(IDLE)
5281{
5282 LOGV("Constructor %p", this);
5283 int lStatus;
5284 sp<ThreadBase> thread = mThread.promote();
5285 if (thread == 0) {
5286 return;
5287 }
5288 PlaybackThread *p = (PlaybackThread *)thread.get();
5289
5290 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
5291
5292 // create effect engine from effect factory
5293 mStatus = EffectCreate(&desc->uuid, sessionId, p->id(), &mEffectInterface);
5294
5295 if (mStatus != NO_ERROR) {
5296 return;
5297 }
5298 lStatus = init();
5299 if (lStatus < 0) {
5300 mStatus = lStatus;
5301 goto Error;
5302 }
5303
5304 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
5305 return;
5306Error:
5307 EffectRelease(mEffectInterface);
5308 mEffectInterface = NULL;
5309 LOGV("Constructor Error %d", mStatus);
5310}
5311
5312AudioFlinger::EffectModule::~EffectModule()
5313{
5314 LOGV("Destructor %p", this);
5315 if (mEffectInterface != NULL) {
5316 // release effect engine
5317 EffectRelease(mEffectInterface);
5318 }
5319}
5320
5321status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
5322{
5323 status_t status;
5324
5325 Mutex::Autolock _l(mLock);
5326 // First handle in mHandles has highest priority and controls the effect module
5327 int priority = handle->priority();
5328 size_t size = mHandles.size();
5329 sp<EffectHandle> h;
5330 size_t i;
5331 for (i = 0; i < size; i++) {
5332 h = mHandles[i].promote();
5333 if (h == 0) continue;
5334 if (h->priority() <= priority) break;
5335 }
5336 // if inserted in first place, move effect control from previous owner to this handle
5337 if (i == 0) {
5338 if (h != 0) {
5339 h->setControl(false, true);
5340 }
5341 handle->setControl(true, false);
5342 status = NO_ERROR;
5343 } else {
5344 status = ALREADY_EXISTS;
5345 }
5346 mHandles.insertAt(handle, i);
5347 return status;
5348}
5349
5350size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
5351{
5352 Mutex::Autolock _l(mLock);
5353 size_t size = mHandles.size();
5354 size_t i;
5355 for (i = 0; i < size; i++) {
5356 if (mHandles[i] == handle) break;
5357 }
5358 if (i == size) {
5359 return size;
5360 }
5361 mHandles.removeAt(i);
5362 size = mHandles.size();
5363 // if removed from first place, move effect control from this handle to next in line
5364 if (i == 0 && size != 0) {
5365 sp<EffectHandle> h = mHandles[0].promote();
5366 if (h != 0) {
5367 h->setControl(true, true);
5368 }
5369 }
5370
Eric Laurentdac69112010-09-28 14:09:57 -07005371 // Release effect engine here so that it is done immediately. Otherwise it will be released
5372 // by the destructor when the last strong reference on the this object is released which can
5373 // happen after next process is called on this effect.
5374 if (size == 0 && mEffectInterface != NULL) {
5375 // release effect engine
5376 EffectRelease(mEffectInterface);
5377 mEffectInterface = NULL;
5378 }
5379
Mathias Agopian65ab4712010-07-14 17:59:35 -07005380 return size;
5381}
5382
5383void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
5384{
5385 // keep a strong reference on this EffectModule to avoid calling the
5386 // destructor before we exit
5387 sp<EffectModule> keep(this);
5388 {
5389 sp<ThreadBase> thread = mThread.promote();
5390 if (thread != 0) {
5391 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
5392 playbackThread->disconnectEffect(keep, handle);
5393 }
5394 }
5395}
5396
5397void AudioFlinger::EffectModule::updateState() {
5398 Mutex::Autolock _l(mLock);
5399
5400 switch (mState) {
5401 case RESTART:
5402 reset_l();
5403 // FALL THROUGH
5404
5405 case STARTING:
5406 // clear auxiliary effect input buffer for next accumulation
5407 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5408 memset(mConfig.inputCfg.buffer.raw,
5409 0,
5410 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5411 }
5412 start_l();
5413 mState = ACTIVE;
5414 break;
5415 case STOPPING:
5416 stop_l();
5417 mDisableWaitCnt = mMaxDisableWaitCnt;
5418 mState = STOPPED;
5419 break;
5420 case STOPPED:
5421 // mDisableWaitCnt is forced to 1 by process() when the engine indicates the end of the
5422 // turn off sequence.
5423 if (--mDisableWaitCnt == 0) {
5424 reset_l();
5425 mState = IDLE;
5426 }
5427 break;
5428 default: //IDLE , ACTIVE
5429 break;
5430 }
5431}
5432
5433void AudioFlinger::EffectModule::process()
5434{
5435 Mutex::Autolock _l(mLock);
5436
5437 if (mEffectInterface == NULL ||
5438 mConfig.inputCfg.buffer.raw == NULL ||
5439 mConfig.outputCfg.buffer.raw == NULL) {
5440 return;
5441 }
5442
Eric Laurent8f45bd72010-08-31 13:50:07 -07005443 if (isProcessEnabled()) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005444 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5445 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5446 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5447 mConfig.inputCfg.buffer.s32,
Eric Laurentde070132010-07-13 04:45:46 -07005448 mConfig.inputCfg.buffer.frameCount/2);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005449 }
5450
5451 // do the actual processing in the effect engine
5452 int ret = (*mEffectInterface)->process(mEffectInterface,
5453 &mConfig.inputCfg.buffer,
5454 &mConfig.outputCfg.buffer);
5455
5456 // force transition to IDLE state when engine is ready
5457 if (mState == STOPPED && ret == -ENODATA) {
5458 mDisableWaitCnt = 1;
5459 }
5460
5461 // clear auxiliary effect input buffer for next accumulation
5462 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurent73337482011-01-19 18:36:13 -08005463 memset(mConfig.inputCfg.buffer.raw, 0,
5464 mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
Mathias Agopian65ab4712010-07-14 17:59:35 -07005465 }
5466 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
Eric Laurent73337482011-01-19 18:36:13 -08005467 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5468 // If an insert effect is idle and input buffer is different from output buffer,
5469 // accumulate input onto output
Mathias Agopian65ab4712010-07-14 17:59:35 -07005470 sp<EffectChain> chain = mChain.promote();
Eric Laurentb469b942011-05-09 12:09:06 -07005471 if (chain != 0 && chain->activeTrackCnt() != 0) {
Eric Laurent73337482011-01-19 18:36:13 -08005472 size_t frameCnt = mConfig.inputCfg.buffer.frameCount * 2; //always stereo here
5473 int16_t *in = mConfig.inputCfg.buffer.s16;
5474 int16_t *out = mConfig.outputCfg.buffer.s16;
5475 for (size_t i = 0; i < frameCnt; i++) {
5476 out[i] = clamp16((int32_t)out[i] + (int32_t)in[i]);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005477 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07005478 }
5479 }
5480}
5481
5482void AudioFlinger::EffectModule::reset_l()
5483{
5484 if (mEffectInterface == NULL) {
5485 return;
5486 }
5487 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5488}
5489
5490status_t AudioFlinger::EffectModule::configure()
5491{
5492 uint32_t channels;
5493 if (mEffectInterface == NULL) {
5494 return NO_INIT;
5495 }
5496
5497 sp<ThreadBase> thread = mThread.promote();
5498 if (thread == 0) {
5499 return DEAD_OBJECT;
5500 }
5501
5502 // TODO: handle configuration of effects replacing track process
5503 if (thread->channelCount() == 1) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005504 channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005505 } else {
Eric Laurente1315cf2011-05-17 19:16:02 -07005506 channels = AUDIO_CHANNEL_OUT_STEREO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005507 }
5508
5509 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
Eric Laurente1315cf2011-05-17 19:16:02 -07005510 mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005511 } else {
5512 mConfig.inputCfg.channels = channels;
5513 }
5514 mConfig.outputCfg.channels = channels;
Eric Laurente1315cf2011-05-17 19:16:02 -07005515 mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
5516 mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005517 mConfig.inputCfg.samplingRate = thread->sampleRate();
5518 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5519 mConfig.inputCfg.bufferProvider.cookie = NULL;
5520 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5521 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5522 mConfig.outputCfg.bufferProvider.cookie = NULL;
5523 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5524 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5525 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5526 // Insert effect:
Dima Zavinfce7a472011-04-19 22:30:36 -07005527 // - in session AUDIO_SESSION_OUTPUT_MIX or AUDIO_SESSION_OUTPUT_STAGE,
Eric Laurentde070132010-07-13 04:45:46 -07005528 // always overwrites output buffer: input buffer == output buffer
Mathias Agopian65ab4712010-07-14 17:59:35 -07005529 // - in other sessions:
5530 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5531 // other effect: overwrites output buffer: input buffer == output buffer
5532 // Auxiliary effect:
5533 // accumulates in output buffer: input buffer != output buffer
5534 // Therefore: accumulate <=> input buffer != output buffer
5535 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5536 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5537 } else {
5538 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5539 }
5540 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5541 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5542 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5543 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5544
Eric Laurentde070132010-07-13 04:45:46 -07005545 LOGV("configure() %p thread %p buffer %p framecount %d",
5546 this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
5547
Mathias Agopian65ab4712010-07-14 17:59:35 -07005548 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005549 uint32_t size = sizeof(int);
5550 status_t status = (*mEffectInterface)->command(mEffectInterface,
5551 EFFECT_CMD_CONFIGURE,
5552 sizeof(effect_config_t),
5553 &mConfig,
5554 &size,
5555 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005556 if (status == 0) {
5557 status = cmdStatus;
5558 }
5559
5560 mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) /
5561 (1000 * mConfig.outputCfg.buffer.frameCount);
5562
5563 return status;
5564}
5565
5566status_t AudioFlinger::EffectModule::init()
5567{
5568 Mutex::Autolock _l(mLock);
5569 if (mEffectInterface == NULL) {
5570 return NO_INIT;
5571 }
5572 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005573 uint32_t size = sizeof(status_t);
5574 status_t status = (*mEffectInterface)->command(mEffectInterface,
5575 EFFECT_CMD_INIT,
5576 0,
5577 NULL,
5578 &size,
5579 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005580 if (status == 0) {
5581 status = cmdStatus;
5582 }
5583 return status;
5584}
5585
5586status_t AudioFlinger::EffectModule::start_l()
5587{
5588 if (mEffectInterface == NULL) {
5589 return NO_INIT;
5590 }
5591 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005592 uint32_t size = sizeof(status_t);
5593 status_t status = (*mEffectInterface)->command(mEffectInterface,
5594 EFFECT_CMD_ENABLE,
5595 0,
5596 NULL,
5597 &size,
5598 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005599 if (status == 0) {
5600 status = cmdStatus;
5601 }
5602 return status;
5603}
5604
5605status_t AudioFlinger::EffectModule::stop_l()
5606{
5607 if (mEffectInterface == NULL) {
5608 return NO_INIT;
5609 }
5610 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005611 uint32_t size = sizeof(status_t);
5612 status_t status = (*mEffectInterface)->command(mEffectInterface,
5613 EFFECT_CMD_DISABLE,
5614 0,
5615 NULL,
5616 &size,
5617 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005618 if (status == 0) {
5619 status = cmdStatus;
5620 }
5621 return status;
5622}
5623
Eric Laurent25f43952010-07-28 05:40:18 -07005624status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
5625 uint32_t cmdSize,
5626 void *pCmdData,
5627 uint32_t *replySize,
5628 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005629{
5630 Mutex::Autolock _l(mLock);
5631// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5632
5633 if (mEffectInterface == NULL) {
5634 return NO_INIT;
5635 }
Eric Laurent25f43952010-07-28 05:40:18 -07005636 status_t status = (*mEffectInterface)->command(mEffectInterface,
5637 cmdCode,
5638 cmdSize,
5639 pCmdData,
5640 replySize,
5641 pReplyData);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005642 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
Eric Laurent25f43952010-07-28 05:40:18 -07005643 uint32_t size = (replySize == NULL) ? 0 : *replySize;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005644 for (size_t i = 1; i < mHandles.size(); i++) {
5645 sp<EffectHandle> h = mHandles[i].promote();
5646 if (h != 0) {
5647 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5648 }
5649 }
5650 }
5651 return status;
5652}
5653
5654status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5655{
5656 Mutex::Autolock _l(mLock);
5657 LOGV("setEnabled %p enabled %d", this, enabled);
5658
5659 if (enabled != isEnabled()) {
5660 switch (mState) {
5661 // going from disabled to enabled
5662 case IDLE:
5663 mState = STARTING;
5664 break;
5665 case STOPPED:
5666 mState = RESTART;
5667 break;
5668 case STOPPING:
5669 mState = ACTIVE;
5670 break;
5671
5672 // going from enabled to disabled
5673 case RESTART:
Eric Laurent8f45bd72010-08-31 13:50:07 -07005674 mState = STOPPED;
5675 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07005676 case STARTING:
5677 mState = IDLE;
5678 break;
5679 case ACTIVE:
5680 mState = STOPPING;
5681 break;
5682 }
5683 for (size_t i = 1; i < mHandles.size(); i++) {
5684 sp<EffectHandle> h = mHandles[i].promote();
5685 if (h != 0) {
5686 h->setEnabled(enabled);
5687 }
5688 }
5689 }
5690 return NO_ERROR;
5691}
5692
5693bool AudioFlinger::EffectModule::isEnabled()
5694{
5695 switch (mState) {
5696 case RESTART:
5697 case STARTING:
5698 case ACTIVE:
5699 return true;
5700 case IDLE:
5701 case STOPPING:
5702 case STOPPED:
5703 default:
5704 return false;
5705 }
5706}
5707
Eric Laurent8f45bd72010-08-31 13:50:07 -07005708bool AudioFlinger::EffectModule::isProcessEnabled()
5709{
5710 switch (mState) {
5711 case RESTART:
5712 case ACTIVE:
5713 case STOPPING:
5714 case STOPPED:
5715 return true;
5716 case IDLE:
5717 case STARTING:
5718 default:
5719 return false;
5720 }
5721}
5722
Mathias Agopian65ab4712010-07-14 17:59:35 -07005723status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5724{
5725 Mutex::Autolock _l(mLock);
5726 status_t status = NO_ERROR;
5727
5728 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5729 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
Eric Laurent8f45bd72010-08-31 13:50:07 -07005730 if (isProcessEnabled() &&
Eric Laurentf997cab2010-07-19 06:24:46 -07005731 ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL ||
5732 (mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_IND)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005733 status_t cmdStatus;
5734 uint32_t volume[2];
5735 uint32_t *pVolume = NULL;
Eric Laurent25f43952010-07-28 05:40:18 -07005736 uint32_t size = sizeof(volume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005737 volume[0] = *left;
5738 volume[1] = *right;
5739 if (controller) {
5740 pVolume = volume;
5741 }
Eric Laurent25f43952010-07-28 05:40:18 -07005742 status = (*mEffectInterface)->command(mEffectInterface,
5743 EFFECT_CMD_SET_VOLUME,
5744 size,
5745 volume,
5746 &size,
5747 pVolume);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005748 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5749 *left = volume[0];
5750 *right = volume[1];
5751 }
5752 }
5753 return status;
5754}
5755
5756status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5757{
5758 Mutex::Autolock _l(mLock);
5759 status_t status = NO_ERROR;
5760 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005761 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005762 uint32_t size = sizeof(status_t);
5763 status = (*mEffectInterface)->command(mEffectInterface,
5764 EFFECT_CMD_SET_DEVICE,
5765 sizeof(uint32_t),
5766 &device,
5767 &size,
5768 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005769 if (status == NO_ERROR) {
5770 status = cmdStatus;
5771 }
5772 }
5773 return status;
5774}
5775
5776status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
5777{
5778 Mutex::Autolock _l(mLock);
5779 status_t status = NO_ERROR;
5780 if ((mDescriptor.flags & EFFECT_FLAG_AUDIO_MODE_MASK) == EFFECT_FLAG_AUDIO_MODE_IND) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07005781 status_t cmdStatus;
Eric Laurent25f43952010-07-28 05:40:18 -07005782 uint32_t size = sizeof(status_t);
5783 status = (*mEffectInterface)->command(mEffectInterface,
5784 EFFECT_CMD_SET_AUDIO_MODE,
5785 sizeof(int),
Eric Laurente1315cf2011-05-17 19:16:02 -07005786 &mode,
Eric Laurent25f43952010-07-28 05:40:18 -07005787 &size,
5788 &cmdStatus);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005789 if (status == NO_ERROR) {
5790 status = cmdStatus;
5791 }
5792 }
5793 return status;
5794}
5795
Mathias Agopian65ab4712010-07-14 17:59:35 -07005796status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5797{
5798 const size_t SIZE = 256;
5799 char buffer[SIZE];
5800 String8 result;
5801
5802 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5803 result.append(buffer);
5804
5805 bool locked = tryLock(mLock);
5806 // failed to lock - AudioFlinger is probably deadlocked
5807 if (!locked) {
5808 result.append("\t\tCould not lock Fx mutex:\n");
5809 }
5810
5811 result.append("\t\tSession Status State Engine:\n");
5812 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5813 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5814 result.append(buffer);
5815
5816 result.append("\t\tDescriptor:\n");
5817 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5818 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5819 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5820 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5821 result.append(buffer);
5822 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5823 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5824 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5825 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5826 result.append(buffer);
Eric Laurente1315cf2011-05-17 19:16:02 -07005827 snprintf(buffer, SIZE, "\t\t- apiVersion: %08X\n\t\t- flags: %08X\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07005828 mDescriptor.apiVersion,
5829 mDescriptor.flags);
5830 result.append(buffer);
5831 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5832 mDescriptor.name);
5833 result.append(buffer);
5834 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5835 mDescriptor.implementor);
5836 result.append(buffer);
5837
5838 result.append("\t\t- Input configuration:\n");
5839 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5840 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5841 (uint32_t)mConfig.inputCfg.buffer.raw,
5842 mConfig.inputCfg.buffer.frameCount,
5843 mConfig.inputCfg.samplingRate,
5844 mConfig.inputCfg.channels,
5845 mConfig.inputCfg.format);
5846 result.append(buffer);
5847
5848 result.append("\t\t- Output configuration:\n");
5849 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5850 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5851 (uint32_t)mConfig.outputCfg.buffer.raw,
5852 mConfig.outputCfg.buffer.frameCount,
5853 mConfig.outputCfg.samplingRate,
5854 mConfig.outputCfg.channels,
5855 mConfig.outputCfg.format);
5856 result.append(buffer);
5857
5858 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5859 result.append(buffer);
5860 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5861 for (size_t i = 0; i < mHandles.size(); ++i) {
5862 sp<EffectHandle> handle = mHandles[i].promote();
5863 if (handle != 0) {
5864 handle->dump(buffer, SIZE);
5865 result.append(buffer);
5866 }
5867 }
5868
5869 result.append("\n");
5870
5871 write(fd, result.string(), result.length());
5872
5873 if (locked) {
5874 mLock.unlock();
5875 }
5876
5877 return NO_ERROR;
5878}
5879
5880// ----------------------------------------------------------------------------
5881// EffectHandle implementation
5882// ----------------------------------------------------------------------------
5883
5884#undef LOG_TAG
5885#define LOG_TAG "AudioFlinger::EffectHandle"
5886
5887AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5888 const sp<AudioFlinger::Client>& client,
5889 const sp<IEffectClient>& effectClient,
5890 int32_t priority)
5891 : BnEffect(),
5892 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5893{
5894 LOGV("constructor %p", this);
5895
5896 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5897 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5898 if (mCblkMemory != 0) {
5899 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5900
5901 if (mCblk) {
5902 new(mCblk) effect_param_cblk_t();
5903 mBuffer = (uint8_t *)mCblk + bufOffset;
5904 }
5905 } else {
5906 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5907 return;
5908 }
5909}
5910
5911AudioFlinger::EffectHandle::~EffectHandle()
5912{
5913 LOGV("Destructor %p", this);
5914 disconnect();
5915}
5916
5917status_t AudioFlinger::EffectHandle::enable()
5918{
5919 if (!mHasControl) return INVALID_OPERATION;
5920 if (mEffect == 0) return DEAD_OBJECT;
5921
5922 return mEffect->setEnabled(true);
5923}
5924
5925status_t AudioFlinger::EffectHandle::disable()
5926{
5927 if (!mHasControl) return INVALID_OPERATION;
5928 if (mEffect == NULL) return DEAD_OBJECT;
5929
5930 return mEffect->setEnabled(false);
5931}
5932
5933void AudioFlinger::EffectHandle::disconnect()
5934{
5935 if (mEffect == 0) {
5936 return;
5937 }
5938 mEffect->disconnect(this);
5939 // release sp on module => module destructor can be called now
5940 mEffect.clear();
5941 if (mCblk) {
5942 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5943 }
5944 mCblkMemory.clear(); // and free the shared memory
5945 if (mClient != 0) {
5946 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5947 mClient.clear();
5948 }
5949}
5950
Eric Laurent25f43952010-07-28 05:40:18 -07005951status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
5952 uint32_t cmdSize,
5953 void *pCmdData,
5954 uint32_t *replySize,
5955 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07005956{
Eric Laurent25f43952010-07-28 05:40:18 -07005957// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
5958// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005959
5960 // only get parameter command is permitted for applications not controlling the effect
5961 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5962 return INVALID_OPERATION;
5963 }
5964 if (mEffect == 0) return DEAD_OBJECT;
5965
5966 // handle commands that are not forwarded transparently to effect engine
5967 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5968 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5969 // no risk to block the whole media server process or mixer threads is we are stuck here
5970 Mutex::Autolock _l(mCblk->lock);
5971 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5972 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5973 mCblk->serverIndex = 0;
5974 mCblk->clientIndex = 0;
5975 return BAD_VALUE;
5976 }
5977 status_t status = NO_ERROR;
5978 while (mCblk->serverIndex < mCblk->clientIndex) {
5979 int reply;
Eric Laurent25f43952010-07-28 05:40:18 -07005980 uint32_t rsize = sizeof(int);
Mathias Agopian65ab4712010-07-14 17:59:35 -07005981 int *p = (int *)(mBuffer + mCblk->serverIndex);
5982 int size = *p++;
5983 if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
5984 LOGW("command(): invalid parameter block size");
5985 break;
5986 }
5987 effect_param_t *param = (effect_param_t *)p;
5988 if (param->psize == 0 || param->vsize == 0) {
5989 LOGW("command(): null parameter or value size");
5990 mCblk->serverIndex += size;
5991 continue;
5992 }
Eric Laurent25f43952010-07-28 05:40:18 -07005993 uint32_t psize = sizeof(effect_param_t) +
5994 ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
5995 param->vsize;
5996 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
5997 psize,
5998 p,
5999 &rsize,
6000 &reply);
Eric Laurentaeae3de2010-09-02 11:56:55 -07006001 // stop at first error encountered
6002 if (ret != NO_ERROR) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006003 status = ret;
Eric Laurentaeae3de2010-09-02 11:56:55 -07006004 *(int *)pReplyData = reply;
6005 break;
6006 } else if (reply != NO_ERROR) {
6007 *(int *)pReplyData = reply;
6008 break;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006009 }
6010 mCblk->serverIndex += size;
6011 }
6012 mCblk->serverIndex = 0;
6013 mCblk->clientIndex = 0;
6014 return status;
6015 } else if (cmdCode == EFFECT_CMD_ENABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006016 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006017 return enable();
6018 } else if (cmdCode == EFFECT_CMD_DISABLE) {
Eric Laurentaeae3de2010-09-02 11:56:55 -07006019 *(int *)pReplyData = NO_ERROR;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006020 return disable();
6021 }
6022
6023 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6024}
6025
6026sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
6027 return mCblkMemory;
6028}
6029
6030void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
6031{
6032 LOGV("setControl %p control %d", this, hasControl);
6033
6034 mHasControl = hasControl;
6035 if (signal && mEffectClient != 0) {
6036 mEffectClient->controlStatusChanged(hasControl);
6037 }
6038}
6039
Eric Laurent25f43952010-07-28 05:40:18 -07006040void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
6041 uint32_t cmdSize,
6042 void *pCmdData,
6043 uint32_t replySize,
6044 void *pReplyData)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006045{
6046 if (mEffectClient != 0) {
6047 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
6048 }
6049}
6050
6051
6052
6053void AudioFlinger::EffectHandle::setEnabled(bool enabled)
6054{
6055 if (mEffectClient != 0) {
6056 mEffectClient->enableStatusChanged(enabled);
6057 }
6058}
6059
6060status_t AudioFlinger::EffectHandle::onTransact(
6061 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6062{
6063 return BnEffect::onTransact(code, data, reply, flags);
6064}
6065
6066
6067void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
6068{
6069 bool locked = tryLock(mCblk->lock);
6070
6071 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
6072 (mClient == NULL) ? getpid() : mClient->pid(),
6073 mPriority,
6074 mHasControl,
6075 !locked,
6076 mCblk->clientIndex,
6077 mCblk->serverIndex
6078 );
6079
6080 if (locked) {
6081 mCblk->lock.unlock();
6082 }
6083}
6084
6085#undef LOG_TAG
6086#define LOG_TAG "AudioFlinger::EffectChain"
6087
6088AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
6089 int sessionId)
Eric Laurentb469b942011-05-09 12:09:06 -07006090 : mThread(wThread), mSessionId(sessionId), mActiveTrackCnt(0), mTrackCnt(0),
6091 mOwnInBuffer(false), mVolumeCtrlIdx(-1), mLeftVolume(UINT_MAX), mRightVolume(UINT_MAX),
6092 mNewLeftVolume(UINT_MAX), mNewRightVolume(UINT_MAX)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093{
Dima Zavinfce7a472011-04-19 22:30:36 -07006094 mStrategy = AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095}
6096
6097AudioFlinger::EffectChain::~EffectChain()
6098{
6099 if (mOwnInBuffer) {
6100 delete mInBuffer;
6101 }
6102
6103}
6104
Eric Laurentcab11242010-07-15 12:50:15 -07006105// getEffectFromDesc_l() must be called with PlaybackThread::mLock held
6106sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc_l(effect_descriptor_t *descriptor)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006107{
6108 sp<EffectModule> effect;
6109 size_t size = mEffects.size();
6110
6111 for (size_t i = 0; i < size; i++) {
6112 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
6113 effect = mEffects[i];
6114 break;
6115 }
6116 }
6117 return effect;
6118}
6119
Eric Laurentcab11242010-07-15 12:50:15 -07006120// getEffectFromId_l() must be called with PlaybackThread::mLock held
6121sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId_l(int id)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006122{
6123 sp<EffectModule> effect;
6124 size_t size = mEffects.size();
6125
6126 for (size_t i = 0; i < size; i++) {
Eric Laurentde070132010-07-13 04:45:46 -07006127 // by convention, return first effect if id provided is 0 (0 is never a valid id)
6128 if (id == 0 || mEffects[i]->id() == id) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006129 effect = mEffects[i];
6130 break;
6131 }
6132 }
6133 return effect;
6134}
6135
6136// Must be called with EffectChain::mLock locked
6137void AudioFlinger::EffectChain::process_l()
6138{
Eric Laurentdac69112010-09-28 14:09:57 -07006139 sp<ThreadBase> thread = mThread.promote();
6140 if (thread == 0) {
6141 LOGW("process_l(): cannot promote mixer thread");
6142 return;
6143 }
6144 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
Dima Zavinfce7a472011-04-19 22:30:36 -07006145 bool isGlobalSession = (mSessionId == AUDIO_SESSION_OUTPUT_MIX) ||
6146 (mSessionId == AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentdac69112010-09-28 14:09:57 -07006147 bool tracksOnSession = false;
6148 if (!isGlobalSession) {
Eric Laurentb469b942011-05-09 12:09:06 -07006149 tracksOnSession = (trackCnt() != 0);
6150 }
6151
6152 // if no track is active, input buffer must be cleared here as the mixer process
6153 // will not do it
6154 if (tracksOnSession &&
6155 activeTrackCnt() == 0) {
6156 size_t numSamples = playbackThread->frameCount() * playbackThread->channelCount();
6157 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
Eric Laurentdac69112010-09-28 14:09:57 -07006158 }
6159
Mathias Agopian65ab4712010-07-14 17:59:35 -07006160 size_t size = mEffects.size();
Eric Laurentdac69112010-09-28 14:09:57 -07006161 // do not process effect if no track is present in same audio session
6162 if (isGlobalSession || tracksOnSession) {
6163 for (size_t i = 0; i < size; i++) {
6164 mEffects[i]->process();
6165 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006166 }
6167 for (size_t i = 0; i < size; i++) {
6168 mEffects[i]->updateState();
6169 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006170}
6171
Eric Laurentcab11242010-07-15 12:50:15 -07006172// addEffect_l() must be called with PlaybackThread::mLock held
Eric Laurentde070132010-07-13 04:45:46 -07006173status_t AudioFlinger::EffectChain::addEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006174{
6175 effect_descriptor_t desc = effect->desc();
6176 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
6177
6178 Mutex::Autolock _l(mLock);
Eric Laurentde070132010-07-13 04:45:46 -07006179 effect->setChain(this);
6180 sp<ThreadBase> thread = mThread.promote();
6181 if (thread == 0) {
6182 return NO_INIT;
6183 }
6184 effect->setThread(thread);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006185
6186 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
6187 // Auxiliary effects are inserted at the beginning of mEffects vector as
6188 // they are processed first and accumulated in chain input buffer
6189 mEffects.insertAt(effect, 0);
Eric Laurentde070132010-07-13 04:45:46 -07006190
Mathias Agopian65ab4712010-07-14 17:59:35 -07006191 // the input buffer for auxiliary effect contains mono samples in
6192 // 32 bit format. This is to avoid saturation in AudoMixer
6193 // accumulation stage. Saturation is done in EffectModule::process() before
6194 // calling the process in effect engine
6195 size_t numSamples = thread->frameCount();
6196 int32_t *buffer = new int32_t[numSamples];
6197 memset(buffer, 0, numSamples * sizeof(int32_t));
6198 effect->setInBuffer((int16_t *)buffer);
6199 // auxiliary effects output samples to chain input buffer for further processing
6200 // by insert effects
6201 effect->setOutBuffer(mInBuffer);
6202 } else {
6203 // Insert effects are inserted at the end of mEffects vector as they are processed
6204 // after track and auxiliary effects.
6205 // Insert effect order as a function of indicated preference:
6206 // if EFFECT_FLAG_INSERT_EXCLUSIVE, insert in first position or reject if
6207 // another effect is present
6208 // else if EFFECT_FLAG_INSERT_FIRST, insert in first position or after the
6209 // last effect claiming first position
6210 // else if EFFECT_FLAG_INSERT_LAST, insert in last position or before the
6211 // first effect claiming last position
6212 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
6213 // Reject insertion if an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is
6214 // already present
6215
6216 int size = (int)mEffects.size();
6217 int idx_insert = size;
6218 int idx_insert_first = -1;
6219 int idx_insert_last = -1;
6220
6221 for (int i = 0; i < size; i++) {
6222 effect_descriptor_t d = mEffects[i]->desc();
6223 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
6224 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
6225 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
6226 // check invalid effect chaining combinations
6227 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
6228 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE) {
Eric Laurentcab11242010-07-15 12:50:15 -07006229 LOGW("addEffect_l() could not insert effect %s: exclusive conflict with %s", desc.name, d.name);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006230 return INVALID_OPERATION;
6231 }
6232 // remember position of first insert effect and by default
6233 // select this as insert position for new effect
6234 if (idx_insert == size) {
6235 idx_insert = i;
6236 }
6237 // remember position of last insert effect claiming
6238 // first position
6239 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
6240 idx_insert_first = i;
6241 }
6242 // remember position of first insert effect claiming
6243 // last position
6244 if (iPref == EFFECT_FLAG_INSERT_LAST &&
6245 idx_insert_last == -1) {
6246 idx_insert_last = i;
6247 }
6248 }
6249 }
6250
6251 // modify idx_insert from first position if needed
6252 if (insertPref == EFFECT_FLAG_INSERT_LAST) {
6253 if (idx_insert_last != -1) {
6254 idx_insert = idx_insert_last;
6255 } else {
6256 idx_insert = size;
6257 }
6258 } else {
6259 if (idx_insert_first != -1) {
6260 idx_insert = idx_insert_first + 1;
6261 }
6262 }
6263
6264 // always read samples from chain input buffer
6265 effect->setInBuffer(mInBuffer);
6266
6267 // if last effect in the chain, output samples to chain
6268 // output buffer, otherwise to chain input buffer
6269 if (idx_insert == size) {
6270 if (idx_insert != 0) {
6271 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
6272 mEffects[idx_insert-1]->configure();
6273 }
6274 effect->setOutBuffer(mOutBuffer);
6275 } else {
6276 effect->setOutBuffer(mInBuffer);
6277 }
6278 mEffects.insertAt(effect, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006279
Eric Laurentcab11242010-07-15 12:50:15 -07006280 LOGV("addEffect_l() effect %p, added in chain %p at rank %d", effect.get(), this, idx_insert);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006281 }
6282 effect->configure();
6283 return NO_ERROR;
6284}
6285
Eric Laurentcab11242010-07-15 12:50:15 -07006286// removeEffect_l() must be called with PlaybackThread::mLock held
6287size_t AudioFlinger::EffectChain::removeEffect_l(const sp<EffectModule>& effect)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006288{
6289 Mutex::Autolock _l(mLock);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006290 int size = (int)mEffects.size();
6291 int i;
6292 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
6293
6294 for (i = 0; i < size; i++) {
6295 if (effect == mEffects[i]) {
6296 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
6297 delete[] effect->inBuffer();
6298 } else {
6299 if (i == size - 1 && i != 0) {
6300 mEffects[i - 1]->setOutBuffer(mOutBuffer);
6301 mEffects[i - 1]->configure();
6302 }
6303 }
6304 mEffects.removeAt(i);
Eric Laurentcab11242010-07-15 12:50:15 -07006305 LOGV("removeEffect_l() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
Mathias Agopian65ab4712010-07-14 17:59:35 -07006306 break;
6307 }
6308 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07006309
6310 return mEffects.size();
6311}
6312
Eric Laurentcab11242010-07-15 12:50:15 -07006313// setDevice_l() must be called with PlaybackThread::mLock held
6314void AudioFlinger::EffectChain::setDevice_l(uint32_t device)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006315{
6316 size_t size = mEffects.size();
6317 for (size_t i = 0; i < size; i++) {
6318 mEffects[i]->setDevice(device);
6319 }
6320}
6321
Eric Laurentcab11242010-07-15 12:50:15 -07006322// setMode_l() must be called with PlaybackThread::mLock held
6323void AudioFlinger::EffectChain::setMode_l(uint32_t mode)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006324{
6325 size_t size = mEffects.size();
6326 for (size_t i = 0; i < size; i++) {
6327 mEffects[i]->setMode(mode);
6328 }
6329}
6330
Eric Laurentcab11242010-07-15 12:50:15 -07006331// setVolume_l() must be called with PlaybackThread::mLock held
6332bool AudioFlinger::EffectChain::setVolume_l(uint32_t *left, uint32_t *right)
Mathias Agopian65ab4712010-07-14 17:59:35 -07006333{
6334 uint32_t newLeft = *left;
6335 uint32_t newRight = *right;
6336 bool hasControl = false;
Eric Laurentcab11242010-07-15 12:50:15 -07006337 int ctrlIdx = -1;
6338 size_t size = mEffects.size();
Mathias Agopian65ab4712010-07-14 17:59:35 -07006339
Eric Laurentcab11242010-07-15 12:50:15 -07006340 // first update volume controller
6341 for (size_t i = size; i > 0; i--) {
Eric Laurent8f45bd72010-08-31 13:50:07 -07006342 if (mEffects[i - 1]->isProcessEnabled() &&
Eric Laurentcab11242010-07-15 12:50:15 -07006343 (mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) == EFFECT_FLAG_VOLUME_CTRL) {
6344 ctrlIdx = i - 1;
Eric Laurentf997cab2010-07-19 06:24:46 -07006345 hasControl = true;
Eric Laurentcab11242010-07-15 12:50:15 -07006346 break;
6347 }
6348 }
6349
6350 if (ctrlIdx == mVolumeCtrlIdx && *left == mLeftVolume && *right == mRightVolume) {
Eric Laurentf997cab2010-07-19 06:24:46 -07006351 if (hasControl) {
6352 *left = mNewLeftVolume;
6353 *right = mNewRightVolume;
6354 }
6355 return hasControl;
Eric Laurentcab11242010-07-15 12:50:15 -07006356 }
6357
6358 mVolumeCtrlIdx = ctrlIdx;
Eric Laurentf997cab2010-07-19 06:24:46 -07006359 mLeftVolume = newLeft;
6360 mRightVolume = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006361
6362 // second get volume update from volume controller
6363 if (ctrlIdx >= 0) {
6364 mEffects[ctrlIdx]->setVolume(&newLeft, &newRight, true);
Eric Laurentf997cab2010-07-19 06:24:46 -07006365 mNewLeftVolume = newLeft;
6366 mNewRightVolume = newRight;
Mathias Agopian65ab4712010-07-14 17:59:35 -07006367 }
6368 // then indicate volume to all other effects in chain.
6369 // Pass altered volume to effects before volume controller
6370 // and requested volume to effects after controller
6371 uint32_t lVol = newLeft;
6372 uint32_t rVol = newRight;
Eric Laurentcab11242010-07-15 12:50:15 -07006373
Mathias Agopian65ab4712010-07-14 17:59:35 -07006374 for (size_t i = 0; i < size; i++) {
Eric Laurentcab11242010-07-15 12:50:15 -07006375 if ((int)i == ctrlIdx) continue;
6376 // this also works for ctrlIdx == -1 when there is no volume controller
6377 if ((int)i > ctrlIdx) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07006378 lVol = *left;
6379 rVol = *right;
6380 }
6381 mEffects[i]->setVolume(&lVol, &rVol, false);
6382 }
6383 *left = newLeft;
6384 *right = newRight;
6385
6386 return hasControl;
6387}
6388
Mathias Agopian65ab4712010-07-14 17:59:35 -07006389status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
6390{
6391 const size_t SIZE = 256;
6392 char buffer[SIZE];
6393 String8 result;
6394
6395 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
6396 result.append(buffer);
6397
6398 bool locked = tryLock(mLock);
6399 // failed to lock - AudioFlinger is probably deadlocked
6400 if (!locked) {
6401 result.append("\tCould not lock mutex:\n");
6402 }
6403
Eric Laurentcab11242010-07-15 12:50:15 -07006404 result.append("\tNum fx In buffer Out buffer Active tracks:\n");
6405 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %d\n",
Mathias Agopian65ab4712010-07-14 17:59:35 -07006406 mEffects.size(),
6407 (uint32_t)mInBuffer,
6408 (uint32_t)mOutBuffer,
Mathias Agopian65ab4712010-07-14 17:59:35 -07006409 mActiveTrackCnt);
6410 result.append(buffer);
6411 write(fd, result.string(), result.size());
6412
6413 for (size_t i = 0; i < mEffects.size(); ++i) {
6414 sp<EffectModule> effect = mEffects[i];
6415 if (effect != 0) {
6416 effect->dump(fd, args);
6417 }
6418 }
6419
6420 if (locked) {
6421 mLock.unlock();
6422 }
6423
6424 return NO_ERROR;
6425}
6426
6427#undef LOG_TAG
6428#define LOG_TAG "AudioFlinger"
6429
6430// ----------------------------------------------------------------------------
6431
6432status_t AudioFlinger::onTransact(
6433 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
6434{
6435 return BnAudioFlinger::onTransact(code, data, reply, flags);
6436}
6437
Mathias Agopian65ab4712010-07-14 17:59:35 -07006438}; // namespace android