blob: 1860793d9fffcf974969f6450a740f354c50d84b [file] [log] [blame]
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -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
Mathias Agopian07952722009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
Eric Laurent65b65452010-06-01 23:49:17 -070040#include <private/media/AudioEffectShared.h>
The Android Open Source Project9266c552009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
Glenn Kasten871c16c2010-03-05 12:18:01 -080050#ifdef LVMX
51#include "lifevibes.h"
52#endif
53
Eric Laurent65b65452010-06-01 23:49:17 -070054#include <media/EffectFactoryApi.h>
55
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056// ----------------------------------------------------------------------------
57// the sim build doesn't have gettid
58
59#ifndef HAVE_GETTID
60# define gettid getpid
61#endif
62
63// ----------------------------------------------------------------------------
64
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070065namespace android {
66
The Android Open Source Project10592532009-03-18 17:39:46 -070067static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
68static const char* kHardwareLockedString = "Hardware lock is taken\n";
69
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080070//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070071static const float MAX_GAIN = 4096.0f;
Eric Laurent65b65452010-06-01 23:49:17 -070072static const float MAX_GAIN_INT = 0x1000;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070073
74// retry counts for buffer fill timeout
75// 50 * ~20msecs = 1 second
76static const int8_t kMaxTrackRetries = 50;
77static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080078// 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;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070082
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070083static const int kDumpLockRetries = 50;
84static const int kDumpLockSleep = 20000;
85
Dave Sparksd0ac8c02009-09-30 03:09:03 -070086static const nsecs_t kWarningThrottle = seconds(5);
87
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070089#define AUDIOFLINGER_SECURITY_ENABLED 1
90
91// ----------------------------------------------------------------------------
92
93static bool recordingAllowed() {
94#ifndef HAVE_ANDROID_OS
95 return true;
96#endif
97#if AUDIOFLINGER_SECURITY_ENABLED
98 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
99 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
100 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
101 return ok;
102#else
103 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
104 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
105 return true;
106#endif
107}
108
109static bool settingsAllowed() {
110#ifndef HAVE_ANDROID_OS
111 return true;
112#endif
113#if AUDIOFLINGER_SECURITY_ENABLED
114 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
115 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
116 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
117 return ok;
118#else
119 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
120 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
121 return true;
122#endif
123}
124
125// ----------------------------------------------------------------------------
126
127AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 : BnAudioFlinger(),
Eric Laurent65b65452010-06-01 23:49:17 -0700129 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextUniqueId(1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700130{
131 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700132
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700134
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700135 mHardwareStatus = AUDIO_HW_INIT;
136 if (mAudioHardware->initCheck() == NO_ERROR) {
137 // open 16-bit output stream for s/w mixer
Eric Laurenta553c252009-07-17 12:17:14 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 setMode(AudioSystem::MODE_NORMAL);
140
141 setMasterVolume(1.0f);
142 setMasterMute(false);
Eric Laurenta553c252009-07-17 12:17:14 -0700143 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700144 LOGE("Couldn't even initialize the stubbed audio hardware!");
145 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800146#ifdef LVMX
147 LifeVibes::init();
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700148 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800149#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700150}
151
152AudioFlinger::~AudioFlinger()
153{
Eric Laurent7954c462009-08-28 10:39:03 -0700154 while (!mRecordThreads.isEmpty()) {
155 // closeInput() will remove first entry from mRecordThreads
156 closeInput(mRecordThreads.keyAt(0));
157 }
158 while (!mPlaybackThreads.isEmpty()) {
159 // closeOutput() will remove first entry from mPlaybackThreads
160 closeOutput(mPlaybackThreads.keyAt(0));
161 }
162 if (mAudioHardware) {
163 delete mAudioHardware;
164 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800165}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800166
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700167
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700168
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700169status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
170{
171 const size_t SIZE = 256;
172 char buffer[SIZE];
173 String8 result;
174
175 result.append("Clients:\n");
176 for (size_t i = 0; i < mClients.size(); ++i) {
177 wp<Client> wClient = mClients.valueAt(i);
178 if (wClient != 0) {
179 sp<Client> client = wClient.promote();
180 if (client != 0) {
181 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
182 result.append(buffer);
183 }
184 }
185 }
186 write(fd, result.string(), result.size());
187 return NO_ERROR;
188}
189
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700190
191status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
192{
193 const size_t SIZE = 256;
194 char buffer[SIZE];
195 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700196 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700197
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700198 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700199 result.append(buffer);
200 write(fd, result.string(), result.size());
201 return NO_ERROR;
202}
203
204status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
205{
206 const size_t SIZE = 256;
207 char buffer[SIZE];
208 String8 result;
209 snprintf(buffer, SIZE, "Permission Denial: "
210 "can't dump AudioFlinger from pid=%d, uid=%d\n",
211 IPCThreadState::self()->getCallingPid(),
212 IPCThreadState::self()->getCallingUid());
213 result.append(buffer);
214 write(fd, result.string(), result.size());
215 return NO_ERROR;
216}
217
The Android Open Source Project10592532009-03-18 17:39:46 -0700218static bool tryLock(Mutex& mutex)
219{
220 bool locked = false;
221 for (int i = 0; i < kDumpLockRetries; ++i) {
222 if (mutex.tryLock() == NO_ERROR) {
223 locked = true;
224 break;
225 }
226 usleep(kDumpLockSleep);
227 }
228 return locked;
229}
230
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700231status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
232{
233 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
234 dumpPermissionDenial(fd, args);
235 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700236 // get state of hardware lock
237 bool hardwareLocked = tryLock(mHardwareLock);
238 if (!hardwareLocked) {
239 String8 result(kHardwareLockedString);
240 write(fd, result.string(), result.size());
241 } else {
242 mHardwareLock.unlock();
243 }
244
245 bool locked = tryLock(mLock);
246
247 // failed to lock - AudioFlinger is probably deadlocked
248 if (!locked) {
249 String8 result(kDeadlockedString);
250 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700251 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700252
253 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700254 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
Eric Laurenta553c252009-07-17 12:17:14 -0700256 // dump playback threads
257 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700258 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700259 }
260
261 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700262 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700263 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700266 if (mAudioHardware) {
267 mAudioHardware->dumpState(fd, args);
268 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700269 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700270 }
271 return NO_ERROR;
272}
273
Eric Laurenta553c252009-07-17 12:17:14 -0700274
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700275// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276
277
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700278sp<IAudioTrack> AudioFlinger::createTrack(
279 pid_t pid,
280 int streamType,
281 uint32_t sampleRate,
282 int format,
283 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800284 int frameCount,
285 uint32_t flags,
286 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700287 int output,
Eric Laurent65b65452010-06-01 23:49:17 -0700288 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800289 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700290{
Eric Laurenta553c252009-07-17 12:17:14 -0700291 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700292 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700293 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800294 wp<Client> wclient;
295 status_t lStatus;
Eric Laurent65b65452010-06-01 23:49:17 -0700296 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800299 LOGE("invalid stream type");
300 lStatus = BAD_VALUE;
301 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700302 }
303
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800304 {
305 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700306 PlaybackThread *thread = checkPlaybackThread_l(output);
307 if (thread == NULL) {
308 LOGE("unknown output thread");
309 lStatus = BAD_VALUE;
310 goto Exit;
311 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800312
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800313 wclient = mClients.valueFor(pid);
314
315 if (wclient != NULL) {
316 client = wclient.promote();
317 } else {
318 client = new Client(this, pid);
319 mClients.add(pid, client);
320 }
Eric Laurent65b65452010-06-01 23:49:17 -0700321
322 // If no audio session id is provided, create one here
323 // TODO: enforce same stream type for all tracks in same audio session?
324 // TODO: prevent same audio session on different output threads
325 LOGV("createTrack() sessionId: %d", (sessionId == NULL) ? -2 : *sessionId);
326 if (sessionId != NULL && *sessionId != 0) {
327 lSessionId = *sessionId;
328 } else {
329 lSessionId = nextUniqueId();
330 if (sessionId != NULL) {
331 *sessionId = lSessionId;
332 }
333 }
334 LOGV("createTrack() lSessionId: %d", lSessionId);
335
Eric Laurenta553c252009-07-17 12:17:14 -0700336 track = thread->createTrack_l(client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -0700337 channelCount, frameCount, sharedBuffer, lSessionId, &lStatus);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700338 }
339 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800340 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700341 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700342 // remove local strong reference to Client before deleting the Track so that the Client
343 // destructor is called by the TrackBase destructor with mLock held
344 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700345 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800346 }
347
348Exit:
349 if(status) {
350 *status = lStatus;
351 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700352 return trackHandle;
353}
354
Eric Laurentddb78e72009-07-28 08:44:33 -0700355uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700356{
Eric Laurenta553c252009-07-17 12:17:14 -0700357 Mutex::Autolock _l(mLock);
358 PlaybackThread *thread = checkPlaybackThread_l(output);
359 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700360 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700361 return 0;
362 }
363 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700364}
365
Eric Laurentddb78e72009-07-28 08:44:33 -0700366int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700367{
Eric Laurenta553c252009-07-17 12:17:14 -0700368 Mutex::Autolock _l(mLock);
369 PlaybackThread *thread = checkPlaybackThread_l(output);
370 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700371 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700372 return 0;
373 }
374 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700375}
376
Eric Laurentddb78e72009-07-28 08:44:33 -0700377int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378{
Eric Laurenta553c252009-07-17 12:17:14 -0700379 Mutex::Autolock _l(mLock);
380 PlaybackThread *thread = checkPlaybackThread_l(output);
381 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700382 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700383 return 0;
384 }
385 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700386}
387
Eric Laurentddb78e72009-07-28 08:44:33 -0700388size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389{
Eric Laurenta553c252009-07-17 12:17:14 -0700390 Mutex::Autolock _l(mLock);
391 PlaybackThread *thread = checkPlaybackThread_l(output);
392 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700393 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700394 return 0;
395 }
396 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700397}
398
Eric Laurentddb78e72009-07-28 08:44:33 -0700399uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800400{
Eric Laurenta553c252009-07-17 12:17:14 -0700401 Mutex::Autolock _l(mLock);
402 PlaybackThread *thread = checkPlaybackThread_l(output);
403 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700404 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700405 return 0;
406 }
407 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800408}
409
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700410status_t AudioFlinger::setMasterVolume(float value)
411{
412 // check calling permissions
413 if (!settingsAllowed()) {
414 return PERMISSION_DENIED;
415 }
416
417 // when hw supports master volume, don't scale in sw mixer
418 AutoMutex lock(mHardwareLock);
419 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
420 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700422 }
423 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700424
425 mMasterVolume = value;
426 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700427 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700428
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700429 return NO_ERROR;
430}
431
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700432status_t AudioFlinger::setMode(int mode)
433{
434 // check calling permissions
435 if (!settingsAllowed()) {
436 return PERMISSION_DENIED;
437 }
438 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
439 LOGW("Illegal value: setMode(%d)", mode);
440 return BAD_VALUE;
441 }
442
443 AutoMutex lock(mHardwareLock);
444 mHardwareStatus = AUDIO_HW_SET_MODE;
445 status_t ret = mAudioHardware->setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800446#ifdef LVMX
447 if (NO_ERROR == ret) {
448 LifeVibes::setMode(mode);
449 }
450#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700451 mHardwareStatus = AUDIO_HW_IDLE;
452 return ret;
453}
454
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700455status_t AudioFlinger::setMicMute(bool state)
456{
457 // check calling permissions
458 if (!settingsAllowed()) {
459 return PERMISSION_DENIED;
460 }
461
462 AutoMutex lock(mHardwareLock);
463 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
464 status_t ret = mAudioHardware->setMicMute(state);
465 mHardwareStatus = AUDIO_HW_IDLE;
466 return ret;
467}
468
469bool AudioFlinger::getMicMute() const
470{
471 bool state = AudioSystem::MODE_INVALID;
472 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
473 mAudioHardware->getMicMute(&state);
474 mHardwareStatus = AUDIO_HW_IDLE;
475 return state;
476}
477
478status_t AudioFlinger::setMasterMute(bool muted)
479{
480 // check calling permissions
481 if (!settingsAllowed()) {
482 return PERMISSION_DENIED;
483 }
Eric Laurenta553c252009-07-17 12:17:14 -0700484
485 mMasterMute = muted;
486 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700487 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700488
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700489 return NO_ERROR;
490}
491
492float AudioFlinger::masterVolume() const
493{
Eric Laurenta553c252009-07-17 12:17:14 -0700494 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700495}
496
497bool AudioFlinger::masterMute() const
498{
Eric Laurenta553c252009-07-17 12:17:14 -0700499 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700500}
501
Eric Laurentddb78e72009-07-28 08:44:33 -0700502status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700503{
504 // check calling permissions
505 if (!settingsAllowed()) {
506 return PERMISSION_DENIED;
507 }
508
Eric Laurenta553c252009-07-17 12:17:14 -0700509 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700510 return BAD_VALUE;
511 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800512
Eric Laurenta553c252009-07-17 12:17:14 -0700513 AutoMutex lock(mLock);
514 PlaybackThread *thread = NULL;
515 if (output) {
516 thread = checkPlaybackThread_l(output);
517 if (thread == NULL) {
518 return BAD_VALUE;
519 }
520 }
521
Eric Laurenta553c252009-07-17 12:17:14 -0700522 mStreamTypes[stream].volume = value;
523
524 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700525 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700526 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700527 }
Eric Laurenta553c252009-07-17 12:17:14 -0700528 } else {
529 thread->setStreamVolume(stream, value);
530 }
Eric Laurentef028272009-04-21 07:56:33 -0700531
Eric Laurent415f3e22009-10-21 08:14:22 -0700532 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700533}
534
535status_t AudioFlinger::setStreamMute(int stream, bool muted)
536{
537 // check calling permissions
538 if (!settingsAllowed()) {
539 return PERMISSION_DENIED;
540 }
541
Eric Laurenta553c252009-07-17 12:17:14 -0700542 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700543 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700544 return BAD_VALUE;
545 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700546
Eric Laurenta553c252009-07-17 12:17:14 -0700547 mStreamTypes[stream].mute = muted;
548 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700549 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700551 return NO_ERROR;
552}
553
Eric Laurentddb78e72009-07-28 08:44:33 -0700554float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555{
Eric Laurenta553c252009-07-17 12:17:14 -0700556 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700557 return 0.0f;
558 }
Eric Laurenta553c252009-07-17 12:17:14 -0700559
560 AutoMutex lock(mLock);
561 float volume;
562 if (output) {
563 PlaybackThread *thread = checkPlaybackThread_l(output);
564 if (thread == NULL) {
565 return 0.0f;
566 }
567 volume = thread->streamVolume(stream);
568 } else {
569 volume = mStreamTypes[stream].volume;
570 }
571
Eric Laurentef028272009-04-21 07:56:33 -0700572 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700573}
574
575bool AudioFlinger::streamMute(int stream) const
576{
Eric Laurenta553c252009-07-17 12:17:14 -0700577 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700578 return true;
579 }
Eric Laurenta553c252009-07-17 12:17:14 -0700580
581 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700582}
583
Eric Laurent23f25cd2010-01-25 08:49:09 -0800584bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700585{
Eric Laurent4e646332009-07-09 03:20:57 -0700586 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700587 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent23f25cd2010-01-25 08:49:09 -0800588 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700589 return true;
590 }
591 }
592 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700593}
594
Eric Laurentddb78e72009-07-28 08:44:33 -0700595status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700596{
Eric Laurenta553c252009-07-17 12:17:14 -0700597 status_t result;
598
Eric Laurentddb78e72009-07-28 08:44:33 -0700599 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700600 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
601 // check calling permissions
602 if (!settingsAllowed()) {
603 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800604 }
Eric Laurenta553c252009-07-17 12:17:14 -0700605
Glenn Kasten871c16c2010-03-05 12:18:01 -0800606#ifdef LVMX
607 AudioParameter param = AudioParameter(keyValuePairs);
608 LifeVibes::setParameters(ioHandle,keyValuePairs);
609 String8 key = String8(AudioParameter::keyRouting);
610 int device;
611 if (NO_ERROR != param.getInt(key, device)) {
612 device = -1;
613 }
614
615 key = String8(LifevibesTag);
616 String8 value;
617 int musicEnabled = -1;
618 if (NO_ERROR == param.get(key, value)) {
619 if (value == LifevibesEnable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700620 mLifeVibesClientPid = IPCThreadState::self()->getCallingPid();
Glenn Kasten871c16c2010-03-05 12:18:01 -0800621 musicEnabled = 1;
622 } else if (value == LifevibesDisable) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700623 mLifeVibesClientPid = -1;
Glenn Kasten871c16c2010-03-05 12:18:01 -0800624 musicEnabled = 0;
625 }
626 }
627#endif
628
Eric Laurenta553c252009-07-17 12:17:14 -0700629 // ioHandle == 0 means the parameters are global to the audio hardware interface
630 if (ioHandle == 0) {
631 AutoMutex lock(mHardwareLock);
632 mHardwareStatus = AUDIO_SET_PARAMETER;
633 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800634#ifdef LVMX
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700635 if (musicEnabled != -1) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800636 LifeVibes::enableMusic((bool) musicEnabled);
637 }
638#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700639 mHardwareStatus = AUDIO_HW_IDLE;
640 return result;
641 }
642
Eric Laurentb7d94602009-09-29 11:12:57 -0700643 // hold a strong ref on thread in case closeOutput() or closeInput() is called
644 // and the thread is exited once the lock is released
645 sp<ThreadBase> thread;
646 {
647 Mutex::Autolock _l(mLock);
648 thread = checkPlaybackThread_l(ioHandle);
649 if (thread == NULL) {
650 thread = checkRecordThread_l(ioHandle);
651 }
Eric Laurenta553c252009-07-17 12:17:14 -0700652 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700653 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800654 result = thread->setParameters(keyValuePairs);
655#ifdef LVMX
656 if ((NO_ERROR == result) && (device != -1)) {
657 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
658 }
659#endif
660 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700661 }
Eric Laurenta553c252009-07-17 12:17:14 -0700662 return BAD_VALUE;
663}
664
Eric Laurentddb78e72009-07-28 08:44:33 -0700665String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700666{
Eric Laurentddb78e72009-07-28 08:44:33 -0700667// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700668// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
669
670 if (ioHandle == 0) {
671 return mAudioHardware->getParameters(keys);
672 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700673
674 Mutex::Autolock _l(mLock);
675
Eric Laurenta553c252009-07-17 12:17:14 -0700676 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
677 if (playbackThread != NULL) {
678 return playbackThread->getParameters(keys);
679 }
680 RecordThread *recordThread = checkRecordThread_l(ioHandle);
681 if (recordThread != NULL) {
682 return recordThread->getParameters(keys);
683 }
684 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700685}
686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
688{
689 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
690}
691
Eric Laurent47d0a922010-02-26 02:47:27 -0800692unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
693{
694 if (ioHandle == 0) {
695 return 0;
696 }
697
698 Mutex::Autolock _l(mLock);
699
700 RecordThread *recordThread = checkRecordThread_l(ioHandle);
701 if (recordThread != NULL) {
702 return recordThread->getInputFramesLost();
703 }
704 return 0;
705}
706
Eric Laurent415f3e22009-10-21 08:14:22 -0700707status_t AudioFlinger::setVoiceVolume(float value)
708{
709 // check calling permissions
710 if (!settingsAllowed()) {
711 return PERMISSION_DENIED;
712 }
713
714 AutoMutex lock(mHardwareLock);
715 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
716 status_t ret = mAudioHardware->setVoiceVolume(value);
717 mHardwareStatus = AUDIO_HW_IDLE;
718
719 return ret;
720}
721
Eric Laurent0986e792010-01-19 17:37:09 -0800722status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
723{
724 status_t status;
725
726 Mutex::Autolock _l(mLock);
727
728 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
729 if (playbackThread != NULL) {
730 return playbackThread->getRenderPosition(halFrames, dspFrames);
731 }
732
733 return BAD_VALUE;
734}
735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
737{
Eric Laurenta553c252009-07-17 12:17:14 -0700738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 Mutex::Autolock _l(mLock);
740
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700741 int pid = IPCThreadState::self()->getCallingPid();
742 if (mNotificationClients.indexOfKey(pid) < 0) {
743 sp<NotificationClient> notificationClient = new NotificationClient(this,
744 client,
745 pid);
746 LOGV("registerClient() client %p, pid %d", notificationClient.get(), pid);
Eric Laurenta553c252009-07-17 12:17:14 -0700747
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700748 mNotificationClients.add(pid, notificationClient);
Eric Laurenta553c252009-07-17 12:17:14 -0700749
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700750 sp<IBinder> binder = client->asBinder();
751 binder->linkToDeath(notificationClient);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700753 // the config change is always sent from playback or record threads to avoid deadlock
754 // with AudioSystem::gLock
755 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
756 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
757 }
Eric Laurenta553c252009-07-17 12:17:14 -0700758
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700759 for (size_t i = 0; i < mRecordThreads.size(); i++) {
760 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 }
762 }
763}
764
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700765void AudioFlinger::removeNotificationClient(pid_t pid)
766{
767 Mutex::Autolock _l(mLock);
768
769 int index = mNotificationClients.indexOfKey(pid);
770 if (index >= 0) {
771 sp <NotificationClient> client = mNotificationClients.valueFor(pid);
772 LOGV("removeNotificationClient() %p, pid %d", client.get(), pid);
773#ifdef LVMX
774 if (pid == mLifeVibesClientPid) {
775 LOGV("Disabling lifevibes");
776 LifeVibes::enableMusic(false);
777 mLifeVibesClientPid = -1;
778 }
779#endif
780 mNotificationClients.removeItem(pid);
781 }
782}
783
Eric Laurent296a0ec2009-09-15 07:10:12 -0700784// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700785void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2)
786{
Eric Laurent49f02be2009-11-19 09:00:56 -0800787 size_t size = mNotificationClients.size();
788 for (size_t i = 0; i < size; i++) {
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700789 mNotificationClients.valueAt(i)->client()->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700790 }
791}
792
Eric Laurentb9481d82009-09-17 05:12:56 -0700793// removeClient_l() must be called with AudioFlinger::mLock held
794void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700795{
Eric Laurentb9481d82009-09-17 05:12:56 -0700796 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700797 mClients.removeItem(pid);
798}
799
Eric Laurent4f0f17d2010-05-12 02:05:53 -0700800
Eric Laurenta553c252009-07-17 12:17:14 -0700801// ----------------------------------------------------------------------------
802
Eric Laurent49f02be2009-11-19 09:00:56 -0800803AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700804 : Thread(false),
805 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurentb0a01472010-05-14 05:45:46 -0700806 mFrameSize(1), mFormat(0), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700807{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808}
809
Eric Laurenta553c252009-07-17 12:17:14 -0700810AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700812 mParamCond.broadcast();
813 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814}
815
Eric Laurenta553c252009-07-17 12:17:14 -0700816void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700817{
Eric Laurentb7d94602009-09-29 11:12:57 -0700818 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700819 // destroyed in the middle of requestExitAndWait()
820 sp <ThreadBase> strongMe = this;
821
822 LOGV("ThreadBase::exit");
823 {
824 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800825 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700826 requestExit();
827 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700828 }
Eric Laurenta553c252009-07-17 12:17:14 -0700829 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700830}
Eric Laurenta553c252009-07-17 12:17:14 -0700831
832uint32_t AudioFlinger::ThreadBase::sampleRate() const
833{
834 return mSampleRate;
835}
836
837int AudioFlinger::ThreadBase::channelCount() const
838{
Eric Laurentb0a01472010-05-14 05:45:46 -0700839 return (int)mChannelCount;
Eric Laurenta553c252009-07-17 12:17:14 -0700840}
841
842int AudioFlinger::ThreadBase::format() const
843{
844 return mFormat;
845}
846
847size_t AudioFlinger::ThreadBase::frameCount() const
848{
849 return mFrameCount;
850}
851
852status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
853{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700854 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700855
Eric Laurent8fce46a2009-08-04 09:45:33 -0700856 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700857 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700858
Eric Laurent8fce46a2009-08-04 09:45:33 -0700859 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700860 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700861 // wait condition with timeout in case the thread loop has exited
862 // before the request could be processed
863 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
864 status = mParamStatus;
865 mWaitWorkCV.signal();
866 } else {
867 status = TIMED_OUT;
868 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700869 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700870}
871
872void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
873{
874 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700875 sendConfigEvent_l(event, param);
876}
877
878// sendConfigEvent_l() must be called with ThreadBase::mLock held
879void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
880{
Eric Laurenta553c252009-07-17 12:17:14 -0700881 ConfigEvent *configEvent = new ConfigEvent();
882 configEvent->mEvent = event;
883 configEvent->mParam = param;
884 mConfigEvents.add(configEvent);
885 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
886 mWaitWorkCV.signal();
887}
888
889void AudioFlinger::ThreadBase::processConfigEvents()
890{
891 mLock.lock();
892 while(!mConfigEvents.isEmpty()) {
893 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
894 ConfigEvent *configEvent = mConfigEvents[0];
895 mConfigEvents.removeAt(0);
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700896 // release mLock before locking AudioFlinger mLock: lock order is always
897 // AudioFlinger then ThreadBase to avoid cross deadlock
Eric Laurenta553c252009-07-17 12:17:14 -0700898 mLock.unlock();
Eric Laurenteb8f850d2010-05-14 03:26:45 -0700899 mAudioFlinger->mLock.lock();
900 audioConfigChanged_l(configEvent->mEvent, configEvent->mParam);
901 mAudioFlinger->mLock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -0700902 delete configEvent;
903 mLock.lock();
904 }
905 mLock.unlock();
906}
907
Eric Laurent3fdb1262009-11-07 00:01:32 -0800908status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
909{
910 const size_t SIZE = 256;
911 char buffer[SIZE];
912 String8 result;
913
914 bool locked = tryLock(mLock);
915 if (!locked) {
916 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
917 write(fd, buffer, strlen(buffer));
918 }
919
920 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
921 result.append(buffer);
922 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
923 result.append(buffer);
924 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
925 result.append(buffer);
926 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
927 result.append(buffer);
928 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
929 result.append(buffer);
930 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
931 result.append(buffer);
932
933 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
934 result.append(buffer);
935 result.append(" Index Command");
936 for (size_t i = 0; i < mNewParameters.size(); ++i) {
937 snprintf(buffer, SIZE, "\n %02d ", i);
938 result.append(buffer);
939 result.append(mNewParameters[i]);
940 }
941
942 snprintf(buffer, SIZE, "\n\nPending config events: \n");
943 result.append(buffer);
944 snprintf(buffer, SIZE, " Index event param\n");
945 result.append(buffer);
946 for (size_t i = 0; i < mConfigEvents.size(); i++) {
947 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
948 result.append(buffer);
949 }
950 result.append("\n");
951
952 write(fd, result.string(), result.size());
953
954 if (locked) {
955 mLock.unlock();
956 }
957 return NO_ERROR;
958}
959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960
961// ----------------------------------------------------------------------------
962
Eric Laurent65b65452010-06-01 23:49:17 -0700963AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
Eric Laurent49f02be2009-11-19 09:00:56 -0800964 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700965 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent65b65452010-06-01 23:49:17 -0700966 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
967 mDevice(device)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968{
Eric Laurenta553c252009-07-17 12:17:14 -0700969 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970
Eric Laurenta553c252009-07-17 12:17:14 -0700971 mMasterVolume = mAudioFlinger->masterVolume();
972 mMasterMute = mAudioFlinger->masterMute();
973
974 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
975 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
976 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978}
979
Eric Laurenta553c252009-07-17 12:17:14 -0700980AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981{
982 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983}
984
Eric Laurenta553c252009-07-17 12:17:14 -0700985status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986{
987 dumpInternals(fd, args);
988 dumpTracks(fd, args);
Eric Laurent65b65452010-06-01 23:49:17 -0700989 dumpEffectChains(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 return NO_ERROR;
991}
992
Eric Laurenta553c252009-07-17 12:17:14 -0700993status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994{
995 const size_t SIZE = 256;
996 char buffer[SIZE];
997 String8 result;
998
Eric Laurenta553c252009-07-17 12:17:14 -0700999 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001001 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001003 sp<Track> track = mTracks[i];
1004 if (track != 0) {
1005 track->dump(buffer, SIZE);
1006 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008 }
1009
Eric Laurenta553c252009-07-17 12:17:14 -07001010 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001012 result.append(" Name Clien Typ Fmt Chn Session Buf S M F SRate LeftV RighV Serv User Main buf Aux Buf\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -07001014 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 if (wTrack != 0) {
1016 sp<Track> track = wTrack.promote();
1017 if (track != 0) {
1018 track->dump(buffer, SIZE);
1019 result.append(buffer);
1020 }
1021 }
1022 }
1023 write(fd, result.string(), result.size());
1024 return NO_ERROR;
1025}
1026
Eric Laurent65b65452010-06-01 23:49:17 -07001027status_t AudioFlinger::PlaybackThread::dumpEffectChains(int fd, const Vector<String16>& args)
1028{
1029 const size_t SIZE = 256;
1030 char buffer[SIZE];
1031 String8 result;
1032
1033 snprintf(buffer, SIZE, "\n- %d Effect Chains:\n", mEffectChains.size());
1034 write(fd, buffer, strlen(buffer));
1035
1036 for (size_t i = 0; i < mEffectChains.size(); ++i) {
1037 sp<EffectChain> chain = mEffectChains[i];
1038 if (chain != 0) {
1039 chain->dump(fd, args);
1040 }
1041 }
1042 return NO_ERROR;
1043}
1044
Eric Laurenta553c252009-07-17 12:17:14 -07001045status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046{
1047 const size_t SIZE = 256;
1048 char buffer[SIZE];
1049 String8 result;
1050
Eric Laurent3fdb1262009-11-07 00:01:32 -08001051 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 result.append(buffer);
1053 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1054 result.append(buffer);
1055 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1056 result.append(buffer);
1057 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1058 result.append(buffer);
1059 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1060 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001061 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1062 result.append(buffer);
Eric Laurent65b65452010-06-01 23:49:17 -07001063 snprintf(buffer, SIZE, "mix buffer : %p\n", mMixBuffer);
1064 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001066
1067 dumpBase(fd, args);
1068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 return NO_ERROR;
1070}
1071
1072// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001073status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074{
1075 if (mSampleRate == 0) {
1076 LOGE("No working audio driver found.");
1077 return NO_INIT;
1078 }
Eric Laurenta553c252009-07-17 12:17:14 -07001079 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 return NO_ERROR;
1081}
1082
Eric Laurenta553c252009-07-17 12:17:14 -07001083void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084{
1085 const size_t SIZE = 256;
1086 char buffer[SIZE];
1087
Eric Laurenta553c252009-07-17 12:17:14 -07001088 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089
1090 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1091}
1092
Eric Laurenta553c252009-07-17 12:17:14 -07001093// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1094sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 const sp<AudioFlinger::Client>& client,
1096 int streamType,
1097 uint32_t sampleRate,
1098 int format,
1099 int channelCount,
1100 int frameCount,
1101 const sp<IMemory>& sharedBuffer,
Eric Laurent65b65452010-06-01 23:49:17 -07001102 int sessionId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 status_t *status)
1104{
1105 sp<Track> track;
1106 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001107
1108 if (mType == DIRECT) {
Eric Laurentb0a01472010-05-14 05:45:46 -07001109 if (sampleRate != mSampleRate || format != mFormat || channelCount != (int)mChannelCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07001110 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1111 sampleRate, format, channelCount, mOutput);
1112 lStatus = BAD_VALUE;
1113 goto Exit;
1114 }
1115 } else {
1116 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1117 if (sampleRate > mSampleRate*2) {
1118 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1119 lStatus = BAD_VALUE;
1120 goto Exit;
1121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 }
1123
Eric Laurenta553c252009-07-17 12:17:14 -07001124 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001125 LOGE("Audio driver not initialized.");
1126 lStatus = NO_INIT;
1127 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 }
1129
Eric Laurenta553c252009-07-17 12:17:14 -07001130 { // scope for mLock
1131 Mutex::Autolock _l(mLock);
1132 track = new Track(this, client, streamType, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07001133 channelCount, frameCount, sharedBuffer, sessionId);
Eric Laurent73b60352009-11-09 04:45:39 -08001134 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001135 lStatus = NO_MEMORY;
1136 goto Exit;
1137 }
1138 mTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001139
1140 sp<EffectChain> chain = getEffectChain_l(sessionId);
1141 if (chain != 0) {
1142 LOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
1143 track->setMainBuffer(chain->inBuffer());
1144 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001145 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001146 lStatus = NO_ERROR;
1147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148Exit:
1149 if(status) {
1150 *status = lStatus;
1151 }
1152 return track;
1153}
1154
Eric Laurenta553c252009-07-17 12:17:14 -07001155uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156{
1157 if (mOutput) {
1158 return mOutput->latency();
1159 }
1160 else {
1161 return 0;
1162 }
1163}
1164
Eric Laurenta553c252009-07-17 12:17:14 -07001165status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001167#ifdef LVMX
1168 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1169 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1170 LifeVibes::setMasterVolume(audioOutputType, value);
1171 }
1172#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 mMasterVolume = value;
1174 return NO_ERROR;
1175}
1176
Eric Laurenta553c252009-07-17 12:17:14 -07001177status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001179#ifdef LVMX
1180 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1181 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1182 LifeVibes::setMasterMute(audioOutputType, muted);
1183 }
1184#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 mMasterMute = muted;
1186 return NO_ERROR;
1187}
1188
Eric Laurenta553c252009-07-17 12:17:14 -07001189float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190{
1191 return mMasterVolume;
1192}
1193
Eric Laurenta553c252009-07-17 12:17:14 -07001194bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195{
1196 return mMasterMute;
1197}
1198
Eric Laurenta553c252009-07-17 12:17:14 -07001199status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001201#ifdef LVMX
1202 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1203 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1204 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1205 }
1206#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 mStreamTypes[stream].volume = value;
1208 return NO_ERROR;
1209}
1210
Eric Laurenta553c252009-07-17 12:17:14 -07001211status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001213#ifdef LVMX
1214 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1215 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1216 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1217 }
1218#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 mStreamTypes[stream].mute = muted;
1220 return NO_ERROR;
1221}
1222
Eric Laurenta553c252009-07-17 12:17:14 -07001223float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224{
1225 return mStreamTypes[stream].volume;
1226}
1227
Eric Laurenta553c252009-07-17 12:17:14 -07001228bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229{
1230 return mStreamTypes[stream].mute;
1231}
1232
Eric Laurent23f25cd2010-01-25 08:49:09 -08001233bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234{
Eric Laurenta553c252009-07-17 12:17:14 -07001235 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 size_t count = mActiveTracks.size();
1237 for (size_t i = 0 ; i < count ; ++i) {
1238 sp<Track> t = mActiveTracks[i].promote();
1239 if (t == 0) continue;
1240 Track* const track = t.get();
Eric Laurent23f25cd2010-01-25 08:49:09 -08001241 if (t->type() == stream)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 return true;
1243 }
1244 return false;
1245}
1246
Eric Laurenta553c252009-07-17 12:17:14 -07001247// addTrack_l() must be called with ThreadBase::mLock held
1248status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249{
1250 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001251
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001252 // set retry count for buffer fill
1253 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001254 if (mActiveTracks.indexOf(track) < 0) {
1255 // the track is newly added, make sure it fills up all its
1256 // buffers before playing. This is to ensure the client will
1257 // effectively get the latency it requested.
1258 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001259 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001260 mActiveTracks.add(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001261 if (track->mainBuffer() != mMixBuffer) {
1262 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
1263 if (chain != 0) {
1264 LOGV("addTrack_l() starting track on chain %p for session %d", chain.get(), track->sessionId());
1265 chain->startTrack();
1266 }
1267 }
1268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001270 }
Eric Laurenta553c252009-07-17 12:17:14 -07001271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001273 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274
1275 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001276}
1277
Eric Laurenta553c252009-07-17 12:17:14 -07001278// destroyTrack_l() must be called with ThreadBase::mLock held
1279void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001280{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001281 track->mState = TrackBase::TERMINATED;
1282 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001283 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001284 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001285 }
1286}
1287
Eric Laurenta553c252009-07-17 12:17:14 -07001288String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001289{
Eric Laurenta553c252009-07-17 12:17:14 -07001290 return mOutput->getParameters(keys);
1291}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001292
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001293// destroyTrack_l() must be called with AudioFlinger::mLock held
1294void AudioFlinger::PlaybackThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07001295 AudioSystem::OutputDescriptor desc;
1296 void *param2 = 0;
1297
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001298 LOGV("PlaybackThread::audioConfigChanged_l, thread %p, event %d, param %d", this, event, param);
Eric Laurenta553c252009-07-17 12:17:14 -07001299
1300 switch (event) {
1301 case AudioSystem::OUTPUT_OPENED:
1302 case AudioSystem::OUTPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07001303 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07001304 desc.samplingRate = mSampleRate;
1305 desc.format = mFormat;
1306 desc.frameCount = mFrameCount;
1307 desc.latency = latency();
1308 param2 = &desc;
1309 break;
1310
1311 case AudioSystem::STREAM_CONFIG_CHANGED:
1312 param2 = &param;
1313 case AudioSystem::OUTPUT_CLOSED:
1314 default:
1315 break;
1316 }
Eric Laurent49f02be2009-11-19 09:00:56 -08001317 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001318}
1319
1320void AudioFlinger::PlaybackThread::readOutputParameters()
1321{
1322 mSampleRate = mOutput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07001323 mChannels = mOutput->channels();
1324 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07001325 mFormat = mOutput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07001326 mFrameSize = (uint16_t)mOutput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07001327 mFrameCount = mOutput->bufferSize() / mFrameSize;
1328
Eric Laurenta553c252009-07-17 12:17:14 -07001329 // FIXME - Current mixer implementation only supports stereo output: Always
1330 // Allocate a stereo buffer even if HW output is mono.
Eric Laurent65b65452010-06-01 23:49:17 -07001331 if (mMixBuffer != NULL) delete[] mMixBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07001332 mMixBuffer = new int16_t[mFrameCount * 2];
1333 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
Eric Laurent65b65452010-06-01 23:49:17 -07001334
1335 //TODO handle effects reconfig
Eric Laurenta553c252009-07-17 12:17:14 -07001336}
1337
Eric Laurent0986e792010-01-19 17:37:09 -08001338status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1339{
1340 if (halFrames == 0 || dspFrames == 0) {
1341 return BAD_VALUE;
1342 }
1343 if (mOutput == 0) {
1344 return INVALID_OPERATION;
1345 }
1346 *halFrames = mBytesWritten/mOutput->frameSize();
1347
1348 return mOutput->getRenderPosition(dspFrames);
1349}
1350
Eric Laurent65b65452010-06-01 23:49:17 -07001351bool AudioFlinger::PlaybackThread::hasAudioSession(int sessionId)
1352{
1353 Mutex::Autolock _l(mLock);
1354 if (getEffectChain_l(sessionId) != 0) {
1355 return true;
1356 }
1357
1358 for (size_t i = 0; i < mTracks.size(); ++i) {
1359 sp<Track> track = mTracks[i];
1360 if (sessionId == track->sessionId()) {
1361 return true;
1362 }
1363 }
1364
1365 return false;
1366}
1367
1368sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain(int sessionId)
1369{
1370 Mutex::Autolock _l(mLock);
1371 return getEffectChain_l(sessionId);
1372}
1373
1374sp<AudioFlinger::EffectChain> AudioFlinger::PlaybackThread::getEffectChain_l(int sessionId)
1375{
1376 sp<EffectChain> chain;
1377
1378 size_t size = mEffectChains.size();
1379 for (size_t i = 0; i < size; i++) {
1380 if (mEffectChains[i]->sessionId() == sessionId) {
1381 chain = mEffectChains[i];
1382 break;
1383 }
1384 }
1385 return chain;
1386}
1387
Eric Laurenta553c252009-07-17 12:17:14 -07001388// ----------------------------------------------------------------------------
1389
Eric Laurent65b65452010-06-01 23:49:17 -07001390AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1391 : PlaybackThread(audioFlinger, output, id, device),
Eric Laurenta553c252009-07-17 12:17:14 -07001392 mAudioMixer(0)
1393{
1394 mType = PlaybackThread::MIXER;
1395 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1396
1397 // FIXME - Current mixer implementation only supports stereo output
1398 if (mChannelCount == 1) {
1399 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001401}
1402
Eric Laurenta553c252009-07-17 12:17:14 -07001403AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001404{
Eric Laurenta553c252009-07-17 12:17:14 -07001405 delete mAudioMixer;
1406}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407
Eric Laurenta553c252009-07-17 12:17:14 -07001408bool AudioFlinger::MixerThread::threadLoop()
1409{
Eric Laurenta553c252009-07-17 12:17:14 -07001410 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001411 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001412 nsecs_t standbyTime = systemTime();
1413 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001414 // FIXME: Relaxed timing because of a certain device that can't meet latency
1415 // Should be reduced to 2x after the vendor fixes the driver issue
1416 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1417 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001418 bool longStandbyExit = false;
1419 uint32_t activeSleepTime = activeSleepTimeUs();
1420 uint32_t idleSleepTime = idleSleepTimeUs();
1421 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07001422 Vector< sp<EffectChain> > effectChains;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423
Eric Laurenta553c252009-07-17 12:17:14 -07001424 while (!exitPending())
1425 {
1426 processConfigEvents();
1427
Eric Laurent059b4be2009-11-09 23:32:22 -08001428 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001429 { // scope for mLock
1430
1431 Mutex::Autolock _l(mLock);
1432
1433 if (checkForNewParameters_l()) {
1434 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001435 // FIXME: Relaxed timing because of a certain device that can't meet latency
1436 // Should be reduced to 2x after the vendor fixes the driver issue
1437 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001438 activeSleepTime = activeSleepTimeUs();
1439 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001440 }
1441
1442 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1443
1444 // put audio hardware into standby after short delay
1445 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1446 mSuspended) {
1447 if (!mStandby) {
1448 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1449 mOutput->standby();
1450 mStandby = true;
1451 mBytesWritten = 0;
1452 }
1453
1454 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1455 // we're about to wait, flush the binder command buffer
1456 IPCThreadState::self()->flushCommands();
1457
1458 if (exitPending()) break;
1459
1460 // wait until we have something to do...
1461 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1462 mWaitWorkCV.wait(mLock);
1463 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1464
1465 if (mMasterMute == false) {
1466 char value[PROPERTY_VALUE_MAX];
1467 property_get("ro.audio.silent", value, "0");
1468 if (atoi(value)) {
1469 LOGD("Silence is golden");
1470 setMasterMute(true);
1471 }
1472 }
1473
1474 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001475 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001476 continue;
1477 }
1478 }
1479
Eric Laurent059b4be2009-11-09 23:32:22 -08001480 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07001481
1482 // prevent any changes in effect chain list and in each effect chain
1483 // during mixing and effect process as the audio buffers could be deleted
1484 // or modified if an effect is created or deleted
1485 effectChains = mEffectChains;
1486 lockEffectChains_l();
Eric Laurenta553c252009-07-17 12:17:14 -07001487 }
1488
Eric Laurent059b4be2009-11-09 23:32:22 -08001489 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001490 // mix buffers...
Eric Laurent65b65452010-06-01 23:49:17 -07001491 mAudioMixer->process();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001492 sleepTime = 0;
1493 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent65b65452010-06-01 23:49:17 -07001494 //TODO: delay standby when effects have a tail
Eric Laurent96c08a62009-09-07 08:38:38 -07001495 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001496 // If no tracks are ready, sleep once for the duration of an output
1497 // buffer size, then write 0s to the output
1498 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001499 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1500 sleepTime = activeSleepTime;
1501 } else {
1502 sleepTime = idleSleepTime;
1503 }
1504 } else if (mBytesWritten != 0 ||
1505 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001506 memset (mMixBuffer, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001507 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001508 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001509 }
Eric Laurent65b65452010-06-01 23:49:17 -07001510 // TODO add standby time extension fct of effect tail
Eric Laurentf69a3f82009-09-22 00:35:48 -07001511 }
1512
1513 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001514 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001515 }
1516 // sleepTime == 0 means we must write to audio hardware
1517 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07001518 for (size_t i = 0; i < effectChains.size(); i ++) {
1519 effectChains[i]->process_l();
1520 }
1521 // enable changes in effect chain
1522 unlockEffectChains();
Glenn Kasten871c16c2010-03-05 12:18:01 -08001523#ifdef LVMX
1524 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1525 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
Eric Laurent65b65452010-06-01 23:49:17 -07001526 LifeVibes::process(audioOutputType, mMixBuffer, mixBufferSize);
Glenn Kasten871c16c2010-03-05 12:18:01 -08001527 }
1528#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001529 mLastWriteTime = systemTime();
1530 mInWrite = true;
1531 mBytesWritten += mixBufferSize;
1532
1533 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001534 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001535 mNumWrites++;
1536 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001537 nsecs_t now = systemTime();
1538 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001539 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001540 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001541 if ((now - lastWarning) > kWarningThrottle) {
1542 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1543 ns2ms(delta), mNumDelayedWrites, this);
1544 lastWarning = now;
1545 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001546 if (mStandby) {
1547 longStandbyExit = true;
1548 }
Eric Laurenta553c252009-07-17 12:17:14 -07001549 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001550 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001551 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07001552 // enable changes in effect chain
1553 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07001554 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001555 }
1556
1557 // finally let go of all our tracks, without the lock held
1558 // since we can't guarantee the destructors won't acquire that
1559 // same lock.
1560 tracksToRemove.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07001561
1562 // Effect chains will be actually deleted here if they were removed from
1563 // mEffectChains list during mixing or effects processing
1564 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07001565 }
1566
1567 if (!mStandby) {
1568 mOutput->standby();
1569 }
Eric Laurenta553c252009-07-17 12:17:14 -07001570
1571 LOGV("MixerThread %p exiting", this);
1572 return false;
1573}
1574
1575// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001576uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001577{
1578
Eric Laurent059b4be2009-11-09 23:32:22 -08001579 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001580 // find out which tracks need to be processed
1581 size_t count = activeTracks.size();
Eric Laurent65b65452010-06-01 23:49:17 -07001582 size_t mixedTracks = 0;
1583 size_t tracksWithEffect = 0;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001584
1585 float masterVolume = mMasterVolume;
1586 bool masterMute = mMasterMute;
1587
1588#ifdef LVMX
1589 bool tracksConnectedChanged = false;
1590 bool stateChanged = false;
1591
1592 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1593 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1594 {
1595 int activeTypes = 0;
1596 for (size_t i=0 ; i<count ; i++) {
1597 sp<Track> t = activeTracks[i].promote();
1598 if (t == 0) continue;
1599 Track* const track = t.get();
1600 int iTracktype=track->type();
1601 activeTypes |= 1<<track->type();
1602 }
1603 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1604 }
1605#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001606 // Delegate master volume control to effect in output mix effect chain if needed
1607 sp<EffectChain> chain = getEffectChain_l(0);
1608 if (chain != 0) {
1609 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
1610 chain->setVolume(&v, &v);
1611 masterVolume = (float)((v + (1 << 23)) >> 24);
1612 chain.clear();
1613 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001614
Eric Laurenta553c252009-07-17 12:17:14 -07001615 for (size_t i=0 ; i<count ; i++) {
1616 sp<Track> t = activeTracks[i].promote();
1617 if (t == 0) continue;
1618
1619 Track* const track = t.get();
1620 audio_track_cblk_t* cblk = track->cblk();
1621
1622 // The first time a track is added we wait
1623 // for all its buffers to be filled before processing it
1624 mAudioMixer->setActiveTrack(track->name());
1625 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent71f37cd2010-03-31 12:21:17 -07001626 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07001627 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001628 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07001629
Eric Laurent65b65452010-06-01 23:49:17 -07001630 mixedTracks++;
1631
1632 // track->mainBuffer() != mMixBuffer means there is an effect chain
1633 // connected to the track
1634 chain.clear();
1635 if (track->mainBuffer() != mMixBuffer) {
1636 chain = getEffectChain_l(track->sessionId());
1637 // Delegate volume control to effect in track effect chain if needed
1638 if (chain != 0) {
1639 tracksWithEffect++;
1640 } else {
1641 LOGW("prepareTracks_l(): track %08x attached to effect but no chain found on session %d",
1642 track->name(), track->sessionId());
1643 }
1644 }
1645
1646
1647 int param = AudioMixer::VOLUME;
1648 if (track->mFillingUpStatus == Track::FS_FILLED) {
1649 // no ramp for the first volume setting
1650 track->mFillingUpStatus = Track::FS_ACTIVE;
1651 if (track->mState == TrackBase::RESUMING) {
1652 track->mState = TrackBase::ACTIVE;
1653 param = AudioMixer::RAMP_VOLUME;
1654 }
1655 } else if (cblk->server != 0) {
1656 // If the track is stopped before the first frame was mixed,
1657 // do not apply ramp
1658 param = AudioMixer::RAMP_VOLUME;
1659 }
1660
Eric Laurenta553c252009-07-17 12:17:14 -07001661 // compute volume for this track
Eric Laurent65b65452010-06-01 23:49:17 -07001662 int16_t left, right, aux;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001663 if (track->isMuted() || masterMute || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001664 mStreamTypes[track->type()].mute) {
Eric Laurent65b65452010-06-01 23:49:17 -07001665 left = right = aux = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07001666 if (track->isPausing()) {
1667 track->setPaused();
1668 }
1669 } else {
Glenn Kasten871c16c2010-03-05 12:18:01 -08001670 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001671 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001672#ifdef LVMX
1673 bool streamMute=false;
1674 // read the volume from the LivesVibes audio engine.
1675 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1676 {
1677 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1678 if (streamMute) {
1679 typeVolume = 0;
1680 }
1681 }
1682#endif
1683 float v = masterVolume * typeVolume;
Eric Laurent65b65452010-06-01 23:49:17 -07001684 uint32_t vl = (uint32_t)(v * cblk->volume[0]) << 12;
1685 uint32_t vr = (uint32_t)(v * cblk->volume[1]) << 12;
Eric Laurenta553c252009-07-17 12:17:14 -07001686
Eric Laurent65b65452010-06-01 23:49:17 -07001687 // Delegate volume control to effect in track effect chain if needed
1688 if (chain != 0 && chain->setVolume(&vl, &vr)) {
1689 // Do not ramp volume is volume is controlled by effect
1690 param = AudioMixer::VOLUME;
Eric Laurenta553c252009-07-17 12:17:14 -07001691 }
Eric Laurent65b65452010-06-01 23:49:17 -07001692
1693 // Convert volumes from 8.24 to 4.12 format
1694 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
1695 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1696 left = int16_t(v_clamped);
1697 v_clamped = (vr + (1 << 11)) >> 12;
1698 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1699 right = int16_t(v_clamped);
1700
1701 v_clamped = (uint32_t)(v * cblk->sendLevel);
1702 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
1703 aux = int16_t(v_clamped);
Eric Laurenta553c252009-07-17 12:17:14 -07001704 }
Eric Laurent65b65452010-06-01 23:49:17 -07001705
Glenn Kasten871c16c2010-03-05 12:18:01 -08001706#ifdef LVMX
1707 if ( tracksConnectedChanged || stateChanged )
1708 {
1709 // only do the ramp when the volume is changed by the user / application
1710 param = AudioMixer::VOLUME;
1711 }
1712#endif
Eric Laurent65b65452010-06-01 23:49:17 -07001713
1714 // XXX: these things DON'T need to be done each time
1715 mAudioMixer->setBufferProvider(track);
1716 mAudioMixer->enable(AudioMixer::MIXING);
1717
1718 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, (void *)left);
1719 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, (void *)right);
1720 mAudioMixer->setParameter(param, AudioMixer::AUXLEVEL, (void *)aux);
Eric Laurenta553c252009-07-17 12:17:14 -07001721 mAudioMixer->setParameter(
1722 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001723 AudioMixer::FORMAT, (void *)track->format());
Eric Laurenta553c252009-07-17 12:17:14 -07001724 mAudioMixer->setParameter(
1725 AudioMixer::TRACK,
Eric Laurent65b65452010-06-01 23:49:17 -07001726 AudioMixer::CHANNEL_COUNT, (void *)track->channelCount());
Eric Laurenta553c252009-07-17 12:17:14 -07001727 mAudioMixer->setParameter(
1728 AudioMixer::RESAMPLE,
1729 AudioMixer::SAMPLE_RATE,
Eric Laurent65b65452010-06-01 23:49:17 -07001730 (void *)(cblk->sampleRate));
1731 mAudioMixer->setParameter(
1732 AudioMixer::TRACK,
1733 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
1734 mAudioMixer->setParameter(
1735 AudioMixer::TRACK,
1736 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
Eric Laurenta553c252009-07-17 12:17:14 -07001737
1738 // reset retry count
1739 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001740 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001741 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001742 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurenta553c252009-07-17 12:17:14 -07001743 if (track->isStopped()) {
1744 track->reset();
1745 }
1746 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1747 // We have consumed all the buffers of this track.
1748 // Remove it from the list of active tracks.
1749 tracksToRemove->add(track);
Eric Laurenta553c252009-07-17 12:17:14 -07001750 } else {
1751 // No buffers for this track. Give it a few chances to
1752 // fill a buffer, then remove it from active list.
1753 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001754 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001755 tracksToRemove->add(track);
Eric Laurent059b4be2009-11-09 23:32:22 -08001756 } else if (mixerStatus != MIXER_TRACKS_READY) {
1757 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001758 }
Eric Laurenta553c252009-07-17 12:17:14 -07001759 }
Eric Laurent65b65452010-06-01 23:49:17 -07001760 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001761 }
1762 }
1763
1764 // remove all the tracks that need to be...
1765 count = tracksToRemove->size();
1766 if (UNLIKELY(count)) {
1767 for (size_t i=0 ; i<count ; i++) {
1768 const sp<Track>& track = tracksToRemove->itemAt(i);
1769 mActiveTracks.remove(track);
Eric Laurent65b65452010-06-01 23:49:17 -07001770 if (track->mainBuffer() != mMixBuffer) {
1771 chain = getEffectChain_l(track->sessionId());
1772 if (chain != 0) {
1773 LOGV("stopping track on chain %p for session Id: %d", chain.get(), track->sessionId());
1774 chain->stopTrack();
1775 }
1776 }
Eric Laurenta553c252009-07-17 12:17:14 -07001777 if (track->isTerminated()) {
1778 mTracks.remove(track);
1779 deleteTrackName_l(track->mName);
1780 }
1781 }
1782 }
1783
Eric Laurent65b65452010-06-01 23:49:17 -07001784 // mix buffer must be cleared if all tracks are connected to an
1785 // effect chain as in this case the mixer will not write to
1786 // mix buffer and track effects will accumulate into it
1787 if (mixedTracks != 0 && mixedTracks == tracksWithEffect) {
1788 memset(mMixBuffer, 0, mFrameCount * mChannelCount * sizeof(int16_t));
1789 }
1790
Eric Laurent059b4be2009-11-09 23:32:22 -08001791 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001792}
1793
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001794void AudioFlinger::MixerThread::invalidateTracks(int streamType)
Eric Laurenta553c252009-07-17 12:17:14 -07001795{
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001796 LOGV ("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %d", this, streamType, mTracks.size());
Eric Laurenta553c252009-07-17 12:17:14 -07001797 Mutex::Autolock _l(mLock);
1798 size_t size = mTracks.size();
1799 for (size_t i = 0; i < size; i++) {
1800 sp<Track> t = mTracks[i];
1801 if (t->type() == streamType) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001802 t->mCblk->lock.lock();
1803 t->mCblk->flags |= CBLK_INVALID_ON;
1804 t->mCblk->cv.signal();
1805 t->mCblk->lock.unlock();
Eric Laurenta553c252009-07-17 12:17:14 -07001806 }
1807 }
1808 }
Eric Laurenta553c252009-07-17 12:17:14 -07001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810
Eric Laurenta553c252009-07-17 12:17:14 -07001811// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001812int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813{
1814 return mAudioMixer->getTrackName();
1815}
1816
Eric Laurenta553c252009-07-17 12:17:14 -07001817// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001818void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819{
Eric Laurent0a080292009-12-07 10:53:10 -08001820 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 mAudioMixer->deleteTrackName(name);
1822}
1823
Eric Laurenta553c252009-07-17 12:17:14 -07001824// checkForNewParameters_l() must be called with ThreadBase::mLock held
1825bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826{
Eric Laurenta553c252009-07-17 12:17:14 -07001827 bool reconfig = false;
1828
Eric Laurent8fce46a2009-08-04 09:45:33 -07001829 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001830 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001831 String8 keyValuePair = mNewParameters[0];
1832 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001833 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001834
Eric Laurenta553c252009-07-17 12:17:14 -07001835 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1836 reconfig = true;
1837 }
1838 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1839 if (value != AudioSystem::PCM_16_BIT) {
1840 status = BAD_VALUE;
1841 } else {
1842 reconfig = true;
1843 }
1844 }
1845 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1846 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1847 status = BAD_VALUE;
1848 } else {
1849 reconfig = true;
1850 }
1851 }
1852 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1853 // do not accept frame count changes if tracks are open as the track buffer
1854 // size depends on frame count and correct behavior would not be garantied
1855 // if frame count is changed after track creation
1856 if (!mTracks.isEmpty()) {
1857 status = INVALID_OPERATION;
1858 } else {
1859 reconfig = true;
1860 }
1861 }
Eric Laurent65b65452010-06-01 23:49:17 -07001862 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
1863 // forward device change to effects that have requested to be
1864 // aware of attached audio device.
1865 mDevice = (uint32_t)value;
1866 for (size_t i = 0; i < mEffectChains.size(); i++) {
1867 mEffectChains[i]->setDevice(mDevice);
1868 }
1869 }
1870
Eric Laurenta553c252009-07-17 12:17:14 -07001871 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001872 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001873 if (!mStandby && status == INVALID_OPERATION) {
1874 mOutput->standby();
1875 mStandby = true;
1876 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001877 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001878 }
1879 if (status == NO_ERROR && reconfig) {
1880 delete mAudioMixer;
1881 readOutputParameters();
1882 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1883 for (size_t i = 0; i < mTracks.size() ; i++) {
1884 int name = getTrackName_l();
1885 if (name < 0) break;
1886 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001887 // limit track sample rate to 2 x new output sample rate
1888 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1889 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1890 }
Eric Laurenta553c252009-07-17 12:17:14 -07001891 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001892 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001893 }
1894 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001895
1896 mNewParameters.removeAt(0);
1897
Eric Laurenta553c252009-07-17 12:17:14 -07001898 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001899 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001900 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001901 }
1902 return reconfig;
1903}
1904
1905status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1906{
1907 const size_t SIZE = 256;
1908 char buffer[SIZE];
1909 String8 result;
1910
1911 PlaybackThread::dumpInternals(fd, args);
1912
1913 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1914 result.append(buffer);
1915 write(fd, result.string(), result.size());
1916 return NO_ERROR;
1917}
1918
Eric Laurent059b4be2009-11-09 23:32:22 -08001919uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07001920{
Eric Laurent059b4be2009-11-09 23:32:22 -08001921 return (uint32_t)(mOutput->latency() * 1000) / 2;
1922}
1923
1924uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1925{
1926 return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07001927}
1928
Eric Laurenta553c252009-07-17 12:17:14 -07001929// ----------------------------------------------------------------------------
Eric Laurent65b65452010-06-01 23:49:17 -07001930AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id, uint32_t device)
1931 : PlaybackThread(audioFlinger, output, id, device)
Eric Laurenta553c252009-07-17 12:17:14 -07001932{
1933 mType = PlaybackThread::DIRECT;
1934}
1935
1936AudioFlinger::DirectOutputThread::~DirectOutputThread()
1937{
1938}
1939
1940
Eric Laurent65b65452010-06-01 23:49:17 -07001941static inline int16_t clamp16(int32_t sample)
1942{
1943 if ((sample>>15) ^ (sample>>31))
1944 sample = 0x7FFF ^ (sample>>31);
1945 return sample;
1946}
1947
1948static inline
1949int32_t mul(int16_t in, int16_t v)
1950{
1951#if defined(__arm__) && !defined(__thumb__)
1952 int32_t out;
1953 asm( "smulbb %[out], %[in], %[v] \n"
1954 : [out]"=r"(out)
1955 : [in]"%r"(in), [v]"r"(v)
1956 : );
1957 return out;
1958#else
1959 return in * int32_t(v);
1960#endif
1961}
1962
1963void AudioFlinger::DirectOutputThread::applyVolume(uint16_t leftVol, uint16_t rightVol, bool ramp)
1964{
1965 // Do not apply volume on compressed audio
1966 if (!AudioSystem::isLinearPCM(mFormat)) {
1967 return;
1968 }
1969
1970 // convert to signed 16 bit before volume calculation
1971 if (mFormat == AudioSystem::PCM_8_BIT) {
1972 size_t count = mFrameCount * mChannelCount;
1973 uint8_t *src = (uint8_t *)mMixBuffer + count-1;
1974 int16_t *dst = mMixBuffer + count-1;
1975 while(count--) {
1976 *dst-- = (int16_t)(*src--^0x80) << 8;
1977 }
1978 }
1979
1980 size_t frameCount = mFrameCount;
1981 int16_t *out = mMixBuffer;
1982 if (ramp) {
1983 if (mChannelCount == 1) {
1984 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
1985 int32_t vlInc = d / (int32_t)frameCount;
1986 int32_t vl = ((int32_t)mLeftVolShort << 16);
1987 do {
1988 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
1989 out++;
1990 vl += vlInc;
1991 } while (--frameCount);
1992
1993 } else {
1994 int32_t d = ((int32_t)leftVol - (int32_t)mLeftVolShort) << 16;
1995 int32_t vlInc = d / (int32_t)frameCount;
1996 d = ((int32_t)rightVol - (int32_t)mRightVolShort) << 16;
1997 int32_t vrInc = d / (int32_t)frameCount;
1998 int32_t vl = ((int32_t)mLeftVolShort << 16);
1999 int32_t vr = ((int32_t)mRightVolShort << 16);
2000 do {
2001 out[0] = clamp16(mul(out[0], vl >> 16) >> 12);
2002 out[1] = clamp16(mul(out[1], vr >> 16) >> 12);
2003 out += 2;
2004 vl += vlInc;
2005 vr += vrInc;
2006 } while (--frameCount);
2007 }
2008 } else {
2009 if (mChannelCount == 1) {
2010 do {
2011 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2012 out++;
2013 } while (--frameCount);
2014 } else {
2015 do {
2016 out[0] = clamp16(mul(out[0], leftVol) >> 12);
2017 out[1] = clamp16(mul(out[1], rightVol) >> 12);
2018 out += 2;
2019 } while (--frameCount);
2020 }
2021 }
2022
2023 // convert back to unsigned 8 bit after volume calculation
2024 if (mFormat == AudioSystem::PCM_8_BIT) {
2025 size_t count = mFrameCount * mChannelCount;
2026 int16_t *src = mMixBuffer;
2027 uint8_t *dst = (uint8_t *)mMixBuffer;
2028 while(count--) {
2029 *dst++ = (uint8_t)(((int32_t)*src++ + (1<<7)) >> 8)^0x80;
2030 }
2031 }
2032
2033 mLeftVolShort = leftVol;
2034 mRightVolShort = rightVol;
2035}
2036
Eric Laurenta553c252009-07-17 12:17:14 -07002037bool AudioFlinger::DirectOutputThread::threadLoop()
2038{
Eric Laurent059b4be2009-11-09 23:32:22 -08002039 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002040 sp<Track> trackToRemove;
2041 sp<Track> activeTrack;
2042 nsecs_t standbyTime = systemTime();
2043 int8_t *curBuf;
2044 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002045 uint32_t activeSleepTime = activeSleepTimeUs();
2046 uint32_t idleSleepTime = idleSleepTimeUs();
2047 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08002048 // use shorter standby delay as on normal output to release
2049 // hardware resources as soon as possible
2050 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08002051
Eric Laurenta553c252009-07-17 12:17:14 -07002052
2053 while (!exitPending())
2054 {
Eric Laurent65b65452010-06-01 23:49:17 -07002055 bool rampVolume;
2056 uint16_t leftVol;
2057 uint16_t rightVol;
2058 Vector< sp<EffectChain> > effectChains;
2059
Eric Laurenta553c252009-07-17 12:17:14 -07002060 processConfigEvents();
2061
Eric Laurent059b4be2009-11-09 23:32:22 -08002062 mixerStatus = MIXER_IDLE;
2063
Eric Laurenta553c252009-07-17 12:17:14 -07002064 { // scope for the mLock
2065
2066 Mutex::Autolock _l(mLock);
2067
2068 if (checkForNewParameters_l()) {
2069 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08002070 activeSleepTime = activeSleepTimeUs();
2071 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08002072 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07002073 }
2074
2075 // put audio hardware into standby after short delay
2076 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
2077 mSuspended) {
2078 // wait until we have something to do...
2079 if (!mStandby) {
2080 LOGV("Audio hardware entering standby, mixer %p\n", this);
2081 mOutput->standby();
2082 mStandby = true;
2083 mBytesWritten = 0;
2084 }
2085
2086 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
2087 // we're about to wait, flush the binder command buffer
2088 IPCThreadState::self()->flushCommands();
2089
2090 if (exitPending()) break;
2091
2092 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
2093 mWaitWorkCV.wait(mLock);
2094 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
2095
2096 if (mMasterMute == false) {
2097 char value[PROPERTY_VALUE_MAX];
2098 property_get("ro.audio.silent", value, "0");
2099 if (atoi(value)) {
2100 LOGD("Silence is golden");
2101 setMasterMute(true);
2102 }
2103 }
2104
Eric Laurentef9500f2010-03-11 14:47:00 -08002105 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08002106 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002107 continue;
2108 }
2109 }
2110
Eric Laurent65b65452010-06-01 23:49:17 -07002111 effectChains = mEffectChains;
2112
Eric Laurenta553c252009-07-17 12:17:14 -07002113 // find out which tracks need to be processed
2114 if (mActiveTracks.size() != 0) {
2115 sp<Track> t = mActiveTracks[0].promote();
2116 if (t == 0) continue;
2117
2118 Track* const track = t.get();
2119 audio_track_cblk_t* cblk = track->cblk();
2120
2121 // The first time a track is added we wait
2122 // for all its buffers to be filled before processing it
2123 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
Eric Laurent380558b2010-04-09 06:11:48 -07002124 !track->isPaused() && !track->isTerminated())
Eric Laurenta553c252009-07-17 12:17:14 -07002125 {
2126 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
2127
Eric Laurent65b65452010-06-01 23:49:17 -07002128 if (track->mFillingUpStatus == Track::FS_FILLED) {
2129 track->mFillingUpStatus = Track::FS_ACTIVE;
2130 mLeftVolFloat = mRightVolFloat = 0;
2131 mLeftVolShort = mRightVolShort = 0;
2132 if (track->mState == TrackBase::RESUMING) {
2133 track->mState = TrackBase::ACTIVE;
2134 rampVolume = true;
2135 }
2136 } else if (cblk->server != 0) {
2137 // If the track is stopped before the first frame was mixed,
2138 // do not apply ramp
2139 rampVolume = true;
2140 }
Eric Laurenta553c252009-07-17 12:17:14 -07002141 // compute volume for this track
2142 float left, right;
2143 if (track->isMuted() || mMasterMute || track->isPausing() ||
2144 mStreamTypes[track->type()].mute) {
2145 left = right = 0;
2146 if (track->isPausing()) {
2147 track->setPaused();
2148 }
2149 } else {
2150 float typeVolume = mStreamTypes[track->type()].volume;
2151 float v = mMasterVolume * typeVolume;
2152 float v_clamped = v * cblk->volume[0];
2153 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2154 left = v_clamped/MAX_GAIN;
2155 v_clamped = v * cblk->volume[1];
2156 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
2157 right = v_clamped/MAX_GAIN;
2158 }
2159
Eric Laurent65b65452010-06-01 23:49:17 -07002160 if (left != mLeftVolFloat || right != mRightVolFloat) {
2161 mLeftVolFloat = left;
2162 mRightVolFloat = right;
Eric Laurenta553c252009-07-17 12:17:14 -07002163
Eric Laurent65b65452010-06-01 23:49:17 -07002164 // If audio HAL implements volume control,
2165 // force software volume to nominal value
2166 if (mOutput->setVolume(left, right) == NO_ERROR) {
2167 left = 1.0f;
2168 right = 1.0f;
Eric Laurenta553c252009-07-17 12:17:14 -07002169 }
Eric Laurent65b65452010-06-01 23:49:17 -07002170
2171 // Convert volumes from float to 8.24
2172 uint32_t vl = (uint32_t)(left * (1 << 24));
2173 uint32_t vr = (uint32_t)(right * (1 << 24));
2174
2175 // Delegate volume control to effect in track effect chain if needed
2176 // only one effect chain can be present on DirectOutputThread, so if
2177 // there is one, the track is connected to it
2178 if (!effectChains.isEmpty()) {
2179 // Do not ramp volume is volume is controlled by effect
2180 if(effectChains[0]->setVolume(&vl, &vr)) {
2181 rampVolume = false;
2182 }
2183 }
2184
2185 // Convert volumes from 8.24 to 4.12 format
2186 uint32_t v_clamped = (vl + (1 << 11)) >> 12;
2187 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2188 leftVol = (uint16_t)v_clamped;
2189 v_clamped = (vr + (1 << 11)) >> 12;
2190 if (v_clamped > MAX_GAIN_INT) v_clamped = MAX_GAIN_INT;
2191 rightVol = (uint16_t)v_clamped;
2192 } else {
2193 leftVol = mLeftVolShort;
2194 rightVol = mRightVolShort;
2195 rampVolume = false;
Eric Laurenta553c252009-07-17 12:17:14 -07002196 }
2197
2198 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08002199 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07002200 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08002201 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07002202 } else {
2203 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
2204 if (track->isStopped()) {
2205 track->reset();
2206 }
2207 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
2208 // We have consumed all the buffers of this track.
2209 // Remove it from the list of active tracks.
2210 trackToRemove = track;
2211 } else {
2212 // No buffers for this track. Give it a few chances to
2213 // fill a buffer, then remove it from active list.
2214 if (--(track->mRetryCount) <= 0) {
2215 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
2216 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08002217 } else {
2218 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07002219 }
Eric Laurent059b4be2009-11-09 23:32:22 -08002220 }
Eric Laurenta553c252009-07-17 12:17:14 -07002221 }
2222 }
2223
2224 // remove all the tracks that need to be...
2225 if (UNLIKELY(trackToRemove != 0)) {
2226 mActiveTracks.remove(trackToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002227 if (!effectChains.isEmpty()) {
2228 LOGV("stopping track on chain %p for session Id: %d", effectChains[0].get(), trackToRemove->sessionId());
2229 effectChains[0]->stopTrack();
2230 }
Eric Laurenta553c252009-07-17 12:17:14 -07002231 if (trackToRemove->isTerminated()) {
2232 mTracks.remove(trackToRemove);
2233 deleteTrackName_l(trackToRemove->mName);
2234 }
2235 }
Eric Laurent65b65452010-06-01 23:49:17 -07002236
2237 lockEffectChains_l();
Eric Laurenta553c252009-07-17 12:17:14 -07002238 }
2239
Eric Laurent059b4be2009-11-09 23:32:22 -08002240 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002241 AudioBufferProvider::Buffer buffer;
2242 size_t frameCount = mFrameCount;
2243 curBuf = (int8_t *)mMixBuffer;
2244 // output audio to hardware
Eric Laurent65b65452010-06-01 23:49:17 -07002245 while (frameCount) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002246 buffer.frameCount = frameCount;
2247 activeTrack->getNextBuffer(&buffer);
2248 if (UNLIKELY(buffer.raw == 0)) {
2249 memset(curBuf, 0, frameCount * mFrameSize);
2250 break;
2251 }
2252 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
2253 frameCount -= buffer.frameCount;
2254 curBuf += buffer.frameCount * mFrameSize;
2255 activeTrack->releaseBuffer(&buffer);
2256 }
2257 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08002258 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07002259 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002260 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002261 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2262 sleepTime = activeSleepTime;
2263 } else {
2264 sleepTime = idleSleepTime;
2265 }
Eric Laurent62443f52009-10-05 20:29:18 -07002266 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002267 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07002268 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07002269 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002270 }
Eric Laurent96c08a62009-09-07 08:38:38 -07002271
Eric Laurentf69a3f82009-09-22 00:35:48 -07002272 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002273 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002274 }
2275 // sleepTime == 0 means we must write to audio hardware
2276 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002277 if (mixerStatus == MIXER_TRACKS_READY) {
2278 applyVolume(leftVol, rightVol, rampVolume);
2279 }
2280 for (size_t i = 0; i < effectChains.size(); i ++) {
2281 effectChains[i]->process_l();
2282 }
2283 unlockEffectChains();
2284
Eric Laurentf69a3f82009-09-22 00:35:48 -07002285 mLastWriteTime = systemTime();
2286 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08002287 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002288 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08002289 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002290 mNumWrites++;
2291 mInWrite = false;
2292 mStandby = false;
2293 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002294 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002295 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002296 }
2297
2298 // finally let go of removed track, without the lock held
2299 // since we can't guarantee the destructors won't acquire that
2300 // same lock.
2301 trackToRemove.clear();
2302 activeTrack.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002303
2304 // Effect chains will be actually deleted here if they were removed from
2305 // mEffectChains list during mixing or effects processing
2306 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002307 }
2308
2309 if (!mStandby) {
2310 mOutput->standby();
2311 }
Eric Laurenta553c252009-07-17 12:17:14 -07002312
2313 LOGV("DirectOutputThread %p exiting", this);
2314 return false;
2315}
2316
2317// getTrackName_l() must be called with ThreadBase::mLock held
2318int AudioFlinger::DirectOutputThread::getTrackName_l()
2319{
2320 return 0;
2321}
2322
2323// deleteTrackName_l() must be called with ThreadBase::mLock held
2324void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2325{
2326}
2327
2328// checkForNewParameters_l() must be called with ThreadBase::mLock held
2329bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2330{
2331 bool reconfig = false;
2332
Eric Laurent8fce46a2009-08-04 09:45:33 -07002333 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002334 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002335 String8 keyValuePair = mNewParameters[0];
2336 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002337 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002338
Eric Laurenta553c252009-07-17 12:17:14 -07002339 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2340 // do not accept frame count changes if tracks are open as the track buffer
2341 // size depends on frame count and correct behavior would not be garantied
2342 // if frame count is changed after track creation
2343 if (!mTracks.isEmpty()) {
2344 status = INVALID_OPERATION;
2345 } else {
2346 reconfig = true;
2347 }
2348 }
2349 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002350 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002351 if (!mStandby && status == INVALID_OPERATION) {
2352 mOutput->standby();
2353 mStandby = true;
2354 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002355 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002356 }
2357 if (status == NO_ERROR && reconfig) {
2358 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002359 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002360 }
2361 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002362
2363 mNewParameters.removeAt(0);
2364
Eric Laurenta553c252009-07-17 12:17:14 -07002365 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002366 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002367 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002368 }
2369 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002370}
2371
Eric Laurent059b4be2009-11-09 23:32:22 -08002372uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002373{
2374 uint32_t time;
2375 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002376 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2377 } else {
2378 time = 10000;
2379 }
2380 return time;
2381}
2382
2383uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2384{
2385 uint32_t time;
2386 if (AudioSystem::isLinearPCM(mFormat)) {
2387 time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07002388 } else {
2389 time = 10000;
2390 }
2391 return time;
2392}
2393
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002394// ----------------------------------------------------------------------------
2395
Eric Laurent49f02be2009-11-19 09:00:56 -08002396AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent65b65452010-06-01 23:49:17 -07002397 : MixerThread(audioFlinger, mainThread->getOutput(), id, mainThread->device()), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002398{
2399 mType = PlaybackThread::DUPLICATING;
2400 addOutputTrack(mainThread);
2401}
2402
2403AudioFlinger::DuplicatingThread::~DuplicatingThread()
2404{
Eric Laurent0a080292009-12-07 10:53:10 -08002405 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2406 mOutputTracks[i]->destroy();
2407 }
Eric Laurenta553c252009-07-17 12:17:14 -07002408 mOutputTracks.clear();
2409}
2410
2411bool AudioFlinger::DuplicatingThread::threadLoop()
2412{
Eric Laurenta553c252009-07-17 12:17:14 -07002413 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002414 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002415 nsecs_t standbyTime = systemTime();
2416 size_t mixBufferSize = mFrameCount*mFrameSize;
2417 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002418 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002419 uint32_t activeSleepTime = activeSleepTimeUs();
2420 uint32_t idleSleepTime = idleSleepTimeUs();
2421 uint32_t sleepTime = idleSleepTime;
Eric Laurent65b65452010-06-01 23:49:17 -07002422 Vector< sp<EffectChain> > effectChains;
Eric Laurenta553c252009-07-17 12:17:14 -07002423
2424 while (!exitPending())
2425 {
2426 processConfigEvents();
2427
Eric Laurent059b4be2009-11-09 23:32:22 -08002428 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002429 { // scope for the mLock
2430
2431 Mutex::Autolock _l(mLock);
2432
2433 if (checkForNewParameters_l()) {
2434 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002435 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002436 activeSleepTime = activeSleepTimeUs();
2437 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002438 }
2439
2440 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2441
2442 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2443 outputTracks.add(mOutputTracks[i]);
2444 }
2445
2446 // put audio hardware into standby after short delay
2447 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2448 mSuspended) {
2449 if (!mStandby) {
2450 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002451 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002452 }
2453 mStandby = true;
2454 mBytesWritten = 0;
2455 }
2456
2457 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2458 // we're about to wait, flush the binder command buffer
2459 IPCThreadState::self()->flushCommands();
2460 outputTracks.clear();
2461
2462 if (exitPending()) break;
2463
2464 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2465 mWaitWorkCV.wait(mLock);
2466 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2467 if (mMasterMute == false) {
2468 char value[PROPERTY_VALUE_MAX];
2469 property_get("ro.audio.silent", value, "0");
2470 if (atoi(value)) {
2471 LOGD("Silence is golden");
2472 setMasterMute(true);
2473 }
2474 }
2475
2476 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002477 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002478 continue;
2479 }
2480 }
2481
Eric Laurent059b4be2009-11-09 23:32:22 -08002482 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent65b65452010-06-01 23:49:17 -07002483
2484 // prevent any changes in effect chain list and in each effect chain
2485 // during mixing and effect process as the audio buffers could be deleted
2486 // or modified if an effect is created or deleted
2487 effectChains = mEffectChains;
2488 lockEffectChains_l();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002489 }
Eric Laurenta553c252009-07-17 12:17:14 -07002490
Eric Laurent059b4be2009-11-09 23:32:22 -08002491 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002492 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002493 if (outputsReady(outputTracks)) {
Eric Laurent65b65452010-06-01 23:49:17 -07002494 mAudioMixer->process();
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002495 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002496 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002497 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002498 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002499 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002500 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002501 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002502 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2503 sleepTime = activeSleepTime;
2504 } else {
2505 sleepTime = idleSleepTime;
2506 }
Eric Laurent62443f52009-10-05 20:29:18 -07002507 } else if (mBytesWritten != 0) {
2508 // flush remaining overflow buffers in output tracks
2509 for (size_t i = 0; i < outputTracks.size(); i++) {
2510 if (outputTracks[i]->isActive()) {
2511 sleepTime = 0;
2512 writeFrames = 0;
Eric Laurent65b65452010-06-01 23:49:17 -07002513 memset(mMixBuffer, 0, mixBufferSize);
Eric Laurent62443f52009-10-05 20:29:18 -07002514 break;
2515 }
2516 }
Eric Laurenta553c252009-07-17 12:17:14 -07002517 }
2518 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002519
2520 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002521 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002522 }
2523 // sleepTime == 0 means we must write to audio hardware
2524 if (sleepTime == 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07002525 for (size_t i = 0; i < effectChains.size(); i ++) {
2526 effectChains[i]->process_l();
2527 }
2528 // enable changes in effect chain
2529 unlockEffectChains();
2530
Eric Laurent62443f52009-10-05 20:29:18 -07002531 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002532 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent65b65452010-06-01 23:49:17 -07002533 outputTracks[i]->write(mMixBuffer, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002534 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002535 mStandby = false;
2536 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002537 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07002538 // enable changes in effect chain
2539 unlockEffectChains();
Eric Laurentf69a3f82009-09-22 00:35:48 -07002540 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002541 }
2542
2543 // finally let go of all our tracks, without the lock held
2544 // since we can't guarantee the destructors won't acquire that
2545 // same lock.
2546 tracksToRemove.clear();
2547 outputTracks.clear();
Eric Laurent65b65452010-06-01 23:49:17 -07002548
2549 // Effect chains will be actually deleted here if they were removed from
2550 // mEffectChains list during mixing or effects processing
2551 effectChains.clear();
Eric Laurenta553c252009-07-17 12:17:14 -07002552 }
2553
Eric Laurenta553c252009-07-17 12:17:14 -07002554 return false;
2555}
2556
2557void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2558{
2559 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2560 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002561 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002562 mSampleRate,
2563 mFormat,
2564 mChannelCount,
2565 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002566 if (outputTrack->cblk() != NULL) {
2567 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2568 mOutputTracks.add(outputTrack);
2569 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002570 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002571 }
Eric Laurenta553c252009-07-17 12:17:14 -07002572}
2573
2574void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2575{
2576 Mutex::Autolock _l(mLock);
2577 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2578 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002579 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002580 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002581 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002582 return;
2583 }
2584 }
2585 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2586}
2587
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002588void AudioFlinger::DuplicatingThread::updateWaitTime()
2589{
2590 mWaitTimeMs = UINT_MAX;
2591 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2592 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2593 if (strong != NULL) {
2594 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2595 if (waitTimeMs < mWaitTimeMs) {
2596 mWaitTimeMs = waitTimeMs;
2597 }
2598 }
2599 }
2600}
2601
2602
2603bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2604{
2605 for (size_t i = 0; i < outputTracks.size(); i++) {
2606 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2607 if (thread == 0) {
2608 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2609 return false;
2610 }
2611 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2612 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2613 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2614 return false;
2615 }
2616 }
2617 return true;
2618}
2619
2620uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2621{
2622 return (mWaitTimeMs * 1000) / 2;
2623}
2624
Eric Laurenta553c252009-07-17 12:17:14 -07002625// ----------------------------------------------------------------------------
2626
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002627// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002628AudioFlinger::ThreadBase::TrackBase::TrackBase(
2629 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002630 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002631 uint32_t sampleRate,
2632 int format,
2633 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002634 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07002636 const sp<IMemory>& sharedBuffer,
2637 int sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002638 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002639 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002640 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002641 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002642 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002643 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002644 mClientTid(-1),
2645 mFormat(format),
Eric Laurent65b65452010-06-01 23:49:17 -07002646 mFlags(flags & ~SYSTEM_FLAGS_MASK),
2647 mSessionId(sessionId)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002648{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002649 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2650
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002651 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002652 size_t size = sizeof(audio_track_cblk_t);
2653 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2654 if (sharedBuffer == 0) {
2655 size += bufferSize;
2656 }
2657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 if (client != NULL) {
2659 mCblkMemory = client->heap()->allocate(size);
2660 if (mCblkMemory != 0) {
2661 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2662 if (mCblk) { // construct the shared structure in-place.
2663 new(mCblk) audio_track_cblk_t();
2664 // clear all buffers
2665 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002666 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002667 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 if (sharedBuffer == 0) {
2669 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2670 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2671 // Force underrun condition to avoid false underrun callback until first data is
2672 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002673 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 } else {
2675 mBuffer = sharedBuffer->pointer();
2676 }
2677 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 } else {
2680 LOGE("not enough memory for AudioTrack size=%u", size);
2681 client->heap()->dump("AudioTrack");
2682 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 } else {
2685 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2686 if (mCblk) { // construct the shared structure in-place.
2687 new(mCblk) audio_track_cblk_t();
2688 // clear all buffers
2689 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002690 mCblk->sampleRate = sampleRate;
Eric Laurentb0a01472010-05-14 05:45:46 -07002691 mCblk->channelCount = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2693 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2694 // Force underrun condition to avoid false underrun callback until first data is
2695 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002696 mCblk->flags = CBLK_UNDERRUN_ON;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002697 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2698 }
2699 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002700}
2701
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002702AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002703{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002704 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002705 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2706 if (mClient == NULL) {
2707 delete mCblk;
2708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002710 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002711 if (mClient != NULL) {
2712 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2713 mClient.clear();
2714 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002715}
2716
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002717void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002718{
2719 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002720 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002721 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002722 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002723}
2724
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002725bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002726 bool result;
2727 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002728
2729 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002730 if (!result) {
2731 LOGV("stepServer failed acquiring cblk mutex");
2732 mFlags |= STEPSERVER_FAILED;
2733 }
2734 return result;
2735}
2736
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002737void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002738 audio_track_cblk_t* cblk = this->cblk();
2739
2740 cblk->user = 0;
2741 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002742 cblk->userBase = 0;
2743 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002745 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002746}
2747
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002748sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002749{
2750 return mCblkMemory;
2751}
2752
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002753int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002754 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002755}
2756
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002757int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurentb0a01472010-05-14 05:45:46 -07002758 return (int)mCblk->channelCount;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002759}
2760
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002761void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002762 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002763 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2764 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002765
2766 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002767 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2768 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002769 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
Eric Laurentb0a01472010-05-14 05:45:46 -07002770 server %d, serverBase %d, user %d, userBase %d, channelCount %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002771 bufferStart, bufferEnd, mBuffer, mBufferEnd,
Eric Laurentb0a01472010-05-14 05:45:46 -07002772 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channelCount);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002773 return 0;
2774 }
2775
2776 return bufferStart;
2777}
2778
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002779// ----------------------------------------------------------------------------
2780
Eric Laurenta553c252009-07-17 12:17:14 -07002781// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2782AudioFlinger::PlaybackThread::Track::Track(
2783 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002784 const sp<Client>& client,
2785 int streamType,
2786 uint32_t sampleRate,
2787 int format,
2788 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002789 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002790 const sp<IMemory>& sharedBuffer,
2791 int sessionId)
2792 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer, sessionId),
2793 mMute(false), mSharedBuffer(sharedBuffer), mName(-1), mMainBuffer(NULL), mAuxBuffer(NULL), mAuxEffectId(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002794{
Eric Laurent8a77a992009-09-09 05:16:08 -07002795 if (mCblk != NULL) {
2796 sp<ThreadBase> baseThread = thread.promote();
2797 if (baseThread != 0) {
2798 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2799 mName = playbackThread->getTrackName_l();
Eric Laurent65b65452010-06-01 23:49:17 -07002800 mMainBuffer = playbackThread->mixBuffer();
Eric Laurent8a77a992009-09-09 05:16:08 -07002801 }
2802 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2803 if (mName < 0) {
2804 LOGE("no more track names available");
2805 }
2806 mVolume[0] = 1.0f;
2807 mVolume[1] = 1.0f;
2808 mStreamType = streamType;
2809 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2810 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2811 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002812 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002813}
2814
Eric Laurenta553c252009-07-17 12:17:14 -07002815AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002816{
Eric Laurenta553c252009-07-17 12:17:14 -07002817 LOGV("PlaybackThread::Track destructor");
2818 sp<ThreadBase> thread = mThread.promote();
2819 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002820 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002821 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002822 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002823}
2824
Eric Laurenta553c252009-07-17 12:17:14 -07002825void AudioFlinger::PlaybackThread::Track::destroy()
2826{
2827 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2828 // by removing it from mTracks vector, so there is a risk that this Tracks's
2829 // desctructor is called. As the destructor needs to lock mLock,
2830 // we must acquire a strong reference on this Track before locking mLock
2831 // here so that the destructor is called only when exiting this function.
2832 // On the other hand, as long as Track::destroy() is only called by
2833 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2834 // this Track with its member mTrack.
2835 sp<Track> keep(this);
2836 { // scope for mLock
2837 sp<ThreadBase> thread = mThread.promote();
2838 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002839 if (!isOutputTrack()) {
2840 if (mState == ACTIVE || mState == RESUMING) {
2841 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2842 }
2843 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002844 }
Eric Laurenta553c252009-07-17 12:17:14 -07002845 Mutex::Autolock _l(thread->mLock);
2846 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2847 playbackThread->destroyTrack_l(this);
2848 }
2849 }
2850}
2851
2852void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002853{
Eric Laurent65b65452010-06-01 23:49:17 -07002854 snprintf(buffer, size, " %05d %05d %03u %03u %03u %05u %04u %1d %1d %1d %05u %05u %05u 0x%08x 0x%08x 0x%08x 0x%08x\n",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002855 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002857 mStreamType,
2858 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07002859 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07002860 mSessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002861 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002862 mState,
2863 mMute,
2864 mFillingUpStatus,
2865 mCblk->sampleRate,
2866 mCblk->volume[0],
2867 mCblk->volume[1],
2868 mCblk->server,
Eric Laurent65b65452010-06-01 23:49:17 -07002869 mCblk->user,
2870 (int)mMainBuffer,
2871 (int)mAuxBuffer);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002872}
2873
Eric Laurenta553c252009-07-17 12:17:14 -07002874status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002875{
2876 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002877 uint32_t framesReady;
2878 uint32_t framesReq = buffer->frameCount;
2879
2880 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002881 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2882 if (!step()) goto getNextBuffer_exit;
2883 LOGV("stepServer recovered");
2884 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2885 }
2886
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002887 framesReady = cblk->framesReady();
2888
2889 if (LIKELY(framesReady)) {
2890 uint32_t s = cblk->server;
2891 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2892
2893 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2894 if (framesReq > framesReady) {
2895 framesReq = framesReady;
2896 }
2897 if (s + framesReq > bufferEnd) {
2898 framesReq = bufferEnd - s;
2899 }
2900
2901 buffer->raw = getBuffer(s, framesReq);
2902 if (buffer->raw == 0) goto getNextBuffer_exit;
2903
2904 buffer->frameCount = framesReq;
2905 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002906 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002907
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002908getNextBuffer_exit:
2909 buffer->raw = 0;
2910 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002911 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002912 return NOT_ENOUGH_DATA;
2913}
2914
Eric Laurenta553c252009-07-17 12:17:14 -07002915bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002916 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002917
2918 if (mCblk->framesReady() >= mCblk->frameCount ||
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002919 (mCblk->flags & CBLK_FORCEREADY_MSK)) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002920 mFillingUpStatus = FS_FILLED;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07002921 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002922 return true;
2923 }
2924 return false;
2925}
2926
Eric Laurenta553c252009-07-17 12:17:14 -07002927status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002928{
Eric Laurent49f02be2009-11-19 09:00:56 -08002929 status_t status = NO_ERROR;
Eric Laurenta553c252009-07-17 12:17:14 -07002930 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2931 sp<ThreadBase> thread = mThread.promote();
2932 if (thread != 0) {
2933 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002934 int state = mState;
2935 // here the track could be either new, or restarted
2936 // in both cases "unstop" the track
2937 if (mState == PAUSED) {
2938 mState = TrackBase::RESUMING;
2939 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2940 } else {
2941 mState = TrackBase::ACTIVE;
2942 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2943 }
2944
2945 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2946 thread->mLock.unlock();
2947 status = AudioSystem::startOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2948 thread->mLock.lock();
2949 }
2950 if (status == NO_ERROR) {
2951 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2952 playbackThread->addTrack_l(this);
2953 } else {
2954 mState = state;
2955 }
2956 } else {
2957 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07002958 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002959 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002960}
2961
Eric Laurenta553c252009-07-17 12:17:14 -07002962void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002963{
Eric Laurenta553c252009-07-17 12:17:14 -07002964 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2965 sp<ThreadBase> thread = mThread.promote();
2966 if (thread != 0) {
2967 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002968 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07002969 if (mState > STOPPED) {
2970 mState = STOPPED;
2971 // If the track is not active (PAUSED and buffers full), flush buffers
2972 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2973 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2974 reset();
2975 }
Eric Laurent62443f52009-10-05 20:29:18 -07002976 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002977 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002978 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
2979 thread->mLock.unlock();
2980 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2981 thread->mLock.lock();
2982 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002983 }
2984}
2985
Eric Laurenta553c252009-07-17 12:17:14 -07002986void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002987{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07002989 sp<ThreadBase> thread = mThread.promote();
2990 if (thread != 0) {
2991 Mutex::Autolock _l(thread->mLock);
2992 if (mState == ACTIVE || mState == RESUMING) {
2993 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07002994 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08002995 if (!isOutputTrack()) {
2996 thread->mLock.unlock();
2997 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2998 thread->mLock.lock();
2999 }
Eric Laurenta553c252009-07-17 12:17:14 -07003000 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003001 }
3002}
3003
Eric Laurenta553c252009-07-17 12:17:14 -07003004void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003005{
3006 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07003007 sp<ThreadBase> thread = mThread.promote();
3008 if (thread != 0) {
3009 Mutex::Autolock _l(thread->mLock);
3010 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
3011 return;
3012 }
3013 // No point remaining in PAUSED state after a flush => go to
3014 // STOPPED state
3015 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003016
Eric Laurenta553c252009-07-17 12:17:14 -07003017 mCblk->lock.lock();
3018 // NOTE: reset() will reset cblk->user and cblk->server with
3019 // the risk that at the same time, the AudioMixer is trying to read
3020 // data. In this case, getNextBuffer() would return a NULL pointer
3021 // as audio buffer => the AudioMixer code MUST always test that pointer
3022 // returned by getNextBuffer() is not NULL!
3023 reset();
3024 mCblk->lock.unlock();
3025 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003026}
3027
Eric Laurenta553c252009-07-17 12:17:14 -07003028void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003029{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003030 // Do not reset twice to avoid discarding data written just after a flush and before
3031 // the audioflinger thread detects the track is stopped.
3032 if (!mResetDone) {
3033 TrackBase::reset();
3034 // Force underrun condition to avoid false underrun callback until first data is
3035 // written to buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003036 mCblk->flags |= CBLK_UNDERRUN_ON;
3037 mCblk->flags &= ~CBLK_FORCEREADY_MSK;
Eric Laurenta553c252009-07-17 12:17:14 -07003038 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003039 mResetDone = true;
3040 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003041}
3042
Eric Laurenta553c252009-07-17 12:17:14 -07003043void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003044{
3045 mMute = muted;
3046}
3047
Eric Laurenta553c252009-07-17 12:17:14 -07003048void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003049{
3050 mVolume[0] = left;
3051 mVolume[1] = right;
3052}
3053
Eric Laurent65b65452010-06-01 23:49:17 -07003054status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
3055{
3056 status_t status = DEAD_OBJECT;
3057 sp<ThreadBase> thread = mThread.promote();
3058 if (thread != 0) {
3059 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
3060 status = playbackThread->attachAuxEffect(this, EffectId);
3061 }
3062 return status;
3063}
3064
3065void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
3066{
3067 mAuxEffectId = EffectId;
3068 mAuxBuffer = buffer;
3069}
3070
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003071// ----------------------------------------------------------------------------
3072
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003073// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07003074AudioFlinger::RecordThread::RecordTrack::RecordTrack(
3075 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 uint32_t sampleRate,
3078 int format,
3079 int channelCount,
3080 int frameCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003081 uint32_t flags,
3082 int sessionId)
Eric Laurenta553c252009-07-17 12:17:14 -07003083 : TrackBase(thread, client, sampleRate, format,
Eric Laurent65b65452010-06-01 23:49:17 -07003084 channelCount, frameCount, flags, 0, sessionId),
Eric Laurenta553c252009-07-17 12:17:14 -07003085 mOverflow(false)
3086{
Eric Laurent8a77a992009-09-09 05:16:08 -07003087 if (mCblk != NULL) {
3088 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
3089 if (format == AudioSystem::PCM_16_BIT) {
3090 mCblk->frameSize = channelCount * sizeof(int16_t);
3091 } else if (format == AudioSystem::PCM_8_BIT) {
3092 mCblk->frameSize = channelCount * sizeof(int8_t);
3093 } else {
3094 mCblk->frameSize = sizeof(int8_t);
3095 }
3096 }
Eric Laurenta553c252009-07-17 12:17:14 -07003097}
3098
3099AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100{
Eric Laurent49f02be2009-11-19 09:00:56 -08003101 sp<ThreadBase> thread = mThread.promote();
3102 if (thread != 0) {
3103 AudioSystem::releaseInput(thread->id());
3104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105}
3106
Eric Laurenta553c252009-07-17 12:17:14 -07003107status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108{
3109 audio_track_cblk_t* cblk = this->cblk();
3110 uint32_t framesAvail;
3111 uint32_t framesReq = buffer->frameCount;
3112
3113 // Check if last stepServer failed, try to step now
3114 if (mFlags & TrackBase::STEPSERVER_FAILED) {
3115 if (!step()) goto getNextBuffer_exit;
3116 LOGV("stepServer recovered");
3117 mFlags &= ~TrackBase::STEPSERVER_FAILED;
3118 }
3119
3120 framesAvail = cblk->framesAvailable_l();
3121
3122 if (LIKELY(framesAvail)) {
3123 uint32_t s = cblk->server;
3124 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
3125
3126 if (framesReq > framesAvail) {
3127 framesReq = framesAvail;
3128 }
3129 if (s + framesReq > bufferEnd) {
3130 framesReq = bufferEnd - s;
3131 }
3132
3133 buffer->raw = getBuffer(s, framesReq);
3134 if (buffer->raw == 0) goto getNextBuffer_exit;
3135
3136 buffer->frameCount = framesReq;
3137 return NO_ERROR;
3138 }
3139
3140getNextBuffer_exit:
3141 buffer->raw = 0;
3142 buffer->frameCount = 0;
3143 return NOT_ENOUGH_DATA;
3144}
3145
Eric Laurenta553c252009-07-17 12:17:14 -07003146status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147{
Eric Laurenta553c252009-07-17 12:17:14 -07003148 sp<ThreadBase> thread = mThread.promote();
3149 if (thread != 0) {
3150 RecordThread *recordThread = (RecordThread *)thread.get();
3151 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08003152 } else {
3153 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07003154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155}
3156
Eric Laurenta553c252009-07-17 12:17:14 -07003157void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158{
Eric Laurenta553c252009-07-17 12:17:14 -07003159 sp<ThreadBase> thread = mThread.promote();
3160 if (thread != 0) {
3161 RecordThread *recordThread = (RecordThread *)thread.get();
3162 recordThread->stop(this);
3163 TrackBase::reset();
3164 // Force overerrun condition to avoid false overrun callback until first data is
3165 // read from buffer
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003166 mCblk->flags |= CBLK_UNDERRUN_ON;
Eric Laurenta553c252009-07-17 12:17:14 -07003167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168}
3169
Eric Laurent3fdb1262009-11-07 00:01:32 -08003170void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
3171{
Eric Laurent65b65452010-06-01 23:49:17 -07003172 snprintf(buffer, size, " %05d %03u %03u %05d %04u %01d %05u %08x %08x\n",
Eric Laurent3fdb1262009-11-07 00:01:32 -08003173 (mClient == NULL) ? getpid() : mClient->pid(),
3174 mFormat,
Eric Laurentb0a01472010-05-14 05:45:46 -07003175 mCblk->channelCount,
Eric Laurent65b65452010-06-01 23:49:17 -07003176 mSessionId,
Eric Laurent3fdb1262009-11-07 00:01:32 -08003177 mFrameCount,
3178 mState,
3179 mCblk->sampleRate,
3180 mCblk->server,
3181 mCblk->user);
3182}
3183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184
3185// ----------------------------------------------------------------------------
3186
Eric Laurenta553c252009-07-17 12:17:14 -07003187AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
3188 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003189 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 uint32_t sampleRate,
3191 int format,
3192 int channelCount,
3193 int frameCount)
Eric Laurent65b65452010-06-01 23:49:17 -07003194 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL, 0),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003195 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196{
Eric Laurenta553c252009-07-17 12:17:14 -07003197
3198 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07003199 if (mCblk != NULL) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07003200 mCblk->flags |= CBLK_DIRECTION_OUT;
Eric Laurent6c30a712009-08-10 23:22:32 -07003201 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
3202 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
3203 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07003204 playbackThread->mTracks.add(this);
Eric Laurentb0a01472010-05-14 05:45:46 -07003205 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channelCount %d mBufferEnd %p",
3206 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channelCount, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07003207 } else {
3208 LOGW("Error creating output track on thread %p", playbackThread);
3209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210}
3211
Eric Laurenta553c252009-07-17 12:17:14 -07003212AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213{
Eric Laurent6c30a712009-08-10 23:22:32 -07003214 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215}
3216
Eric Laurenta553c252009-07-17 12:17:14 -07003217status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218{
3219 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07003220 if (status != NO_ERROR) {
3221 return status;
3222 }
3223
3224 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 mRetryCount = 127;
3226 return status;
3227}
3228
Eric Laurenta553c252009-07-17 12:17:14 -07003229void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230{
3231 Track::stop();
3232 clearBufferQueue();
3233 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003234 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235}
3236
Eric Laurenta553c252009-07-17 12:17:14 -07003237bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238{
3239 Buffer *pInBuffer;
3240 Buffer inBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003241 uint32_t channelCount = mCblk->channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003242 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 inBuffer.frameCount = frames;
3244 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07003245
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003246 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07003247
Eric Laurent62443f52009-10-05 20:29:18 -07003248 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003249 start();
3250 sp<ThreadBase> thread = mThread.promote();
3251 if (thread != 0) {
3252 MixerThread *mixerThread = (MixerThread *)thread.get();
3253 if (mCblk->frameCount > frames){
3254 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3255 uint32_t startFrames = (mCblk->frameCount - frames);
3256 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003257 pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003258 pInBuffer->frameCount = startFrames;
3259 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003260 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003261 mBufferQueue.add(pInBuffer);
3262 } else {
3263 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
3264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 }
Eric Laurenta553c252009-07-17 12:17:14 -07003266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 }
3268
Eric Laurenta553c252009-07-17 12:17:14 -07003269 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 // First write pending buffers, then new data
3271 if (mBufferQueue.size()) {
3272 pInBuffer = mBufferQueue.itemAt(0);
3273 } else {
3274 pInBuffer = &inBuffer;
3275 }
Eric Laurenta553c252009-07-17 12:17:14 -07003276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 if (pInBuffer->frameCount == 0) {
3278 break;
3279 }
Eric Laurenta553c252009-07-17 12:17:14 -07003280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 if (mOutBuffer.frameCount == 0) {
3282 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003283 nsecs_t startTime = systemTime();
3284 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003285 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07003286 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 break;
3288 }
Eric Laurenta553c252009-07-17 12:17:14 -07003289 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07003290 if (waitTimeLeftMs >= waitTimeMs) {
3291 waitTimeLeftMs -= waitTimeMs;
3292 } else {
3293 waitTimeLeftMs = 0;
3294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 }
Eric Laurenta553c252009-07-17 12:17:14 -07003296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
Eric Laurentb0a01472010-05-14 05:45:46 -07003298 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 mCblk->stepUser(outFrames);
3300 pInBuffer->frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003301 pInBuffer->i16 += outFrames * channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 mOutBuffer.frameCount -= outFrames;
Eric Laurentb0a01472010-05-14 05:45:46 -07003303 mOutBuffer.i16 += outFrames * channelCount;
Eric Laurenta553c252009-07-17 12:17:14 -07003304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 if (pInBuffer->frameCount == 0) {
3306 if (mBufferQueue.size()) {
3307 mBufferQueue.removeAt(0);
3308 delete [] pInBuffer->mBuffer;
3309 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003310 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 } else {
3312 break;
3313 }
3314 }
3315 }
Eric Laurenta553c252009-07-17 12:17:14 -07003316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 // If we could not write all frames, allocate a buffer and queue it for next time.
3318 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003319 sp<ThreadBase> thread = mThread.promote();
3320 if (thread != 0 && !thread->standby()) {
3321 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
3322 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003323 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003324 pInBuffer->frameCount = inBuffer.frameCount;
3325 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003326 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * sizeof(int16_t));
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08003327 mBufferQueue.add(pInBuffer);
3328 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
3329 } else {
3330 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
3331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 }
3333 }
Eric Laurenta553c252009-07-17 12:17:14 -07003334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07003336 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07003338 if (frames == 0 && mBufferQueue.size() == 0) {
3339 if (mCblk->user < mCblk->frameCount) {
3340 frames = mCblk->frameCount - mCblk->user;
3341 pInBuffer = new Buffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003342 pInBuffer->mBuffer = new int16_t[frames * channelCount];
Eric Laurenta553c252009-07-17 12:17:14 -07003343 pInBuffer->frameCount = frames;
3344 pInBuffer->i16 = pInBuffer->mBuffer;
Eric Laurentb0a01472010-05-14 05:45:46 -07003345 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
Eric Laurenta553c252009-07-17 12:17:14 -07003346 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07003347 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07003348 stop();
3349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 }
3351
Eric Laurenta553c252009-07-17 12:17:14 -07003352 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353}
3354
Eric Laurenta553c252009-07-17 12:17:14 -07003355status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356{
3357 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 status_t result;
3359 audio_track_cblk_t* cblk = mCblk;
3360 uint32_t framesReq = buffer->frameCount;
3361
Eric Laurenta553c252009-07-17 12:17:14 -07003362// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 uint32_t framesAvail = cblk->framesAvailable();
3366
Eric Laurenta553c252009-07-17 12:17:14 -07003367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003369 Mutex::Autolock _l(cblk->lock);
3370 goto start_loop_here;
3371 while (framesAvail == 0) {
3372 active = mActive;
3373 if (UNLIKELY(!active)) {
3374 LOGV("Not active and NO_MORE_BUFFERS");
3375 return AudioTrack::NO_MORE_BUFFERS;
3376 }
3377 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3378 if (result != NO_ERROR) {
3379 return AudioTrack::NO_MORE_BUFFERS;
3380 }
3381 // read the server count again
3382 start_loop_here:
3383 framesAvail = cblk->framesAvailable_l();
3384 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 }
3386
Eric Laurenta553c252009-07-17 12:17:14 -07003387// if (framesAvail < framesReq) {
3388// return AudioTrack::NO_MORE_BUFFERS;
3389// }
3390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 if (framesReq > framesAvail) {
3392 framesReq = framesAvail;
3393 }
3394
3395 uint32_t u = cblk->user;
3396 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3397
3398 if (u + framesReq > bufferEnd) {
3399 framesReq = bufferEnd - u;
3400 }
3401
3402 buffer->frameCount = framesReq;
3403 buffer->raw = (void *)cblk->buffer(u);
3404 return NO_ERROR;
3405}
3406
3407
Eric Laurenta553c252009-07-17 12:17:14 -07003408void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409{
3410 size_t size = mBufferQueue.size();
3411 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 for (size_t i = 0; i < size; i++) {
3414 pBuffer = mBufferQueue.itemAt(i);
3415 delete [] pBuffer->mBuffer;
3416 delete pBuffer;
3417 }
3418 mBufferQueue.clear();
3419}
3420
3421// ----------------------------------------------------------------------------
3422
3423AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3424 : RefBase(),
3425 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003426 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 mPid(pid)
3428{
3429 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3430}
3431
Eric Laurentb9481d82009-09-17 05:12:56 -07003432// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433AudioFlinger::Client::~Client()
3434{
Eric Laurentb9481d82009-09-17 05:12:56 -07003435 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436}
3437
3438const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3439{
3440 return mMemoryDealer;
3441}
3442
3443// ----------------------------------------------------------------------------
3444
Eric Laurent4f0f17d2010-05-12 02:05:53 -07003445AudioFlinger::NotificationClient::NotificationClient(const sp<AudioFlinger>& audioFlinger,
3446 const sp<IAudioFlingerClient>& client,
3447 pid_t pid)
3448 : mAudioFlinger(audioFlinger), mPid(pid), mClient(client)
3449{
3450}
3451
3452AudioFlinger::NotificationClient::~NotificationClient()
3453{
3454 mClient.clear();
3455}
3456
3457void AudioFlinger::NotificationClient::binderDied(const wp<IBinder>& who)
3458{
3459 sp<NotificationClient> keep(this);
3460 {
3461 mAudioFlinger->removeNotificationClient(mPid);
3462 }
3463}
3464
3465// ----------------------------------------------------------------------------
3466
Eric Laurenta553c252009-07-17 12:17:14 -07003467AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003468 : BnAudioTrack(),
3469 mTrack(track)
3470{
3471}
3472
3473AudioFlinger::TrackHandle::~TrackHandle() {
3474 // just stop the track on deletion, associated resources
3475 // will be freed from the main thread once all pending buffers have
3476 // been played. Unless it's not in the active track list, in which
3477 // case we free everything now...
3478 mTrack->destroy();
3479}
3480
3481status_t AudioFlinger::TrackHandle::start() {
3482 return mTrack->start();
3483}
3484
3485void AudioFlinger::TrackHandle::stop() {
3486 mTrack->stop();
3487}
3488
3489void AudioFlinger::TrackHandle::flush() {
3490 mTrack->flush();
3491}
3492
3493void AudioFlinger::TrackHandle::mute(bool e) {
3494 mTrack->mute(e);
3495}
3496
3497void AudioFlinger::TrackHandle::pause() {
3498 mTrack->pause();
3499}
3500
3501void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3502 mTrack->setVolume(left, right);
3503}
3504
3505sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3506 return mTrack->getCblk();
3507}
3508
Eric Laurent65b65452010-06-01 23:49:17 -07003509status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
3510{
3511 return mTrack->attachAuxEffect(EffectId);
3512}
3513
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003514status_t AudioFlinger::TrackHandle::onTransact(
3515 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3516{
3517 return BnAudioTrack::onTransact(code, data, reply, flags);
3518}
3519
3520// ----------------------------------------------------------------------------
3521
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003522sp<IAudioRecord> AudioFlinger::openRecord(
3523 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003524 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003525 uint32_t sampleRate,
3526 int format,
3527 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003528 int frameCount,
3529 uint32_t flags,
Eric Laurent65b65452010-06-01 23:49:17 -07003530 int *sessionId,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003531 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003532{
Eric Laurenta553c252009-07-17 12:17:14 -07003533 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003534 sp<RecordHandle> recordHandle;
3535 sp<Client> client;
3536 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003537 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003538 RecordThread *thread;
3539 size_t inFrameCount;
Eric Laurent65b65452010-06-01 23:49:17 -07003540 int lSessionId;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003541
3542 // check calling permissions
3543 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003544 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003545 goto Exit;
3546 }
3547
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003548 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003549 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003550 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003551 thread = checkRecordThread_l(input);
3552 if (thread == NULL) {
3553 lStatus = BAD_VALUE;
3554 goto Exit;
3555 }
3556
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003557 wclient = mClients.valueFor(pid);
3558 if (wclient != NULL) {
3559 client = wclient.promote();
3560 } else {
3561 client = new Client(this, pid);
3562 mClients.add(pid, client);
3563 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003564
Eric Laurent65b65452010-06-01 23:49:17 -07003565 // If no audio session id is provided, create one here
3566 if (sessionId != NULL && *sessionId != 0) {
3567 lSessionId = *sessionId;
3568 } else {
3569 lSessionId = nextUniqueId();
3570 if (sessionId != NULL) {
3571 *sessionId = lSessionId;
3572 }
3573 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003574 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003575 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
Eric Laurent65b65452010-06-01 23:49:17 -07003576 format, channelCount, frameCount, flags, lSessionId);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003578 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003579 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3580 // destructor is called by the TrackBase destructor with mLock held
3581 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 recordTrack.clear();
3583 lStatus = NO_MEMORY;
3584 goto Exit;
3585 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003586
3587 // return to handle to client
3588 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003589 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003590
3591Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003592 if (status) {
3593 *status = lStatus;
3594 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003595 return recordHandle;
3596}
3597
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003598// ----------------------------------------------------------------------------
3599
Eric Laurenta553c252009-07-17 12:17:14 -07003600AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003601 : BnAudioRecord(),
3602 mRecordTrack(recordTrack)
3603{
3604}
3605
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003606AudioFlinger::RecordHandle::~RecordHandle() {
3607 stop();
3608}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003609
3610status_t AudioFlinger::RecordHandle::start() {
3611 LOGV("RecordHandle::start()");
3612 return mRecordTrack->start();
3613}
3614
3615void AudioFlinger::RecordHandle::stop() {
3616 LOGV("RecordHandle::stop()");
3617 mRecordTrack->stop();
3618}
3619
3620sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3621 return mRecordTrack->getCblk();
3622}
3623
3624status_t AudioFlinger::RecordHandle::onTransact(
3625 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3626{
3627 return BnAudioRecord::onTransact(code, data, reply, flags);
3628}
3629
3630// ----------------------------------------------------------------------------
3631
Eric Laurent49f02be2009-11-19 09:00:56 -08003632AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3633 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003634 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003635{
Eric Laurenta553c252009-07-17 12:17:14 -07003636 mReqChannelCount = AudioSystem::popCount(channels);
3637 mReqSampleRate = sampleRate;
3638 readInputParameters();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003639}
3640
Eric Laurenta553c252009-07-17 12:17:14 -07003641
3642AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003643{
Eric Laurenta553c252009-07-17 12:17:14 -07003644 delete[] mRsmpInBuffer;
3645 if (mResampler != 0) {
3646 delete mResampler;
3647 delete[] mRsmpOutBuffer;
3648 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003649}
3650
Eric Laurenta553c252009-07-17 12:17:14 -07003651void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003652{
Eric Laurenta553c252009-07-17 12:17:14 -07003653 const size_t SIZE = 256;
3654 char buffer[SIZE];
3655
3656 snprintf(buffer, SIZE, "Record Thread %p", this);
3657
3658 run(buffer, PRIORITY_URGENT_AUDIO);
3659}
Eric Laurent49f02be2009-11-19 09:00:56 -08003660
Eric Laurenta553c252009-07-17 12:17:14 -07003661bool AudioFlinger::RecordThread::threadLoop()
3662{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003663 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003664 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003665
3666 // start recording
3667 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003668
Eric Laurenta553c252009-07-17 12:17:14 -07003669 processConfigEvents();
3670
3671 { // scope for mLock
3672 Mutex::Autolock _l(mLock);
3673 checkForNewParameters_l();
3674 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3675 if (!mStandby) {
3676 mInput->standby();
3677 mStandby = true;
3678 }
3679
3680 if (exitPending()) break;
3681
3682 LOGV("RecordThread: loop stopping");
3683 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003684 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003685 LOGV("RecordThread: loop starting");
3686 continue;
3687 }
3688 if (mActiveTrack != 0) {
3689 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003690 if (!mStandby) {
3691 mInput->standby();
3692 mStandby = true;
3693 }
Eric Laurenta553c252009-07-17 12:17:14 -07003694 mActiveTrack.clear();
3695 mStartStopCond.broadcast();
3696 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003697 if (mReqChannelCount != mActiveTrack->channelCount()) {
3698 mActiveTrack.clear();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003699 mStartStopCond.broadcast();
3700 } else if (mBytesRead != 0) {
3701 // record start succeeds only if first read from audio input
3702 // succeeds
3703 if (mBytesRead > 0) {
3704 mActiveTrack->mState = TrackBase::ACTIVE;
3705 } else {
3706 mActiveTrack.clear();
3707 }
3708 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003709 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003710 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003711 }
Eric Laurenta553c252009-07-17 12:17:14 -07003712 }
3713 }
3714
3715 if (mActiveTrack != 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003716 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3717 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003718 usleep(5000);
3719 continue;
3720 }
Eric Laurenta553c252009-07-17 12:17:14 -07003721 buffer.frameCount = mFrameCount;
3722 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3723 size_t framesOut = buffer.frameCount;
3724 if (mResampler == 0) {
3725 // no resampling
3726 while (framesOut) {
3727 size_t framesIn = mFrameCount - mRsmpInIndex;
3728 if (framesIn) {
3729 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3730 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3731 if (framesIn > framesOut)
3732 framesIn = framesOut;
3733 mRsmpInIndex += framesIn;
3734 framesOut -= framesIn;
Eric Laurentb0a01472010-05-14 05:45:46 -07003735 if ((int)mChannelCount == mReqChannelCount ||
Eric Laurenta553c252009-07-17 12:17:14 -07003736 mFormat != AudioSystem::PCM_16_BIT) {
3737 memcpy(dst, src, framesIn * mFrameSize);
3738 } else {
3739 int16_t *src16 = (int16_t *)src;
3740 int16_t *dst16 = (int16_t *)dst;
3741 if (mChannelCount == 1) {
3742 while (framesIn--) {
3743 *dst16++ = *src16;
3744 *dst16++ = *src16++;
3745 }
3746 } else {
3747 while (framesIn--) {
3748 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3749 src16 += 2;
3750 }
3751 }
3752 }
3753 }
3754 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003755 if (framesOut == mFrameCount &&
Eric Laurentb0a01472010-05-14 05:45:46 -07003756 ((int)mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003757 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003758 framesOut = 0;
3759 } else {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003760 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003761 mRsmpInIndex = 0;
3762 }
Eric Laurent9cc489a22009-12-05 05:20:01 -08003763 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003764 LOGE("Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003765 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003766 // Force input into standby so that it tries to
3767 // recover at next read attempt
3768 mInput->standby();
3769 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003770 }
Eric Laurenta553c252009-07-17 12:17:14 -07003771 mRsmpInIndex = mFrameCount;
3772 framesOut = 0;
3773 buffer.frameCount = 0;
3774 }
3775 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003776 }
3777 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003778 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003779
Eric Laurenta553c252009-07-17 12:17:14 -07003780 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3781 // alter output frame count as if we were expecting stereo samples
3782 if (mChannelCount == 1 && mReqChannelCount == 1) {
3783 framesOut >>= 1;
3784 }
3785 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3786 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3787 // are 32 bit aligned which should be always true.
3788 if (mChannelCount == 2 && mReqChannelCount == 1) {
3789 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3790 // the resampler always outputs stereo samples: do post stereo to mono conversion
3791 int16_t *src = (int16_t *)mRsmpOutBuffer;
3792 int16_t *dst = buffer.i16;
3793 while (framesOut--) {
3794 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3795 src += 2;
3796 }
3797 } else {
3798 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3799 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003800
Eric Laurenta553c252009-07-17 12:17:14 -07003801 }
3802 mActiveTrack->releaseBuffer(&buffer);
3803 mActiveTrack->overflow();
3804 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003805 // client isn't retrieving buffers fast enough
3806 else {
Eric Laurenta553c252009-07-17 12:17:14 -07003807 if (!mActiveTrack->setOverflow())
3808 LOGW("RecordThread: buffer overflow");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003809 // Release the processor for a while before asking for a new buffer.
3810 // This will give the application more chance to read from the buffer and
3811 // clear the overflow.
3812 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003813 }
3814 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003815 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003816
Eric Laurenta553c252009-07-17 12:17:14 -07003817 if (!mStandby) {
3818 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003819 }
Eric Laurenta553c252009-07-17 12:17:14 -07003820 mActiveTrack.clear();
3821
Eric Laurent49f02be2009-11-19 09:00:56 -08003822 mStartStopCond.broadcast();
3823
Eric Laurenta553c252009-07-17 12:17:14 -07003824 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003825 return false;
3826}
3827
Eric Laurenta553c252009-07-17 12:17:14 -07003828status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003829{
Eric Laurenta553c252009-07-17 12:17:14 -07003830 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003831 sp <ThreadBase> strongMe = this;
3832 status_t status = NO_ERROR;
3833 {
3834 AutoMutex lock(&mLock);
3835 if (mActiveTrack != 0) {
3836 if (recordTrack != mActiveTrack.get()) {
3837 status = -EBUSY;
3838 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003839 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003840 }
3841 return status;
3842 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003843
Eric Laurent49f02be2009-11-19 09:00:56 -08003844 recordTrack->mState = TrackBase::IDLE;
3845 mActiveTrack = recordTrack;
3846 mLock.unlock();
3847 status_t status = AudioSystem::startInput(mId);
3848 mLock.lock();
3849 if (status != NO_ERROR) {
3850 mActiveTrack.clear();
3851 return status;
3852 }
3853 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a22009-12-05 05:20:01 -08003854 mRsmpInIndex = mFrameCount;
3855 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003856 // signal thread to start
3857 LOGV("Signal record thread");
3858 mWaitWorkCV.signal();
3859 // do not wait for mStartStopCond if exiting
3860 if (mExiting) {
3861 mActiveTrack.clear();
3862 status = INVALID_OPERATION;
3863 goto startError;
3864 }
3865 mStartStopCond.wait(mLock);
3866 if (mActiveTrack == 0) {
3867 LOGV("Record failed to start");
3868 status = BAD_VALUE;
3869 goto startError;
3870 }
Eric Laurenta553c252009-07-17 12:17:14 -07003871 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003872 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003873 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003874startError:
3875 AudioSystem::stopInput(mId);
3876 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003877}
3878
Eric Laurenta553c252009-07-17 12:17:14 -07003879void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3880 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08003881 sp <ThreadBase> strongMe = this;
3882 {
3883 AutoMutex lock(&mLock);
3884 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3885 mActiveTrack->mState = TrackBase::PAUSING;
3886 // do not wait for mStartStopCond if exiting
3887 if (mExiting) {
3888 return;
3889 }
3890 mStartStopCond.wait(mLock);
3891 // if we have been restarted, recordTrack == mActiveTrack.get() here
3892 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3893 mLock.unlock();
3894 AudioSystem::stopInput(mId);
3895 mLock.lock();
Eric Laurent9cc489a22009-12-05 05:20:01 -08003896 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003897 }
3898 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003899 }
3900}
3901
Eric Laurenta553c252009-07-17 12:17:14 -07003902status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903{
3904 const size_t SIZE = 256;
3905 char buffer[SIZE];
3906 String8 result;
3907 pid_t pid = 0;
3908
Eric Laurent3fdb1262009-11-07 00:01:32 -08003909 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3910 result.append(buffer);
3911
3912 if (mActiveTrack != 0) {
3913 result.append("Active Track:\n");
Eric Laurent65b65452010-06-01 23:49:17 -07003914 result.append(" Clien Fmt Chn Session Buf S SRate Serv User\n");
Eric Laurent3fdb1262009-11-07 00:01:32 -08003915 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08003917
3918 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3919 result.append(buffer);
3920 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3921 result.append(buffer);
3922 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3923 result.append(buffer);
3924 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3925 result.append(buffer);
3926 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3927 result.append(buffer);
3928
3929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 } else {
3931 result.append("No record client\n");
3932 }
3933 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08003934
3935 dumpBase(fd, args);
3936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 return NO_ERROR;
3938}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003939
Eric Laurenta553c252009-07-17 12:17:14 -07003940status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3941{
3942 size_t framesReq = buffer->frameCount;
3943 size_t framesReady = mFrameCount - mRsmpInIndex;
3944 int channelCount;
3945
3946 if (framesReady == 0) {
Eric Laurent9cc489a22009-12-05 05:20:01 -08003947 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3948 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003949 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a22009-12-05 05:20:01 -08003950 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003951 // Force input into standby so that it tries to
3952 // recover at next read attempt
3953 mInput->standby();
3954 usleep(5000);
Eric Laurent9cc489a22009-12-05 05:20:01 -08003955 }
Eric Laurenta553c252009-07-17 12:17:14 -07003956 buffer->raw = 0;
3957 buffer->frameCount = 0;
3958 return NOT_ENOUGH_DATA;
3959 }
3960 mRsmpInIndex = 0;
3961 framesReady = mFrameCount;
3962 }
3963
3964 if (framesReq > framesReady) {
3965 framesReq = framesReady;
3966 }
3967
3968 if (mChannelCount == 1 && mReqChannelCount == 2) {
3969 channelCount = 1;
3970 } else {
3971 channelCount = 2;
3972 }
3973 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3974 buffer->frameCount = framesReq;
3975 return NO_ERROR;
3976}
3977
3978void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3979{
3980 mRsmpInIndex += buffer->frameCount;
3981 buffer->frameCount = 0;
3982}
3983
3984bool AudioFlinger::RecordThread::checkForNewParameters_l()
3985{
3986 bool reconfig = false;
3987
Eric Laurent8fce46a2009-08-04 09:45:33 -07003988 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07003989 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003990 String8 keyValuePair = mNewParameters[0];
3991 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003992 int value;
3993 int reqFormat = mFormat;
3994 int reqSamplingRate = mReqSampleRate;
3995 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003996
Eric Laurenta553c252009-07-17 12:17:14 -07003997 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3998 reqSamplingRate = value;
3999 reconfig = true;
4000 }
4001 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
4002 reqFormat = value;
4003 reconfig = true;
4004 }
4005 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
4006 reqChannelCount = AudioSystem::popCount(value);
4007 reconfig = true;
4008 }
4009 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
4010 // do not accept frame count changes if tracks are open as the track buffer
4011 // size depends on frame count and correct behavior would not be garantied
4012 // if frame count is changed after track creation
4013 if (mActiveTrack != 0) {
4014 status = INVALID_OPERATION;
4015 } else {
4016 reconfig = true;
4017 }
4018 }
4019 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07004020 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004021 if (status == INVALID_OPERATION) {
4022 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004023 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07004024 }
4025 if (reconfig) {
4026 if (status == BAD_VALUE &&
4027 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
4028 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
4029 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
4030 status = NO_ERROR;
4031 }
4032 if (status == NO_ERROR) {
4033 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004034 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07004035 }
4036 }
4037 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08004038
4039 mNewParameters.removeAt(0);
4040
Eric Laurenta553c252009-07-17 12:17:14 -07004041 mParamStatus = status;
4042 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07004043 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07004044 }
4045 return reconfig;
4046}
4047
4048String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
4049{
4050 return mInput->getParameters(keys);
4051}
4052
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004053void AudioFlinger::RecordThread::audioConfigChanged_l(int event, int param) {
Eric Laurenta553c252009-07-17 12:17:14 -07004054 AudioSystem::OutputDescriptor desc;
4055 void *param2 = 0;
4056
4057 switch (event) {
4058 case AudioSystem::INPUT_OPENED:
4059 case AudioSystem::INPUT_CONFIG_CHANGED:
Eric Laurentb0a01472010-05-14 05:45:46 -07004060 desc.channels = mChannels;
Eric Laurenta553c252009-07-17 12:17:14 -07004061 desc.samplingRate = mSampleRate;
4062 desc.format = mFormat;
4063 desc.frameCount = mFrameCount;
4064 desc.latency = 0;
4065 param2 = &desc;
4066 break;
4067
4068 case AudioSystem::INPUT_CLOSED:
4069 default:
4070 break;
4071 }
Eric Laurent49f02be2009-11-19 09:00:56 -08004072 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07004073}
4074
4075void AudioFlinger::RecordThread::readInputParameters()
4076{
4077 if (mRsmpInBuffer) delete mRsmpInBuffer;
4078 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
4079 if (mResampler) delete mResampler;
4080 mResampler = 0;
4081
4082 mSampleRate = mInput->sampleRate();
Eric Laurentb0a01472010-05-14 05:45:46 -07004083 mChannels = mInput->channels();
4084 mChannelCount = (uint16_t)AudioSystem::popCount(mChannels);
Eric Laurenta553c252009-07-17 12:17:14 -07004085 mFormat = mInput->format();
Eric Laurentb0a01472010-05-14 05:45:46 -07004086 mFrameSize = (uint16_t)mInput->frameSize();
Eric Laurenta553c252009-07-17 12:17:14 -07004087 mInputBytes = mInput->bufferSize();
4088 mFrameCount = mInputBytes / mFrameSize;
4089 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
4090
4091 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
4092 {
4093 int channelCount;
4094 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
4095 // stereo to mono post process as the resampler always outputs stereo.
4096 if (mChannelCount == 1 && mReqChannelCount == 2) {
4097 channelCount = 1;
4098 } else {
4099 channelCount = 2;
4100 }
4101 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
4102 mResampler->setSampleRate(mSampleRate);
4103 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
4104 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
4105
4106 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
4107 if (mChannelCount == 1 && mReqChannelCount == 1) {
4108 mFrameCount >>= 1;
4109 }
4110
4111 }
4112 mRsmpInIndex = mFrameCount;
4113}
4114
Eric Laurent47d0a922010-02-26 02:47:27 -08004115unsigned int AudioFlinger::RecordThread::getInputFramesLost()
4116{
4117 return mInput->getInputFramesLost();
4118}
4119
Eric Laurenta553c252009-07-17 12:17:14 -07004120// ----------------------------------------------------------------------------
4121
Eric Laurentddb78e72009-07-28 08:44:33 -07004122int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004123 uint32_t *pSamplingRate,
4124 uint32_t *pFormat,
4125 uint32_t *pChannels,
4126 uint32_t *pLatencyMs,
4127 uint32_t flags)
4128{
4129 status_t status;
4130 PlaybackThread *thread = NULL;
4131 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
4132 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4133 uint32_t format = pFormat ? *pFormat : 0;
4134 uint32_t channels = pChannels ? *pChannels : 0;
4135 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
4136
4137 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
4138 pDevices ? *pDevices : 0,
4139 samplingRate,
4140 format,
4141 channels,
4142 flags);
4143
4144 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004145 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004146 }
4147 Mutex::Autolock _l(mLock);
4148
4149 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
4150 (int *)&format,
4151 &channels,
4152 &samplingRate,
4153 &status);
4154 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
4155 output,
4156 samplingRate,
4157 format,
4158 channels,
4159 status);
4160
4161 mHardwareStatus = AUDIO_HW_IDLE;
4162 if (output != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004163 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004164 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
4165 (format != AudioSystem::PCM_16_BIT) ||
4166 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent65b65452010-06-01 23:49:17 -07004167 thread = new DirectOutputThread(this, output, id, *pDevices);
4168 LOGV("openOutput() created direct output: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004169 } else {
Eric Laurent65b65452010-06-01 23:49:17 -07004170 thread = new MixerThread(this, output, id, *pDevices);
4171 LOGV("openOutput() created mixer output: ID %d thread %p", id, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08004172
4173#ifdef LVMX
4174 unsigned bitsPerSample =
4175 (format == AudioSystem::PCM_16_BIT) ? 16 :
4176 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
4177 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
4178 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
4179
4180 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
4181 LifeVibes::setDevice(audioOutputType, *pDevices);
4182#endif
4183
Eric Laurenta553c252009-07-17 12:17:14 -07004184 }
Eric Laurent65b65452010-06-01 23:49:17 -07004185 mPlaybackThreads.add(id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004186
4187 if (pSamplingRate) *pSamplingRate = samplingRate;
4188 if (pFormat) *pFormat = format;
4189 if (pChannels) *pChannels = channels;
4190 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004191
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004192 // notify client processes of the new output creation
4193 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004194 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004195 }
4196
Eric Laurent9cc489a22009-12-05 05:20:01 -08004197 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004198}
4199
Eric Laurentddb78e72009-07-28 08:44:33 -07004200int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07004201{
4202 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07004203 MixerThread *thread1 = checkMixerThread_l(output1);
4204 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07004205
Eric Laurentddb78e72009-07-28 08:44:33 -07004206 if (thread1 == NULL || thread2 == NULL) {
4207 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
4208 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004209 }
4210
Eric Laurent65b65452010-06-01 23:49:17 -07004211 int id = nextUniqueId();
4212 DuplicatingThread *thread = new DuplicatingThread(this, thread1, id);
Eric Laurentddb78e72009-07-28 08:44:33 -07004213 thread->addOutputTrack(thread2);
Eric Laurent65b65452010-06-01 23:49:17 -07004214 mPlaybackThreads.add(id, thread);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004215 // notify client processes of the new output creation
4216 thread->audioConfigChanged_l(AudioSystem::OUTPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004217 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004218}
4219
Eric Laurentddb78e72009-07-28 08:44:33 -07004220status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004221{
Eric Laurent49018a52009-08-04 08:37:05 -07004222 // keep strong reference on the playback thread so that
4223 // it is not destroyed while exit() is executed
4224 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004225 {
4226 Mutex::Autolock _l(mLock);
4227 thread = checkPlaybackThread_l(output);
4228 if (thread == NULL) {
4229 return BAD_VALUE;
4230 }
4231
Eric Laurentddb78e72009-07-28 08:44:33 -07004232 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004233
4234 if (thread->type() == PlaybackThread::MIXER) {
4235 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004236 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
4237 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07004238 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07004239 }
4240 }
4241 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07004242 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004243 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004244 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07004245 }
4246 thread->exit();
4247
Eric Laurent49018a52009-08-04 08:37:05 -07004248 if (thread->type() != PlaybackThread::DUPLICATING) {
4249 mAudioHardware->closeOutputStream(thread->getOutput());
4250 }
Eric Laurenta553c252009-07-17 12:17:14 -07004251 return NO_ERROR;
4252}
4253
Eric Laurentddb78e72009-07-28 08:44:33 -07004254status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004255{
4256 Mutex::Autolock _l(mLock);
4257 PlaybackThread *thread = checkPlaybackThread_l(output);
4258
4259 if (thread == NULL) {
4260 return BAD_VALUE;
4261 }
4262
Eric Laurentddb78e72009-07-28 08:44:33 -07004263 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004264 thread->suspend();
4265
4266 return NO_ERROR;
4267}
4268
Eric Laurentddb78e72009-07-28 08:44:33 -07004269status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004270{
4271 Mutex::Autolock _l(mLock);
4272 PlaybackThread *thread = checkPlaybackThread_l(output);
4273
4274 if (thread == NULL) {
4275 return BAD_VALUE;
4276 }
4277
Eric Laurentddb78e72009-07-28 08:44:33 -07004278 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004279
4280 thread->restore();
4281
4282 return NO_ERROR;
4283}
4284
Eric Laurentddb78e72009-07-28 08:44:33 -07004285int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07004286 uint32_t *pSamplingRate,
4287 uint32_t *pFormat,
4288 uint32_t *pChannels,
4289 uint32_t acoustics)
4290{
4291 status_t status;
4292 RecordThread *thread = NULL;
4293 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
4294 uint32_t format = pFormat ? *pFormat : 0;
4295 uint32_t channels = pChannels ? *pChannels : 0;
4296 uint32_t reqSamplingRate = samplingRate;
4297 uint32_t reqFormat = format;
4298 uint32_t reqChannels = channels;
4299
4300 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004301 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004302 }
4303 Mutex::Autolock _l(mLock);
4304
4305 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
4306 (int *)&format,
4307 &channels,
4308 &samplingRate,
4309 &status,
4310 (AudioSystem::audio_in_acoustics)acoustics);
4311 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
4312 input,
4313 samplingRate,
4314 format,
4315 channels,
4316 acoustics,
4317 status);
4318
4319 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
4320 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
4321 // or stereo to mono conversions on 16 bit PCM inputs.
4322 if (input == 0 && status == BAD_VALUE &&
4323 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
4324 (samplingRate <= 2 * reqSamplingRate) &&
4325 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
4326 LOGV("openInput() reopening with proposed sampling rate and channels");
4327 input = mAudioHardware->openInputStream(*pDevices,
4328 (int *)&format,
4329 &channels,
4330 &samplingRate,
4331 &status,
4332 (AudioSystem::audio_in_acoustics)acoustics);
4333 }
4334
4335 if (input != 0) {
Eric Laurent65b65452010-06-01 23:49:17 -07004336 int id = nextUniqueId();
Eric Laurenta553c252009-07-17 12:17:14 -07004337 // Start record thread
Eric Laurent65b65452010-06-01 23:49:17 -07004338 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, id);
4339 mRecordThreads.add(id, thread);
4340 LOGV("openInput() created record thread: ID %d thread %p", id, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07004341 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
4342 if (pFormat) *pFormat = format;
4343 if (pChannels) *pChannels = reqChannels;
4344
4345 input->standby();
Eric Laurent9cc489a22009-12-05 05:20:01 -08004346
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004347 // notify client processes of the new input creation
4348 thread->audioConfigChanged_l(AudioSystem::INPUT_OPENED);
Eric Laurent65b65452010-06-01 23:49:17 -07004349 return id;
Eric Laurenta553c252009-07-17 12:17:14 -07004350 }
4351
Eric Laurent9cc489a22009-12-05 05:20:01 -08004352 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07004353}
4354
Eric Laurentddb78e72009-07-28 08:44:33 -07004355status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07004356{
Eric Laurent49018a52009-08-04 08:37:05 -07004357 // keep strong reference on the record thread so that
4358 // it is not destroyed while exit() is executed
4359 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07004360 {
4361 Mutex::Autolock _l(mLock);
4362 thread = checkRecordThread_l(input);
4363 if (thread == NULL) {
4364 return BAD_VALUE;
4365 }
4366
Eric Laurentddb78e72009-07-28 08:44:33 -07004367 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07004368 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08004369 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07004370 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07004371 }
4372 thread->exit();
4373
Eric Laurent49018a52009-08-04 08:37:05 -07004374 mAudioHardware->closeInputStream(thread->getInput());
4375
Eric Laurenta553c252009-07-17 12:17:14 -07004376 return NO_ERROR;
4377}
4378
Eric Laurentddb78e72009-07-28 08:44:33 -07004379status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07004380{
4381 Mutex::Autolock _l(mLock);
4382 MixerThread *dstThread = checkMixerThread_l(output);
4383 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004384 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07004385 return BAD_VALUE;
4386 }
4387
Eric Laurentddb78e72009-07-28 08:44:33 -07004388 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004389 audioConfigChanged_l(AudioSystem::STREAM_CONFIG_CHANGED, output, &stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004390
4391 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07004392 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004393 if (thread != dstThread &&
4394 thread->type() != PlaybackThread::DIRECT) {
4395 MixerThread *srcThread = (MixerThread *)thread;
Eric Laurenteb8f850d2010-05-14 03:26:45 -07004396 srcThread->invalidateTracks(stream);
Eric Laurenta553c252009-07-17 12:17:14 -07004397 }
4398 }
Eric Laurentd069f322009-09-01 05:56:26 -07004399
Eric Laurenta553c252009-07-17 12:17:14 -07004400 return NO_ERROR;
4401}
4402
Eric Laurent65b65452010-06-01 23:49:17 -07004403
4404int AudioFlinger::newAudioSessionId()
4405{
4406 return nextUniqueId();
4407}
4408
Eric Laurenta553c252009-07-17 12:17:14 -07004409// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004410AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004411{
4412 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004413 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4414 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004415 }
Eric Laurenta553c252009-07-17 12:17:14 -07004416 return thread;
4417}
4418
4419// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004420AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004421{
4422 PlaybackThread *thread = checkPlaybackThread_l(output);
4423 if (thread != NULL) {
4424 if (thread->type() == PlaybackThread::DIRECT) {
4425 thread = NULL;
4426 }
4427 }
4428 return (MixerThread *)thread;
4429}
4430
4431// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004432AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004433{
4434 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004435 if (mRecordThreads.indexOfKey(input) >= 0) {
4436 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004437 }
Eric Laurenta553c252009-07-17 12:17:14 -07004438 return thread;
4439}
4440
Eric Laurent65b65452010-06-01 23:49:17 -07004441int AudioFlinger::nextUniqueId()
4442{
4443 return android_atomic_inc(&mNextUniqueId);
4444}
4445
4446// ----------------------------------------------------------------------------
4447// Effect management
4448// ----------------------------------------------------------------------------
4449
4450
4451status_t AudioFlinger::loadEffectLibrary(const char *libPath, int *handle)
4452{
4453 Mutex::Autolock _l(mLock);
4454 return EffectLoadLibrary(libPath, handle);
4455}
4456
4457status_t AudioFlinger::unloadEffectLibrary(int handle)
4458{
4459 Mutex::Autolock _l(mLock);
4460 return EffectUnloadLibrary(handle);
4461}
4462
4463status_t AudioFlinger::queryNumberEffects(uint32_t *numEffects)
4464{
4465 Mutex::Autolock _l(mLock);
4466 return EffectQueryNumberEffects(numEffects);
4467}
4468
4469status_t AudioFlinger::queryNextEffect(effect_descriptor_t *descriptor)
4470{
4471 Mutex::Autolock _l(mLock);
4472 return EffectQueryNext(descriptor);
4473}
4474
4475status_t AudioFlinger::getEffectDescriptor(effect_uuid_t *pUuid, effect_descriptor_t *descriptor)
4476{
4477 Mutex::Autolock _l(mLock);
4478 return EffectGetDescriptor(pUuid, descriptor);
4479}
4480
4481sp<IEffect> AudioFlinger::createEffect(pid_t pid,
4482 effect_descriptor_t *pDesc,
4483 const sp<IEffectClient>& effectClient,
4484 int32_t priority,
4485 int output,
4486 int sessionId,
4487 status_t *status,
4488 int *id,
4489 int *enabled)
4490{
4491 status_t lStatus = NO_ERROR;
4492 sp<EffectHandle> handle;
4493 effect_interface_t itfe;
4494 effect_descriptor_t desc;
4495 sp<Client> client;
4496 wp<Client> wclient;
4497
4498 LOGV("createEffect pid %d, client %p, priority %d, sessionId %d, output %d", pid, effectClient.get(), priority, sessionId, output);
4499
4500 if (pDesc == NULL) {
4501 lStatus = BAD_VALUE;
4502 goto Exit;
4503 }
4504
4505 {
4506 Mutex::Autolock _l(mLock);
4507
4508 if (!EffectIsNullUuid(&pDesc->uuid)) {
4509 // if uuid is specified, request effect descriptor
4510 lStatus = EffectGetDescriptor(&pDesc->uuid, &desc);
4511 if (lStatus < 0) {
4512 LOGW("createEffect() error %d from EffectGetDescriptor", lStatus);
4513 goto Exit;
4514 }
4515 } else {
4516 // if uuid is not specified, look for an available implementation
4517 // of the required type in effect factory
4518 if (EffectIsNullUuid(&pDesc->type)) {
4519 LOGW("createEffect() no effect type");
4520 lStatus = BAD_VALUE;
4521 goto Exit;
4522 }
4523 uint32_t numEffects = 0;
4524 effect_descriptor_t d;
4525 bool found = false;
4526
4527 lStatus = EffectQueryNumberEffects(&numEffects);
4528 if (lStatus < 0) {
4529 LOGW("createEffect() error %d from EffectQueryNumberEffects", lStatus);
4530 goto Exit;
4531 }
4532 for (; numEffects > 0; numEffects--) {
4533 lStatus = EffectQueryNext(&desc);
4534 if (lStatus < 0) {
4535 LOGW("createEffect() error %d from EffectQueryNext", lStatus);
4536 continue;
4537 }
4538 if (memcmp(&desc.type, &pDesc->type, sizeof(effect_uuid_t)) == 0) {
4539 // If matching type found save effect descriptor. If the session is
4540 // 0 and the effect is not auxiliary, continue enumeration in case
4541 // an auxiliary version of this effect type is available
4542 found = true;
4543 memcpy(&d, &desc, sizeof(effect_descriptor_t));
4544 if (sessionId != 0 ||
4545 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4546 break;
4547 }
4548 }
4549 }
4550 if (!found) {
4551 lStatus = BAD_VALUE;
4552 LOGW("createEffect() effect not found");
4553 goto Exit;
4554 }
4555 // For same effect type, chose auxiliary version over insert version if
4556 // connect to output mix (Compliance to OpenSL ES)
4557 if (sessionId == 0 &&
4558 (d.flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_AUXILIARY) {
4559 memcpy(&desc, &d, sizeof(effect_descriptor_t));
4560 }
4561 }
4562
4563 // Do not allow auxiliary effects on a session different from 0 (output mix)
4564 if (sessionId != 0 &&
4565 (desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4566 lStatus = INVALID_OPERATION;
4567 goto Exit;
4568 }
4569
4570 // return effect descriptor
4571 memcpy(pDesc, &desc, sizeof(effect_descriptor_t));
4572
4573 // If output is not specified try to find a matching audio session ID in one of the
4574 // output threads.
4575 // TODO: allow attachment of effect to inputs
4576 if (output == 0) {
4577 if (sessionId == 0) {
4578 // default to first output
4579 // TODO: define criteria to choose output when not specified. Or
4580 // receive output from audio policy manager
4581 if (mPlaybackThreads.size() != 0) {
4582 output = mPlaybackThreads.keyAt(0);
4583 }
4584 } else {
4585 // look for the thread where the specified audio session is present
4586 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
4587 if (mPlaybackThreads.valueAt(i)->hasAudioSession(sessionId)) {
4588 output = mPlaybackThreads.keyAt(i);
4589 break;
4590 }
4591 }
4592 }
4593 }
4594 PlaybackThread *thread = checkPlaybackThread_l(output);
4595 if (thread == NULL) {
4596 LOGE("unknown output thread");
4597 lStatus = BAD_VALUE;
4598 goto Exit;
4599 }
4600
4601 wclient = mClients.valueFor(pid);
4602
4603 if (wclient != NULL) {
4604 client = wclient.promote();
4605 } else {
4606 client = new Client(this, pid);
4607 mClients.add(pid, client);
4608 }
4609
4610 // create effect on selected output trhead
4611 handle = thread->createEffect_l(client, effectClient, priority, sessionId, &desc, enabled, &lStatus);
4612 if (handle != 0 && id != NULL) {
4613 *id = handle->id();
4614 }
4615 }
4616
4617Exit:
4618 if(status) {
4619 *status = lStatus;
4620 }
4621 return handle;
4622}
4623
4624// PlaybackThread::createEffect_l() must be called with AudioFlinger::mLock held
4625sp<AudioFlinger::EffectHandle> AudioFlinger::PlaybackThread::createEffect_l(
4626 const sp<AudioFlinger::Client>& client,
4627 const sp<IEffectClient>& effectClient,
4628 int32_t priority,
4629 int sessionId,
4630 effect_descriptor_t *desc,
4631 int *enabled,
4632 status_t *status
4633 )
4634{
4635 sp<EffectModule> effect;
4636 sp<EffectHandle> handle;
4637 status_t lStatus;
4638 sp<Track> track;
4639 sp<EffectChain> chain;
4640 bool effectCreated = false;
4641
4642 if (mOutput == 0) {
4643 LOGW("createEffect_l() Audio driver not initialized.");
4644 lStatus = NO_INIT;
4645 goto Exit;
4646 }
4647
4648 // Do not allow auxiliary effect on session other than 0
4649 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY &&
4650 sessionId != 0) {
4651 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", desc->name, sessionId);
4652 lStatus = BAD_VALUE;
4653 goto Exit;
4654 }
4655
4656 // Do not allow effects with session ID 0 on direct output or duplicating threads
4657 // TODO: add rule for hw accelerated effects on direct outputs with non PCM format
4658 if (sessionId == 0 && mType != MIXER) {
4659 LOGW("createEffect_l() Cannot add auxiliary effect %s to session %d", desc->name, sessionId);
4660 lStatus = BAD_VALUE;
4661 goto Exit;
4662 }
4663
4664 LOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
4665
4666 { // scope for mLock
4667 Mutex::Autolock _l(mLock);
4668
4669 // check for existing effect chain with the requested audio session
4670 chain = getEffectChain_l(sessionId);
4671 if (chain == 0) {
4672 // create a new chain for this session
4673 LOGV("createEffect_l() new effect chain for session %d", sessionId);
4674 chain = new EffectChain(this, sessionId);
4675 addEffectChain_l(chain);
4676 } else {
4677 effect = chain->getEffectFromDesc(desc);
4678 }
4679
4680 LOGV("createEffect_l() got effect %p on chain %p", effect == 0 ? 0 : effect.get(), chain.get());
4681
4682 if (effect == 0) {
4683 // create a new effect module if none present in the chain
4684 effectCreated = true;
4685 effect = new EffectModule(this, chain, desc, mAudioFlinger->nextUniqueId(), sessionId);
4686 lStatus = effect->status();
4687 if (lStatus != NO_ERROR) {
4688 goto Exit;
4689 }
4690 //TODO: handle CPU load and memory usage here
4691 lStatus = chain->addEffect(effect);
4692 if (lStatus != NO_ERROR) {
4693 goto Exit;
4694 }
4695
4696 effect->setDevice(mDevice);
4697 }
4698 // create effect handle and connect it to effect module
4699 handle = new EffectHandle(effect, client, effectClient, priority);
4700 lStatus = effect->addHandle(handle);
4701 if (enabled) {
4702 *enabled = (int)effect->isEnabled();
4703 }
4704 }
4705
4706Exit:
4707 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
4708 if (chain != 0 && effectCreated) {
4709 if (chain->removeEffect(effect) == 0) {
4710 removeEffectChain_l(chain);
4711 }
4712 }
4713 handle.clear();
4714 }
4715
4716 if(status) {
4717 *status = lStatus;
4718 }
4719 return handle;
4720}
4721
4722status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
4723{
4724 int session = chain->sessionId();
4725 int16_t *buffer = mMixBuffer;
4726
4727 LOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
4728 if (session == 0) {
4729 chain->setInBuffer(buffer, false);
4730 chain->setOutBuffer(buffer);
4731 // Effect chain for session 0 is inserted at end of effect chains list
4732 // to be processed last as it contains output mix effects to apply after
4733 // all track specific effects
4734 mEffectChains.add(chain);
4735 } else {
4736 bool ownsBuffer = false;
4737 // Only one effect chain can be present in direct output thread and it uses
4738 // the mix buffer as input
4739 if (mType != DIRECT) {
4740 size_t numSamples = mFrameCount * mChannelCount;
4741 buffer = new int16_t[numSamples];
4742 memset(buffer, 0, numSamples * sizeof(int16_t));
4743 LOGV("addEffectChain_l() creating new input buffer %p session %d", buffer, session);
4744 ownsBuffer = true;
4745 }
4746 chain->setInBuffer(buffer, ownsBuffer);
4747 chain->setOutBuffer(mMixBuffer);
4748 // Effect chain for session other than 0 is inserted at beginning of effect
4749 // chains list to be processed before output mix effects. Relative order between
4750 // sessions other than 0 is not important
4751 mEffectChains.insertAt(chain, 0);
4752 }
4753
4754 // Attach all tracks with same session ID to this chain.
4755 for (size_t i = 0; i < mTracks.size(); ++i) {
4756 sp<Track> track = mTracks[i];
4757 if (session == track->sessionId()) {
4758 LOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(), buffer);
4759 track->setMainBuffer(buffer);
4760 }
4761 }
4762
4763 // indicate all active tracks in the chain
4764 for (size_t i = 0 ; i < mActiveTracks.size() ; ++i) {
4765 sp<Track> track = mActiveTracks[i].promote();
4766 if (track == 0) continue;
4767 if (session == track->sessionId()) {
4768 LOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
4769 chain->startTrack();
4770 }
4771 }
4772
4773 return NO_ERROR;
4774}
4775
4776size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
4777{
4778 int session = chain->sessionId();
4779
4780 LOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
4781
4782 for (size_t i = 0; i < mEffectChains.size(); i++) {
4783 if (chain == mEffectChains[i]) {
4784 mEffectChains.removeAt(i);
4785 // detach all tracks with same session ID from this chain
4786 for (size_t i = 0; i < mTracks.size(); ++i) {
4787 sp<Track> track = mTracks[i];
4788 if (session == track->sessionId()) {
4789 track->setMainBuffer(mMixBuffer);
4790 }
4791 }
4792 }
4793 }
4794 return mEffectChains.size();
4795}
4796
4797void AudioFlinger::PlaybackThread::lockEffectChains_l()
4798{
4799 for (size_t i = 0; i < mEffectChains.size(); i++) {
4800 mEffectChains[i]->lock();
4801 }
4802}
4803
4804void AudioFlinger::PlaybackThread::unlockEffectChains()
4805{
4806 Mutex::Autolock _l(mLock);
4807 for (size_t i = 0; i < mEffectChains.size(); i++) {
4808 mEffectChains[i]->unlock();
4809 }
4810}
4811
4812sp<AudioFlinger::EffectModule> AudioFlinger::PlaybackThread::getEffect_l(int sessionId, int effectId)
4813{
4814 sp<EffectModule> effect;
4815
4816 sp<EffectChain> chain = getEffectChain_l(sessionId);
4817 if (chain != 0) {
4818 effect = chain->getEffectFromId(effectId);
4819 }
4820 return effect;
4821}
4822
4823status_t AudioFlinger::PlaybackThread::attachAuxEffect(const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
4824{
4825 Mutex::Autolock _l(mLock);
4826 return attachAuxEffect_l(track, EffectId);
4827}
4828
4829status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(const sp<AudioFlinger::PlaybackThread::Track> track, int EffectId)
4830{
4831 status_t status = NO_ERROR;
4832
4833 if (EffectId == 0) {
4834 track->setAuxBuffer(0, NULL);
4835 } else {
4836 // Auxiliary effects are always in audio session 0
4837 sp<EffectModule> effect = getEffect_l(0, EffectId);
4838 if (effect != 0) {
4839 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4840 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
4841 } else {
4842 status = INVALID_OPERATION;
4843 }
4844 } else {
4845 status = BAD_VALUE;
4846 }
4847 }
4848 return status;
4849}
4850
4851void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
4852{
4853 for (size_t i = 0; i < mTracks.size(); ++i) {
4854 sp<Track> track = mTracks[i];
4855 if (track->auxEffectId() == effectId) {
4856 attachAuxEffect_l(track, 0);
4857 }
4858 }
4859}
4860
4861// ----------------------------------------------------------------------------
4862// EffectModule implementation
4863// ----------------------------------------------------------------------------
4864
4865#undef LOG_TAG
4866#define LOG_TAG "AudioFlinger::EffectModule"
4867
4868AudioFlinger::EffectModule::EffectModule(const wp<ThreadBase>& wThread,
4869 const wp<AudioFlinger::EffectChain>& chain,
4870 effect_descriptor_t *desc,
4871 int id,
4872 int sessionId)
4873 : mThread(wThread), mChain(chain), mId(id), mSessionId(sessionId), mEffectInterface(NULL),
4874 mStatus(NO_INIT), mState(IDLE)
4875{
4876 LOGV("Constructor %p", this);
4877 int lStatus;
4878 sp<ThreadBase> thread = mThread.promote();
4879 if (thread == 0) {
4880 return;
4881 }
4882 PlaybackThread *p = (PlaybackThread *)thread.get();
4883
4884 memcpy(&mDescriptor, desc, sizeof(effect_descriptor_t));
4885
4886 // create effect engine from effect factory
4887 mStatus = EffectCreate(&desc->uuid, &mEffectInterface);
4888 if (mStatus != NO_ERROR) {
4889 return;
4890 }
4891 lStatus = init();
4892 if (lStatus < 0) {
4893 mStatus = lStatus;
4894 goto Error;
4895 }
4896
4897 LOGV("Constructor success name %s, Interface %p", mDescriptor.name, mEffectInterface);
4898 return;
4899Error:
4900 EffectRelease(mEffectInterface);
4901 mEffectInterface = NULL;
4902 LOGV("Constructor Error %d", mStatus);
4903}
4904
4905AudioFlinger::EffectModule::~EffectModule()
4906{
4907 LOGV("Destructor %p", this);
4908 if (mEffectInterface != NULL) {
4909 // release effect engine
4910 EffectRelease(mEffectInterface);
4911 }
4912}
4913
4914status_t AudioFlinger::EffectModule::addHandle(sp<EffectHandle>& handle)
4915{
4916 status_t status;
4917
4918 Mutex::Autolock _l(mLock);
4919 // First handle in mHandles has highest priority and controls the effect module
4920 int priority = handle->priority();
4921 size_t size = mHandles.size();
4922 sp<EffectHandle> h;
4923 size_t i;
4924 for (i = 0; i < size; i++) {
4925 h = mHandles[i].promote();
4926 if (h == 0) continue;
4927 if (h->priority() <= priority) break;
4928 }
4929 // if inserted in first place, move effect control from previous owner to this handle
4930 if (i == 0) {
4931 if (h != 0) {
4932 h->setControl(false, true);
4933 }
4934 handle->setControl(true, false);
4935 status = NO_ERROR;
4936 } else {
4937 status = ALREADY_EXISTS;
4938 }
4939 mHandles.insertAt(handle, i);
4940 return status;
4941}
4942
4943size_t AudioFlinger::EffectModule::removeHandle(const wp<EffectHandle>& handle)
4944{
4945 Mutex::Autolock _l(mLock);
4946 size_t size = mHandles.size();
4947 size_t i;
4948 for (i = 0; i < size; i++) {
4949 if (mHandles[i] == handle) break;
4950 }
4951 if (i == size) {
4952 return size;
4953 }
4954 mHandles.removeAt(i);
4955 size = mHandles.size();
4956 // if removed from first place, move effect control from this handle to next in line
4957 if (i == 0 && size != 0) {
4958 sp<EffectHandle> h = mHandles[0].promote();
4959 if (h != 0) {
4960 h->setControl(true, true);
4961 }
4962 }
4963
4964 return size;
4965}
4966
4967void AudioFlinger::EffectModule::disconnect(const wp<EffectHandle>& handle)
4968{
4969 // keep a strong reference on this EffectModule to avoid calling the
4970 // destructor before we exit
4971 sp<EffectModule> keep(this);
4972 sp<ThreadBase> thread = mThread.promote();
4973 if (thread != 0) {
4974 Mutex::Autolock _l(thread->mLock);
4975 // delete the effect module if removing last handle on it
4976 if (removeHandle(handle) == 0) {
4977 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
4978 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
4979 playbackThread->detachAuxEffect_l(mId);
4980 }
4981 sp<EffectChain> chain = mChain.promote();
4982 if (chain != 0) {
4983 // remove effect chain if remove last effect
4984 if (chain->removeEffect(keep) == 0) {
4985 playbackThread->removeEffectChain_l(chain);
4986 }
4987 }
4988 }
4989 }
4990}
4991
4992void AudioFlinger::EffectModule::process()
4993{
4994 Mutex::Autolock _l(mLock);
4995
4996 if (mEffectInterface == NULL || mConfig.inputCfg.buffer.raw == NULL || mConfig.outputCfg.buffer.raw == NULL) {
4997 return;
4998 }
4999
5000 if (mState != IDLE) {
5001 // do 32 bit to 16 bit conversion for auxiliary effect input buffer
5002 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5003 AudioMixer::ditherAndClamp(mConfig.inputCfg.buffer.s32,
5004 mConfig.inputCfg.buffer.s32,
5005 mConfig.inputCfg.buffer.frameCount);
5006 }
5007
5008 // TODO: handle effects with buffer provider
5009 if (mState != ACTIVE) {
5010 uint32_t count = mConfig.inputCfg.buffer.frameCount;
5011 int32_t amp = 32767L << 16;
5012 int32_t step = amp / count;
5013 int16_t *pIn = mConfig.inputCfg.buffer.s16;
5014 int16_t *pOut = mConfig.outputCfg.buffer.s16;
5015 int inChannels;
5016 int outChannels;
5017
5018 if (mConfig.inputCfg.channels == CHANNEL_MONO) {
5019 inChannels = 1;
5020 } else {
5021 inChannels = 2;
5022 }
5023 if (mConfig.outputCfg.channels == CHANNEL_MONO) {
5024 outChannels = 1;
5025 } else {
5026 outChannels = 2;
5027 }
5028
5029 switch (mState) {
5030 case RESET:
5031 reset();
5032 // clear auxiliary effect input buffer for next accumulation
5033 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5034 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5035 }
5036 step = -step;
5037 mState = STARTING;
5038 break;
5039 case STARTING:
5040 start();
5041 amp = 0;
5042 pOut = mConfig.inputCfg.buffer.s16;
5043 outChannels = inChannels;
5044 mState = ACTIVE;
5045 break;
5046 case STOPPING:
5047 step = -step;
5048 pOut = mConfig.inputCfg.buffer.s16;
5049 outChannels = inChannels;
5050 mState = STOPPED;
5051 break;
5052 case STOPPED:
5053 stop();
5054 amp = 0;
5055 mState = IDLE;
5056 break;
5057 }
5058
5059 // ramp volume down or up before activating or deactivating the effect
5060 if (inChannels == 1) {
5061 if (outChannels == 1) {
5062 while (count--) {
5063 *pOut++ = (int16_t)(((int32_t)*pIn++ * (amp >> 16)) >> 15);
5064 amp += step;
5065 }
5066 } else {
5067 while (count--) {
5068 int32_t smp = (int16_t)(((int32_t)*pIn++ * (amp >> 16)) >> 15);
5069 *pOut++ = smp;
5070 *pOut++ = smp;
5071 amp += step;
5072 }
5073 }
5074 } else {
5075 if (outChannels == 1) {
5076 while (count--) {
5077 int32_t smp = (((int32_t)*pIn * (amp >> 16)) >> 16) +
5078 (((int32_t)*(pIn + 1) * (amp >> 16)) >> 16);
5079 pIn += 2;
5080 *pOut++ = (int16_t)smp;
5081 amp += step;
5082 }
5083 } else {
5084 while (count--) {
5085 *pOut++ = (int16_t)((int32_t)*pIn++ * (amp >> 16)) >> 15;
5086 *pOut++ = (int16_t)((int32_t)*pIn++ * (amp >> 16)) >> 15;
5087 amp += step;
5088 }
5089 }
5090 }
5091 if (mState == STARTING || mState == IDLE) {
5092 return;
5093 }
5094 }
5095
5096 // do the actual processing in the effect engine
5097 (*mEffectInterface)->process(mEffectInterface, &mConfig.inputCfg.buffer, &mConfig.outputCfg.buffer);
5098
5099 // clear auxiliary effect input buffer for next accumulation
5100 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5101 memset(mConfig.inputCfg.buffer.raw, 0, mConfig.inputCfg.buffer.frameCount*sizeof(int32_t));
5102 }
5103 } else if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_INSERT &&
5104 mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw){
5105 // If an insert effect is idle and input buffer is different from output buffer, copy input to
5106 // output
5107 sp<EffectChain> chain = mChain.promote();
5108 if (chain != 0 && chain->activeTracks() != 0) {
5109 size_t size = mConfig.inputCfg.buffer.frameCount * sizeof(int16_t);
5110 if (mConfig.inputCfg.channels == CHANNEL_STEREO) {
5111 size *= 2;
5112 }
5113 memcpy(mConfig.outputCfg.buffer.raw, mConfig.inputCfg.buffer.raw, size);
5114 }
5115 }
5116}
5117
5118void AudioFlinger::EffectModule::reset()
5119{
5120 if (mEffectInterface == NULL) {
5121 return;
5122 }
5123 (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_RESET, 0, NULL, 0, NULL);
5124}
5125
5126status_t AudioFlinger::EffectModule::configure()
5127{
5128 uint32_t channels;
5129 if (mEffectInterface == NULL) {
5130 return NO_INIT;
5131 }
5132
5133 sp<ThreadBase> thread = mThread.promote();
5134 if (thread == 0) {
5135 return DEAD_OBJECT;
5136 }
5137
5138 // TODO: handle configuration of effects replacing track process
5139 if (thread->channelCount() == 1) {
5140 channels = CHANNEL_MONO;
5141 } else {
5142 channels = CHANNEL_STEREO;
5143 }
5144
5145 if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5146 mConfig.inputCfg.channels = CHANNEL_MONO;
5147 } else {
5148 mConfig.inputCfg.channels = channels;
5149 }
5150 mConfig.outputCfg.channels = channels;
5151 mConfig.inputCfg.format = PCM_FORMAT_S15;
5152 mConfig.outputCfg.format = PCM_FORMAT_S15;
5153 mConfig.inputCfg.samplingRate = thread->sampleRate();
5154 mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate;
5155 mConfig.inputCfg.bufferProvider.cookie = NULL;
5156 mConfig.inputCfg.bufferProvider.getBuffer = NULL;
5157 mConfig.inputCfg.bufferProvider.releaseBuffer = NULL;
5158 mConfig.outputCfg.bufferProvider.cookie = NULL;
5159 mConfig.outputCfg.bufferProvider.getBuffer = NULL;
5160 mConfig.outputCfg.bufferProvider.releaseBuffer = NULL;
5161 mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ;
5162 // Insert effect:
5163 // - in session 0, always overwrites output buffer: input buffer == output buffer
5164 // - in other sessions:
5165 // last effect in the chain accumulates in output buffer: input buffer != output buffer
5166 // other effect: overwrites output buffer: input buffer == output buffer
5167 // Auxiliary effect:
5168 // accumulates in output buffer: input buffer != output buffer
5169 // Therefore: accumulate <=> input buffer != output buffer
5170 if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) {
5171 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE;
5172 } else {
5173 mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE;
5174 }
5175 mConfig.inputCfg.mask = EFFECT_CONFIG_ALL;
5176 mConfig.outputCfg.mask = EFFECT_CONFIG_ALL;
5177 mConfig.inputCfg.buffer.frameCount = thread->frameCount();
5178 mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount;
5179
5180 status_t cmdStatus;
5181 int size = sizeof(int);
5182 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_CONFIGURE, sizeof(effect_config_t), &mConfig, &size, &cmdStatus);
5183 if (status == 0) {
5184 status = cmdStatus;
5185 }
5186 return status;
5187}
5188
5189status_t AudioFlinger::EffectModule::init()
5190{
5191 if (mEffectInterface == NULL) {
5192 return NO_INIT;
5193 }
5194 status_t cmdStatus;
5195 int size = sizeof(status_t);
5196 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_INIT, 0, NULL, &size, &cmdStatus);
5197 if (status == 0) {
5198 status = cmdStatus;
5199 }
5200 return status;
5201}
5202
5203status_t AudioFlinger::EffectModule::start()
5204{
5205 if (mEffectInterface == NULL) {
5206 return NO_INIT;
5207 }
5208 status_t cmdStatus;
5209 int size = sizeof(status_t);
5210 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_ENABLE, 0, NULL, &size, &cmdStatus);
5211 if (status == 0) {
5212 status = cmdStatus;
5213 }
5214 return status;
5215}
5216
5217status_t AudioFlinger::EffectModule::stop()
5218{
5219 if (mEffectInterface == NULL) {
5220 return NO_INIT;
5221 }
5222 status_t cmdStatus;
5223 int size = sizeof(status_t);
5224 status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_DISABLE, 0, NULL, &size, &cmdStatus);
5225 if (status == 0) {
5226 status = cmdStatus;
5227 }
5228 return status;
5229}
5230
5231status_t AudioFlinger::EffectModule::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5232{
5233 LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
5234
5235 if (mEffectInterface == NULL) {
5236 return NO_INIT;
5237 }
5238 status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5239 if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
5240 int size = (replySize == NULL) ? 0 : *replySize;
5241 Mutex::Autolock _l(mLock);
5242 for (size_t i = 1; i < mHandles.size(); i++) {
5243 sp<EffectHandle> h = mHandles[i].promote();
5244 if (h != 0) {
5245 h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData);
5246 }
5247 }
5248 }
5249 return status;
5250}
5251
5252status_t AudioFlinger::EffectModule::setEnabled(bool enabled)
5253{
5254 Mutex::Autolock _l(mLock);
5255 LOGV("setEnabled %p enabled %d", this, enabled);
5256
5257 if (enabled != isEnabled()) {
5258 switch (mState) {
5259 // going from disabled to enabled
5260 case IDLE:
5261 mState = RESET;
5262 break;
5263 case STOPPING:
5264 mState = ACTIVE;
5265 break;
5266 case STOPPED:
5267 mState = STARTING;
5268 break;
5269
5270 // going from enabled to disabled
5271 case RESET:
5272 mState = IDLE;
5273 break;
5274 case STARTING:
5275 mState = STOPPED;
5276 break;
5277 case ACTIVE:
5278 mState = STOPPING;
5279 break;
5280 }
5281 for (size_t i = 1; i < mHandles.size(); i++) {
5282 sp<EffectHandle> h = mHandles[i].promote();
5283 if (h != 0) {
5284 h->setEnabled(enabled);
5285 }
5286 }
5287 }
5288 return NO_ERROR;
5289}
5290
5291bool AudioFlinger::EffectModule::isEnabled()
5292{
5293 switch (mState) {
5294 case RESET:
5295 case STARTING:
5296 case ACTIVE:
5297 return true;
5298 case IDLE:
5299 case STOPPING:
5300 case STOPPED:
5301 default:
5302 return false;
5303 }
5304}
5305
5306status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right, bool controller)
5307{
5308 status_t status = NO_ERROR;
5309
5310 // Send volume indication if EFFECT_FLAG_VOLUME_IND is set and read back altered volume
5311 // if controller flag is set (Note that controller == TRUE => EFFECT_FLAG_VOLUME_CTRL set)
5312 if ((mDescriptor.flags & EFFECT_FLAG_VOLUME_MASK) & (EFFECT_FLAG_VOLUME_CTRL|EFFECT_FLAG_VOLUME_IND)) {
5313 status_t cmdStatus;
5314 uint32_t volume[2];
5315 uint32_t *pVolume = NULL;
5316 int size = sizeof(volume);
5317 volume[0] = *left;
5318 volume[1] = *right;
5319 if (controller) {
5320 pVolume = volume;
5321 }
5322 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_VOLUME, size, volume, &size, pVolume);
5323 if (controller && status == NO_ERROR && size == sizeof(volume)) {
5324 *left = volume[0];
5325 *right = volume[1];
5326 }
5327 }
5328 return status;
5329}
5330
5331status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
5332{
5333 status_t status = NO_ERROR;
5334 if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_MASK) {
5335 status_t cmdStatus;
5336 int size = sizeof(status_t);
5337 status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_DEVICE, sizeof(uint32_t), &device, &size, &cmdStatus);
5338 if (status == NO_ERROR) {
5339 status = cmdStatus;
5340 }
5341 }
5342 return status;
5343}
5344
5345
5346status_t AudioFlinger::EffectModule::dump(int fd, const Vector<String16>& args)
5347{
5348 const size_t SIZE = 256;
5349 char buffer[SIZE];
5350 String8 result;
5351
5352 snprintf(buffer, SIZE, "\tEffect ID %d:\n", mId);
5353 result.append(buffer);
5354
5355 bool locked = tryLock(mLock);
5356 // failed to lock - AudioFlinger is probably deadlocked
5357 if (!locked) {
5358 result.append("\t\tCould not lock Fx mutex:\n");
5359 }
5360
5361 result.append("\t\tSession Status State Engine:\n");
5362 snprintf(buffer, SIZE, "\t\t%05d %03d %03d 0x%08x\n",
5363 mSessionId, mStatus, mState, (uint32_t)mEffectInterface);
5364 result.append(buffer);
5365
5366 result.append("\t\tDescriptor:\n");
5367 snprintf(buffer, SIZE, "\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5368 mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion,
5369 mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1],mDescriptor.uuid.node[2],
5370 mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]);
5371 result.append(buffer);
5372 snprintf(buffer, SIZE, "\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n",
5373 mDescriptor.type.timeLow, mDescriptor.type.timeMid, mDescriptor.type.timeHiAndVersion,
5374 mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1],mDescriptor.type.node[2],
5375 mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]);
5376 result.append(buffer);
5377 snprintf(buffer, SIZE, "\t\t- apiVersion: %04X\n\t\t- flags: %08X\n",
5378 mDescriptor.apiVersion,
5379 mDescriptor.flags);
5380 result.append(buffer);
5381 snprintf(buffer, SIZE, "\t\t- name: %s\n",
5382 mDescriptor.name);
5383 result.append(buffer);
5384 snprintf(buffer, SIZE, "\t\t- implementor: %s\n",
5385 mDescriptor.implementor);
5386 result.append(buffer);
5387
5388 result.append("\t\t- Input configuration:\n");
5389 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5390 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5391 (uint32_t)mConfig.inputCfg.buffer.raw,
5392 mConfig.inputCfg.buffer.frameCount,
5393 mConfig.inputCfg.samplingRate,
5394 mConfig.inputCfg.channels,
5395 mConfig.inputCfg.format);
5396 result.append(buffer);
5397
5398 result.append("\t\t- Output configuration:\n");
5399 result.append("\t\t\tBuffer Frames Smp rate Channels Format\n");
5400 snprintf(buffer, SIZE, "\t\t\t0x%08x %05d %05d %08x %d\n",
5401 (uint32_t)mConfig.outputCfg.buffer.raw,
5402 mConfig.outputCfg.buffer.frameCount,
5403 mConfig.outputCfg.samplingRate,
5404 mConfig.outputCfg.channels,
5405 mConfig.outputCfg.format);
5406 result.append(buffer);
5407
5408 snprintf(buffer, SIZE, "\t\t%d Clients:\n", mHandles.size());
5409 result.append(buffer);
5410 result.append("\t\t\tPid Priority Ctrl Locked client server\n");
5411 for (size_t i = 0; i < mHandles.size(); ++i) {
5412 sp<EffectHandle> handle = mHandles[i].promote();
5413 if (handle != 0) {
5414 handle->dump(buffer, SIZE);
5415 result.append(buffer);
5416 }
5417 }
5418
5419 result.append("\n");
5420
5421 write(fd, result.string(), result.length());
5422
5423 if (locked) {
5424 mLock.unlock();
5425 }
5426
5427 return NO_ERROR;
5428}
5429
5430// ----------------------------------------------------------------------------
5431// EffectHandle implementation
5432// ----------------------------------------------------------------------------
5433
5434#undef LOG_TAG
5435#define LOG_TAG "AudioFlinger::EffectHandle"
5436
5437AudioFlinger::EffectHandle::EffectHandle(const sp<EffectModule>& effect,
5438 const sp<AudioFlinger::Client>& client,
5439 const sp<IEffectClient>& effectClient,
5440 int32_t priority)
5441 : BnEffect(),
5442 mEffect(effect), mEffectClient(effectClient), mClient(client), mPriority(priority), mHasControl(false)
5443{
5444 LOGV("constructor %p", this);
5445
5446 int bufOffset = ((sizeof(effect_param_cblk_t) - 1) / sizeof(int) + 1) * sizeof(int);
5447 mCblkMemory = client->heap()->allocate(EFFECT_PARAM_BUFFER_SIZE + bufOffset);
5448 if (mCblkMemory != 0) {
5449 mCblk = static_cast<effect_param_cblk_t *>(mCblkMemory->pointer());
5450
5451 if (mCblk) {
5452 new(mCblk) effect_param_cblk_t();
5453 mBuffer = (uint8_t *)mCblk + bufOffset;
5454 }
5455 } else {
5456 LOGE("not enough memory for Effect size=%u", EFFECT_PARAM_BUFFER_SIZE + sizeof(effect_param_cblk_t));
5457 return;
5458 }
5459}
5460
5461AudioFlinger::EffectHandle::~EffectHandle()
5462{
5463 LOGV("Destructor %p", this);
5464 disconnect();
5465}
5466
5467status_t AudioFlinger::EffectHandle::enable()
5468{
5469 if (!mHasControl) return INVALID_OPERATION;
5470 if (mEffect == 0) return DEAD_OBJECT;
5471
5472 return mEffect->setEnabled(true);
5473}
5474
5475status_t AudioFlinger::EffectHandle::disable()
5476{
5477 if (!mHasControl) return INVALID_OPERATION;
5478 if (mEffect == NULL) return DEAD_OBJECT;
5479
5480 return mEffect->setEnabled(false);
5481}
5482
5483void AudioFlinger::EffectHandle::disconnect()
5484{
5485 if (mEffect == 0) {
5486 return;
5487 }
5488 mEffect->disconnect(this);
5489 // release sp on module => module destructor can be called now
5490 mEffect.clear();
5491 if (mCblk) {
5492 mCblk->~effect_param_cblk_t(); // destroy our shared-structure.
5493 }
5494 mCblkMemory.clear(); // and free the shared memory
5495 if (mClient != 0) {
5496 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
5497 mClient.clear();
5498 }
5499}
5500
5501status_t AudioFlinger::EffectHandle::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
5502{
5503 LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
5504
5505 // only get parameter command is permitted for applications not controlling the effect
5506 if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
5507 return INVALID_OPERATION;
5508 }
5509 if (mEffect == 0) return DEAD_OBJECT;
5510
5511 // handle commands that are not forwarded transparently to effect engine
5512 if (cmdCode == EFFECT_CMD_SET_PARAM_COMMIT) {
5513 // No need to trylock() here as this function is executed in the binder thread serving a particular client process:
5514 // no risk to block the whole media server process or mixer threads is we are stuck here
5515 Mutex::Autolock _l(mCblk->lock);
5516 if (mCblk->clientIndex > EFFECT_PARAM_BUFFER_SIZE ||
5517 mCblk->serverIndex > EFFECT_PARAM_BUFFER_SIZE) {
5518 mCblk->serverIndex = 0;
5519 mCblk->clientIndex = 0;
5520 return BAD_VALUE;
5521 }
5522 status_t status = NO_ERROR;
5523 while (mCblk->serverIndex < mCblk->clientIndex) {
5524 int reply;
5525 int rsize = sizeof(int);
5526 int *p = (int *)(mBuffer + mCblk->serverIndex);
5527 int size = *p++;
5528 effect_param_t *param = (effect_param_t *)p;
5529 int psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
5530 status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, psize, p, &rsize, &reply);
5531 if (ret == NO_ERROR) {
5532 if (reply != NO_ERROR) {
5533 status = reply;
5534 }
5535 } else {
5536 status = ret;
5537 }
5538 mCblk->serverIndex += size;
5539 }
5540 mCblk->serverIndex = 0;
5541 mCblk->clientIndex = 0;
5542 return status;
5543 } else if (cmdCode == EFFECT_CMD_ENABLE) {
5544 return enable();
5545 } else if (cmdCode == EFFECT_CMD_DISABLE) {
5546 return disable();
5547 }
5548
5549 return mEffect->command(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5550}
5551
5552sp<IMemory> AudioFlinger::EffectHandle::getCblk() const {
5553 return mCblkMemory;
5554}
5555
5556void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
5557{
5558 LOGV("setControl %p control %d", this, hasControl);
5559
5560 mHasControl = hasControl;
5561 if (signal && mEffectClient != 0) {
5562 mEffectClient->controlStatusChanged(hasControl);
5563 }
5564}
5565
5566void AudioFlinger::EffectHandle::commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData)
5567{
5568 if (mEffectClient != 0) {
5569 mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
5570 }
5571}
5572
5573
5574
5575void AudioFlinger::EffectHandle::setEnabled(bool enabled)
5576{
5577 if (mEffectClient != 0) {
5578 mEffectClient->enableStatusChanged(enabled);
5579 }
5580}
5581
5582status_t AudioFlinger::EffectHandle::onTransact(
5583 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5584{
5585 return BnEffect::onTransact(code, data, reply, flags);
5586}
5587
5588
5589void AudioFlinger::EffectHandle::dump(char* buffer, size_t size)
5590{
5591 bool locked = tryLock(mCblk->lock);
5592
5593 snprintf(buffer, size, "\t\t\t%05d %05d %01u %01u %05u %05u\n",
5594 (mClient == NULL) ? getpid() : mClient->pid(),
5595 mPriority,
5596 mHasControl,
5597 !locked,
5598 mCblk->clientIndex,
5599 mCblk->serverIndex
5600 );
5601
5602 if (locked) {
5603 mCblk->lock.unlock();
5604 }
5605}
5606
5607#undef LOG_TAG
5608#define LOG_TAG "AudioFlinger::EffectChain"
5609
5610AudioFlinger::EffectChain::EffectChain(const wp<ThreadBase>& wThread,
5611 int sessionId)
5612 : mThread(wThread), mSessionId(sessionId), mVolumeCtrlIdx(-1), mActiveTrackCnt(0), mOwnInBuffer(false)
5613{
5614
5615}
5616
5617AudioFlinger::EffectChain::~EffectChain()
5618{
5619 if (mOwnInBuffer) {
5620 delete mInBuffer;
5621 }
5622
5623}
5624
5625sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromDesc(effect_descriptor_t *descriptor)
5626{
5627 sp<EffectModule> effect;
5628 size_t size = mEffects.size();
5629
5630 for (size_t i = 0; i < size; i++) {
5631 if (memcmp(&mEffects[i]->desc().uuid, &descriptor->uuid, sizeof(effect_uuid_t)) == 0) {
5632 effect = mEffects[i];
5633 break;
5634 }
5635 }
5636 return effect;
5637}
5638
5639sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getEffectFromId(int id)
5640{
5641 sp<EffectModule> effect;
5642 size_t size = mEffects.size();
5643
5644 for (size_t i = 0; i < size; i++) {
5645 if (mEffects[i]->id() == id) {
5646 effect = mEffects[i];
5647 break;
5648 }
5649 }
5650 return effect;
5651}
5652
5653// Must be called with EffectChain::mLock locked
5654void AudioFlinger::EffectChain::process_l()
5655{
5656 size_t size = mEffects.size();
5657 for (size_t i = 0; i < size; i++) {
5658 mEffects[i]->process();
5659 }
5660 // if no track is active, input buffer must be cleared here as the mixer process
5661 // will not do it
5662 if (mSessionId != 0 && activeTracks() == 0) {
5663 sp<ThreadBase> thread = mThread.promote();
5664 if (thread != 0) {
5665 size_t numSamples = thread->frameCount() * thread->channelCount();
5666 memset(mInBuffer, 0, numSamples * sizeof(int16_t));
5667 }
5668 }
5669}
5670
5671status_t AudioFlinger::EffectChain::addEffect(sp<EffectModule>& effect)
5672{
5673 effect_descriptor_t desc = effect->desc();
5674 uint32_t insertPref = desc.flags & EFFECT_FLAG_INSERT_MASK;
5675
5676 Mutex::Autolock _l(mLock);
5677
5678 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
5679 // Auxiliary effects are inserted at the beginning of mEffects vector as
5680 // they are processed first and accumulated in chain input buffer
5681 mEffects.insertAt(effect, 0);
5682 sp<ThreadBase> thread = mThread.promote();
5683 if (thread == 0) {
5684 return NO_INIT;
5685 }
5686 // the input buffer for auxiliary effect contains mono samples in
5687 // 32 bit format. This is to avoid saturation in AudoMixer
5688 // accumulation stage. Saturation is done in EffectModule::process() before
5689 // calling the process in effect engine
5690 size_t numSamples = thread->frameCount();
5691 int32_t *buffer = new int32_t[numSamples];
5692 memset(buffer, 0, numSamples * sizeof(int32_t));
5693 effect->setInBuffer((int16_t *)buffer);
5694 // auxiliary effects output samples to chain input buffer for further processing
5695 // by insert effects
5696 effect->setOutBuffer(mInBuffer);
5697 } else {
5698 // Insert effects are inserted at the end of mEffects vector as they are processed
5699 // after track and auxiliary effects.
5700 // Insert effect order:
5701 // if EFFECT_FLAG_INSERT_FIRST or EFFECT_FLAG_INSERT_EXCLUSIVE insert as first insert effect
5702 // else if EFFECT_FLAG_INSERT_ANY insert after first or before last
5703 // else insert as last insert effect
5704 // Reject insertion if:
5705 // - EFFECT_FLAG_INSERT_EXCLUSIVE and another effect is present
5706 // - an effect with EFFECT_FLAG_INSERT_EXCLUSIVE is present
5707 // - EFFECT_FLAG_INSERT_FIRST or EFFECT_FLAG_INSERT_LAST and an effect with same
5708 // preference is present
5709
5710 int size = (int)mEffects.size();
5711 int idx_insert = size;
5712 int idx_insert_first = -1;
5713 int idx_insert_last = -1;
5714
5715 for (int i = 0; i < size; i++) {
5716 effect_descriptor_t d = mEffects[i]->desc();
5717 uint32_t iMode = d.flags & EFFECT_FLAG_TYPE_MASK;
5718 uint32_t iPref = d.flags & EFFECT_FLAG_INSERT_MASK;
5719 if (iMode == EFFECT_FLAG_TYPE_INSERT) {
5720 // check invalid effect chaining combinations
5721 if (insertPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
5722 iPref == EFFECT_FLAG_INSERT_EXCLUSIVE ||
5723 (insertPref != EFFECT_FLAG_INSERT_ANY
5724 && insertPref == iPref)) {
5725 return INVALID_OPERATION;
5726 }
5727 // remember position of first insert effect
5728 if (idx_insert == size) {
5729 idx_insert = i;
5730 }
5731 // remember position of insert effect claiming
5732 // first place
5733 if (iPref == EFFECT_FLAG_INSERT_FIRST) {
5734 idx_insert_first = i;
5735 }
5736 // remember position of insert effect claiming
5737 // last place
5738 if (iPref == EFFECT_FLAG_INSERT_LAST) {
5739 idx_insert_last = i;
5740 }
5741 }
5742 }
5743
5744 // modify idx_insert from first place if needed
5745 if (idx_insert_first != -1) {
5746 idx_insert = idx_insert_first + 1;
5747 } else if (idx_insert_last != -1) {
5748 idx_insert = idx_insert_last;
5749 } else if (insertPref == EFFECT_FLAG_INSERT_LAST) {
5750 idx_insert = size;
5751 }
5752
5753 // always read samples from chain input buffer
5754 effect->setInBuffer(mInBuffer);
5755
5756 // if last effect in the chain, output samples to chain
5757 // output buffer, otherwise to chain input buffer
5758 if (idx_insert == size) {
5759 if (idx_insert != 0) {
5760 mEffects[idx_insert-1]->setOutBuffer(mInBuffer);
5761 mEffects[idx_insert-1]->configure();
5762 }
5763 effect->setOutBuffer(mOutBuffer);
5764 } else {
5765 effect->setOutBuffer(mInBuffer);
5766 }
5767 status_t status = mEffects.insertAt(effect, idx_insert);
5768 // Always give volume control to last effect in chain with volume control capability
5769 if (((desc.flags & EFFECT_FLAG_VOLUME_MASK) & EFFECT_FLAG_VOLUME_CTRL) &&
5770 mVolumeCtrlIdx < idx_insert) {
5771 mVolumeCtrlIdx = idx_insert;
5772 }
5773
5774 LOGV("addEffect() effect %p, added in chain %p at rank %d status %d", effect.get(), this, idx_insert, status);
5775 }
5776 effect->configure();
5777 return NO_ERROR;
5778}
5779
5780size_t AudioFlinger::EffectChain::removeEffect(const sp<EffectModule>& effect)
5781{
5782 Mutex::Autolock _l(mLock);
5783
5784 int size = (int)mEffects.size();
5785 int i;
5786 uint32_t type = effect->desc().flags & EFFECT_FLAG_TYPE_MASK;
5787
5788 for (i = 0; i < size; i++) {
5789 if (effect == mEffects[i]) {
5790 if (type == EFFECT_FLAG_TYPE_AUXILIARY) {
5791 delete[] effect->inBuffer();
5792 } else {
5793 if (i == size - 1 && i != 0) {
5794 mEffects[i - 1]->setOutBuffer(mOutBuffer);
5795 mEffects[i - 1]->configure();
5796 }
5797 }
5798 mEffects.removeAt(i);
5799 LOGV("removeEffect() effect %p, removed from chain %p at rank %d", effect.get(), this, i);
5800 break;
5801 }
5802 }
5803 // Return volume control to last effect in chain with volume control capability
5804 if (mVolumeCtrlIdx == i) {
5805 size = (int)mEffects.size();
5806 for (i = size; i > 0; i--) {
5807 if ((mEffects[i - 1]->desc().flags & EFFECT_FLAG_VOLUME_MASK) & EFFECT_FLAG_VOLUME_CTRL) {
5808 break;
5809 }
5810 }
5811 // mVolumeCtrlIdx reset to -1 if no effect found with volume control flag set
5812 mVolumeCtrlIdx = i - 1;
5813 }
5814
5815 return mEffects.size();
5816}
5817
5818void AudioFlinger::EffectChain::setDevice(uint32_t device)
5819{
5820 size_t size = mEffects.size();
5821 for (size_t i = 0; i < size; i++) {
5822 mEffects[i]->setDevice(device);
5823 }
5824}
5825
5826bool AudioFlinger::EffectChain::setVolume(uint32_t *left, uint32_t *right)
5827{
5828 uint32_t newLeft = *left;
5829 uint32_t newRight = *right;
5830 bool hasControl = false;
5831
5832 // first get volume update from volume controller
5833 if (mVolumeCtrlIdx >= 0) {
5834 mEffects[mVolumeCtrlIdx]->setVolume(&newLeft, &newRight, true);
5835 hasControl = true;
5836 }
5837 // then indicate volume to all other effects in chain.
5838 // Pass altered volume to effects before volume controller
5839 // and requested volume to effects after controller
5840 uint32_t lVol = newLeft;
5841 uint32_t rVol = newRight;
5842 size_t size = mEffects.size();
5843 for (size_t i = 0; i < size; i++) {
5844 if ((int)i == mVolumeCtrlIdx) continue;
5845 // this also works for mVolumeCtrlIdx == -1 when there is no volume controller
5846 if ((int)i > mVolumeCtrlIdx) {
5847 lVol = *left;
5848 rVol = *right;
5849 }
5850 mEffects[i]->setVolume(&lVol, &rVol, false);
5851 }
5852 *left = newLeft;
5853 *right = newRight;
5854
5855 return hasControl;
5856}
5857
5858sp<AudioFlinger::EffectModule> AudioFlinger::EffectChain::getVolumeController()
5859{
5860 sp<EffectModule> effect;
5861 if (mVolumeCtrlIdx >= 0) {
5862 effect = mEffects[mVolumeCtrlIdx];
5863 }
5864 return effect;
5865}
5866
5867
5868status_t AudioFlinger::EffectChain::dump(int fd, const Vector<String16>& args)
5869{
5870 const size_t SIZE = 256;
5871 char buffer[SIZE];
5872 String8 result;
5873
5874 snprintf(buffer, SIZE, "Effects for session %d:\n", mSessionId);
5875 result.append(buffer);
5876
5877 bool locked = tryLock(mLock);
5878 // failed to lock - AudioFlinger is probably deadlocked
5879 if (!locked) {
5880 result.append("\tCould not lock mutex:\n");
5881 }
5882
5883 result.append("\tNum fx In buffer Out buffer Vol ctrl Active tracks:\n");
5884 snprintf(buffer, SIZE, "\t%02d 0x%08x 0x%08x %02d %d\n",
5885 mEffects.size(),
5886 (uint32_t)mInBuffer,
5887 (uint32_t)mOutBuffer,
5888 (mVolumeCtrlIdx == -1) ? 0 : mEffects[mVolumeCtrlIdx]->id(),
5889 mActiveTrackCnt);
5890 result.append(buffer);
5891 write(fd, result.string(), result.size());
5892
5893 for (size_t i = 0; i < mEffects.size(); ++i) {
5894 sp<EffectModule> effect = mEffects[i];
5895 if (effect != 0) {
5896 effect->dump(fd, args);
5897 }
5898 }
5899
5900 if (locked) {
5901 mLock.unlock();
5902 }
5903
5904 return NO_ERROR;
5905}
5906
5907#undef LOG_TAG
5908#define LOG_TAG "AudioFlinger"
5909
Eric Laurenta553c252009-07-17 12:17:14 -07005910// ----------------------------------------------------------------------------
5911
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005912status_t AudioFlinger::onTransact(
5913 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
5914{
5915 return BnAudioFlinger::onTransact(code, data, reply, flags);
5916}
5917
5918// ----------------------------------------------------------------------------
Eric Laurenta553c252009-07-17 12:17:14 -07005919
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07005920void AudioFlinger::instantiate() {
5921 defaultServiceManager()->addService(
5922 String16("media.audio_flinger"), new AudioFlinger());
5923}
5924
5925}; // namespace android