blob: 815a36737ef9cd10dbc1d8f463d0f237218f5bf7 [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>
40
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054// ----------------------------------------------------------------------------
55// the sim build doesn't have gettid
56
57#ifndef HAVE_GETTID
58# define gettid getpid
59#endif
60
61// ----------------------------------------------------------------------------
62
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070063namespace android {
64
The Android Open Source Project10592532009-03-18 17:39:46 -070065static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
66static const char* kHardwareLockedString = "Hardware lock is taken\n";
67
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080068//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070069static const float MAX_GAIN = 4096.0f;
70
71// retry counts for buffer fill timeout
72// 50 * ~20msecs = 1 second
73static const int8_t kMaxTrackRetries = 50;
74static const int8_t kMaxTrackStartupRetries = 50;
Eric Laurentef9500f2010-03-11 14:47:00 -080075// allow less retry attempts on direct output thread.
76// direct outputs can be a scarce resource in audio hardware and should
77// be released as quickly as possible.
78static const int8_t kMaxTrackRetriesDirect = 2;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070079
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -070080static const int kDumpLockRetries = 50;
81static const int kDumpLockSleep = 20000;
82
Dave Sparksd0ac8c02009-09-30 03:09:03 -070083static const nsecs_t kWarningThrottle = seconds(5);
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070086#define AUDIOFLINGER_SECURITY_ENABLED 1
87
88// ----------------------------------------------------------------------------
89
90static bool recordingAllowed() {
91#ifndef HAVE_ANDROID_OS
92 return true;
93#endif
94#if AUDIOFLINGER_SECURITY_ENABLED
95 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
96 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
97 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
98 return ok;
99#else
100 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
101 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
102 return true;
103#endif
104}
105
106static bool settingsAllowed() {
107#ifndef HAVE_ANDROID_OS
108 return true;
109#endif
110#if AUDIOFLINGER_SECURITY_ENABLED
111 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
112 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
113 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
114 return ok;
115#else
116 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
117 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
118 return true;
119#endif
120}
121
122// ----------------------------------------------------------------------------
123
124AudioFlinger::AudioFlinger()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 : BnAudioFlinger(),
Eric Laurentddb78e72009-07-28 08:44:33 -0700126 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700127{
128 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700129
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700130 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700131
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700132 mHardwareStatus = AUDIO_HW_INIT;
133 if (mAudioHardware->initCheck() == NO_ERROR) {
134 // open 16-bit output stream for s/w mixer
Eric Laurenta553c252009-07-17 12:17:14 -0700135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 setMode(AudioSystem::MODE_NORMAL);
137
138 setMasterVolume(1.0f);
139 setMasterMute(false);
Eric Laurenta553c252009-07-17 12:17:14 -0700140 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700141 LOGE("Couldn't even initialize the stubbed audio hardware!");
142 }
Glenn Kasten871c16c2010-03-05 12:18:01 -0800143#ifdef LVMX
144 LifeVibes::init();
145#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700146}
147
148AudioFlinger::~AudioFlinger()
149{
Eric Laurent7954c462009-08-28 10:39:03 -0700150 while (!mRecordThreads.isEmpty()) {
151 // closeInput() will remove first entry from mRecordThreads
152 closeInput(mRecordThreads.keyAt(0));
153 }
154 while (!mPlaybackThreads.isEmpty()) {
155 // closeOutput() will remove first entry from mPlaybackThreads
156 closeOutput(mPlaybackThreads.keyAt(0));
157 }
158 if (mAudioHardware) {
159 delete mAudioHardware;
160 }
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800161}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800162
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700163
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700164
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700165status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
166{
167 const size_t SIZE = 256;
168 char buffer[SIZE];
169 String8 result;
170
171 result.append("Clients:\n");
172 for (size_t i = 0; i < mClients.size(); ++i) {
173 wp<Client> wClient = mClients.valueAt(i);
174 if (wClient != 0) {
175 sp<Client> client = wClient.promote();
176 if (client != 0) {
177 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
178 result.append(buffer);
179 }
180 }
181 }
182 write(fd, result.string(), result.size());
183 return NO_ERROR;
184}
185
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700186
187status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
188{
189 const size_t SIZE = 256;
190 char buffer[SIZE];
191 String8 result;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700192 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700193
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700194 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700195 result.append(buffer);
196 write(fd, result.string(), result.size());
197 return NO_ERROR;
198}
199
200status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
201{
202 const size_t SIZE = 256;
203 char buffer[SIZE];
204 String8 result;
205 snprintf(buffer, SIZE, "Permission Denial: "
206 "can't dump AudioFlinger from pid=%d, uid=%d\n",
207 IPCThreadState::self()->getCallingPid(),
208 IPCThreadState::self()->getCallingUid());
209 result.append(buffer);
210 write(fd, result.string(), result.size());
211 return NO_ERROR;
212}
213
The Android Open Source Project10592532009-03-18 17:39:46 -0700214static bool tryLock(Mutex& mutex)
215{
216 bool locked = false;
217 for (int i = 0; i < kDumpLockRetries; ++i) {
218 if (mutex.tryLock() == NO_ERROR) {
219 locked = true;
220 break;
221 }
222 usleep(kDumpLockSleep);
223 }
224 return locked;
225}
226
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700227status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
228{
229 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
230 dumpPermissionDenial(fd, args);
231 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -0700232 // get state of hardware lock
233 bool hardwareLocked = tryLock(mHardwareLock);
234 if (!hardwareLocked) {
235 String8 result(kHardwareLockedString);
236 write(fd, result.string(), result.size());
237 } else {
238 mHardwareLock.unlock();
239 }
240
241 bool locked = tryLock(mLock);
242
243 // failed to lock - AudioFlinger is probably deadlocked
244 if (!locked) {
245 String8 result(kDeadlockedString);
246 write(fd, result.string(), result.size());
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700247 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700248
249 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700250 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
Eric Laurenta553c252009-07-17 12:17:14 -0700252 // dump playback threads
253 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700254 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700255 }
256
257 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700258 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700259 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700262 if (mAudioHardware) {
263 mAudioHardware->dumpState(fd, args);
264 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700265 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700266 }
267 return NO_ERROR;
268}
269
Eric Laurenta553c252009-07-17 12:17:14 -0700270
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700271// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272
273
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700274sp<IAudioTrack> AudioFlinger::createTrack(
275 pid_t pid,
276 int streamType,
277 uint32_t sampleRate,
278 int format,
279 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800280 int frameCount,
281 uint32_t flags,
282 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700283 int output,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800284 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700285{
Eric Laurenta553c252009-07-17 12:17:14 -0700286 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700287 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700288 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800289 wp<Client> wclient;
290 status_t lStatus;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800293 LOGE("invalid stream type");
294 lStatus = BAD_VALUE;
295 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700296 }
297
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800298 {
299 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700300 PlaybackThread *thread = checkPlaybackThread_l(output);
301 if (thread == NULL) {
302 LOGE("unknown output thread");
303 lStatus = BAD_VALUE;
304 goto Exit;
305 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800306
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800307 wclient = mClients.valueFor(pid);
308
309 if (wclient != NULL) {
310 client = wclient.promote();
311 } else {
312 client = new Client(this, pid);
313 mClients.add(pid, client);
314 }
Eric Laurenta553c252009-07-17 12:17:14 -0700315 track = thread->createTrack_l(client, streamType, sampleRate, format,
316 channelCount, frameCount, sharedBuffer, &lStatus);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700317 }
318 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800319 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700320 } else {
Eric Laurentb9481d82009-09-17 05:12:56 -0700321 // remove local strong reference to Client before deleting the Track so that the Client
322 // destructor is called by the TrackBase destructor with mLock held
323 client.clear();
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700324 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800325 }
326
327Exit:
328 if(status) {
329 *status = lStatus;
330 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700331 return trackHandle;
332}
333
Eric Laurentddb78e72009-07-28 08:44:33 -0700334uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700335{
Eric Laurenta553c252009-07-17 12:17:14 -0700336 Mutex::Autolock _l(mLock);
337 PlaybackThread *thread = checkPlaybackThread_l(output);
338 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700339 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700340 return 0;
341 }
342 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700343}
344
Eric Laurentddb78e72009-07-28 08:44:33 -0700345int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700346{
Eric Laurenta553c252009-07-17 12:17:14 -0700347 Mutex::Autolock _l(mLock);
348 PlaybackThread *thread = checkPlaybackThread_l(output);
349 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700350 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700351 return 0;
352 }
353 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700354}
355
Eric Laurentddb78e72009-07-28 08:44:33 -0700356int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700357{
Eric Laurenta553c252009-07-17 12:17:14 -0700358 Mutex::Autolock _l(mLock);
359 PlaybackThread *thread = checkPlaybackThread_l(output);
360 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700361 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700362 return 0;
363 }
364 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700365}
366
Eric Laurentddb78e72009-07-28 08:44:33 -0700367size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700368{
Eric Laurenta553c252009-07-17 12:17:14 -0700369 Mutex::Autolock _l(mLock);
370 PlaybackThread *thread = checkPlaybackThread_l(output);
371 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700372 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700373 return 0;
374 }
375 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700376}
377
Eric Laurentddb78e72009-07-28 08:44:33 -0700378uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800379{
Eric Laurenta553c252009-07-17 12:17:14 -0700380 Mutex::Autolock _l(mLock);
381 PlaybackThread *thread = checkPlaybackThread_l(output);
382 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700383 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700384 return 0;
385 }
386 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800387}
388
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700389status_t AudioFlinger::setMasterVolume(float value)
390{
391 // check calling permissions
392 if (!settingsAllowed()) {
393 return PERMISSION_DENIED;
394 }
395
396 // when hw supports master volume, don't scale in sw mixer
397 AutoMutex lock(mHardwareLock);
398 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
399 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700401 }
402 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700403
404 mMasterVolume = value;
405 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700406 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700407
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700408 return NO_ERROR;
409}
410
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700411status_t AudioFlinger::setMode(int mode)
412{
413 // check calling permissions
414 if (!settingsAllowed()) {
415 return PERMISSION_DENIED;
416 }
417 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
418 LOGW("Illegal value: setMode(%d)", mode);
419 return BAD_VALUE;
420 }
421
422 AutoMutex lock(mHardwareLock);
423 mHardwareStatus = AUDIO_HW_SET_MODE;
424 status_t ret = mAudioHardware->setMode(mode);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800425#ifdef LVMX
426 if (NO_ERROR == ret) {
427 LifeVibes::setMode(mode);
428 }
429#endif
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700430 mHardwareStatus = AUDIO_HW_IDLE;
431 return ret;
432}
433
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700434status_t AudioFlinger::setMicMute(bool state)
435{
436 // check calling permissions
437 if (!settingsAllowed()) {
438 return PERMISSION_DENIED;
439 }
440
441 AutoMutex lock(mHardwareLock);
442 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
443 status_t ret = mAudioHardware->setMicMute(state);
444 mHardwareStatus = AUDIO_HW_IDLE;
445 return ret;
446}
447
448bool AudioFlinger::getMicMute() const
449{
450 bool state = AudioSystem::MODE_INVALID;
451 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
452 mAudioHardware->getMicMute(&state);
453 mHardwareStatus = AUDIO_HW_IDLE;
454 return state;
455}
456
457status_t AudioFlinger::setMasterMute(bool muted)
458{
459 // check calling permissions
460 if (!settingsAllowed()) {
461 return PERMISSION_DENIED;
462 }
Eric Laurenta553c252009-07-17 12:17:14 -0700463
464 mMasterMute = muted;
465 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700466 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700467
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700468 return NO_ERROR;
469}
470
471float AudioFlinger::masterVolume() const
472{
Eric Laurenta553c252009-07-17 12:17:14 -0700473 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700474}
475
476bool AudioFlinger::masterMute() const
477{
Eric Laurenta553c252009-07-17 12:17:14 -0700478 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700479}
480
Eric Laurentddb78e72009-07-28 08:44:33 -0700481status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700482{
483 // check calling permissions
484 if (!settingsAllowed()) {
485 return PERMISSION_DENIED;
486 }
487
Eric Laurenta553c252009-07-17 12:17:14 -0700488 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700489 return BAD_VALUE;
490 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800491
Eric Laurenta553c252009-07-17 12:17:14 -0700492 AutoMutex lock(mLock);
493 PlaybackThread *thread = NULL;
494 if (output) {
495 thread = checkPlaybackThread_l(output);
496 if (thread == NULL) {
497 return BAD_VALUE;
498 }
499 }
500
Eric Laurenta553c252009-07-17 12:17:14 -0700501 mStreamTypes[stream].volume = value;
502
503 if (thread == NULL) {
Eric Laurent415f3e22009-10-21 08:14:22 -0700504 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700505 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent415f3e22009-10-21 08:14:22 -0700506 }
Eric Laurenta553c252009-07-17 12:17:14 -0700507 } else {
508 thread->setStreamVolume(stream, value);
509 }
Eric Laurentef028272009-04-21 07:56:33 -0700510
Eric Laurent415f3e22009-10-21 08:14:22 -0700511 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700512}
513
514status_t AudioFlinger::setStreamMute(int stream, bool muted)
515{
516 // check calling permissions
517 if (!settingsAllowed()) {
518 return PERMISSION_DENIED;
519 }
520
Eric Laurenta553c252009-07-17 12:17:14 -0700521 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700522 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700523 return BAD_VALUE;
524 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700525
Eric Laurenta553c252009-07-17 12:17:14 -0700526 mStreamTypes[stream].mute = muted;
527 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700528 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700530 return NO_ERROR;
531}
532
Eric Laurentddb78e72009-07-28 08:44:33 -0700533float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700534{
Eric Laurenta553c252009-07-17 12:17:14 -0700535 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700536 return 0.0f;
537 }
Eric Laurenta553c252009-07-17 12:17:14 -0700538
539 AutoMutex lock(mLock);
540 float volume;
541 if (output) {
542 PlaybackThread *thread = checkPlaybackThread_l(output);
543 if (thread == NULL) {
544 return 0.0f;
545 }
546 volume = thread->streamVolume(stream);
547 } else {
548 volume = mStreamTypes[stream].volume;
549 }
550
Eric Laurentef028272009-04-21 07:56:33 -0700551 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700552}
553
554bool AudioFlinger::streamMute(int stream) const
555{
Eric Laurenta553c252009-07-17 12:17:14 -0700556 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700557 return true;
558 }
Eric Laurenta553c252009-07-17 12:17:14 -0700559
560 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700561}
562
Eric Laurent23f25cd2010-01-25 08:49:09 -0800563bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700564{
Eric Laurent4e646332009-07-09 03:20:57 -0700565 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700566 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurent23f25cd2010-01-25 08:49:09 -0800567 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
Eric Laurenta553c252009-07-17 12:17:14 -0700568 return true;
569 }
570 }
571 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700572}
573
Eric Laurentddb78e72009-07-28 08:44:33 -0700574status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700575{
Eric Laurenta553c252009-07-17 12:17:14 -0700576 status_t result;
577
Eric Laurentddb78e72009-07-28 08:44:33 -0700578 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700579 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
580 // check calling permissions
581 if (!settingsAllowed()) {
582 return PERMISSION_DENIED;
The Android Open Source Project9266c552009-01-15 16:12:10 -0800583 }
Eric Laurenta553c252009-07-17 12:17:14 -0700584
Glenn Kasten871c16c2010-03-05 12:18:01 -0800585#ifdef LVMX
586 AudioParameter param = AudioParameter(keyValuePairs);
587 LifeVibes::setParameters(ioHandle,keyValuePairs);
588 String8 key = String8(AudioParameter::keyRouting);
589 int device;
590 if (NO_ERROR != param.getInt(key, device)) {
591 device = -1;
592 }
593
594 key = String8(LifevibesTag);
595 String8 value;
596 int musicEnabled = -1;
597 if (NO_ERROR == param.get(key, value)) {
598 if (value == LifevibesEnable) {
599 musicEnabled = 1;
600 } else if (value == LifevibesDisable) {
601 musicEnabled = 0;
602 }
603 }
604#endif
605
Eric Laurenta553c252009-07-17 12:17:14 -0700606 // ioHandle == 0 means the parameters are global to the audio hardware interface
607 if (ioHandle == 0) {
608 AutoMutex lock(mHardwareLock);
609 mHardwareStatus = AUDIO_SET_PARAMETER;
610 result = mAudioHardware->setParameters(keyValuePairs);
Glenn Kasten871c16c2010-03-05 12:18:01 -0800611#ifdef LVMX
612 if ((NO_ERROR == result) && (musicEnabled != -1)) {
613 LifeVibes::enableMusic((bool) musicEnabled);
614 }
615#endif
Eric Laurenta553c252009-07-17 12:17:14 -0700616 mHardwareStatus = AUDIO_HW_IDLE;
617 return result;
618 }
619
Eric Laurentb7d94602009-09-29 11:12:57 -0700620 // hold a strong ref on thread in case closeOutput() or closeInput() is called
621 // and the thread is exited once the lock is released
622 sp<ThreadBase> thread;
623 {
624 Mutex::Autolock _l(mLock);
625 thread = checkPlaybackThread_l(ioHandle);
626 if (thread == NULL) {
627 thread = checkRecordThread_l(ioHandle);
628 }
Eric Laurenta553c252009-07-17 12:17:14 -0700629 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700630 if (thread != NULL) {
Glenn Kasten871c16c2010-03-05 12:18:01 -0800631 result = thread->setParameters(keyValuePairs);
632#ifdef LVMX
633 if ((NO_ERROR == result) && (device != -1)) {
634 LifeVibes::setDevice(LifeVibes::threadIdToAudioOutputType(thread->id()), device);
635 }
636#endif
637 return result;
Eric Laurenta553c252009-07-17 12:17:14 -0700638 }
Eric Laurenta553c252009-07-17 12:17:14 -0700639 return BAD_VALUE;
640}
641
Eric Laurentddb78e72009-07-28 08:44:33 -0700642String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700643{
Eric Laurentddb78e72009-07-28 08:44:33 -0700644// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-07-17 12:17:14 -0700645// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
646
647 if (ioHandle == 0) {
648 return mAudioHardware->getParameters(keys);
649 }
Eric Laurentb7d94602009-09-29 11:12:57 -0700650
651 Mutex::Autolock _l(mLock);
652
Eric Laurenta553c252009-07-17 12:17:14 -0700653 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
654 if (playbackThread != NULL) {
655 return playbackThread->getParameters(keys);
656 }
657 RecordThread *recordThread = checkRecordThread_l(ioHandle);
658 if (recordThread != NULL) {
659 return recordThread->getParameters(keys);
660 }
661 return String8("");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700662}
663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
665{
666 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
667}
668
Eric Laurent47d0a922010-02-26 02:47:27 -0800669unsigned int AudioFlinger::getInputFramesLost(int ioHandle)
670{
671 if (ioHandle == 0) {
672 return 0;
673 }
674
675 Mutex::Autolock _l(mLock);
676
677 RecordThread *recordThread = checkRecordThread_l(ioHandle);
678 if (recordThread != NULL) {
679 return recordThread->getInputFramesLost();
680 }
681 return 0;
682}
683
Eric Laurent415f3e22009-10-21 08:14:22 -0700684status_t AudioFlinger::setVoiceVolume(float value)
685{
686 // check calling permissions
687 if (!settingsAllowed()) {
688 return PERMISSION_DENIED;
689 }
690
691 AutoMutex lock(mHardwareLock);
692 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
693 status_t ret = mAudioHardware->setVoiceVolume(value);
694 mHardwareStatus = AUDIO_HW_IDLE;
695
696 return ret;
697}
698
Eric Laurent0986e792010-01-19 17:37:09 -0800699status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
700{
701 status_t status;
702
703 Mutex::Autolock _l(mLock);
704
705 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
706 if (playbackThread != NULL) {
707 return playbackThread->getRenderPosition(halFrames, dspFrames);
708 }
709
710 return BAD_VALUE;
711}
712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
714{
Eric Laurenta553c252009-07-17 12:17:14 -0700715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
717 Mutex::Autolock _l(mLock);
718
719 sp<IBinder> binder = client->asBinder();
720 if (mNotificationClients.indexOf(binder) < 0) {
721 LOGV("Adding notification client %p", binder.get());
722 binder->linkToDeath(this);
723 mNotificationClients.add(binder);
Eric Laurenta553c252009-07-17 12:17:14 -0700724 }
725
726 // the config change is always sent from playback or record threads to avoid deadlock
727 // with AudioSystem::gLock
728 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700729 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurenta553c252009-07-17 12:17:14 -0700730 }
731
732 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700733 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
735}
736
737void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurenta553c252009-07-17 12:17:14 -0700738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
740 Mutex::Autolock _l(mLock);
741
742 IBinder *binder = who.unsafe_get();
743
744 if (binder != NULL) {
745 int index = mNotificationClients.indexOf(binder);
746 if (index >= 0) {
747 LOGV("Removing notification client %p", binder);
748 mNotificationClients.removeAt(index);
749 }
750 }
751}
752
Eric Laurent296a0ec2009-09-15 07:10:12 -0700753// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent49f02be2009-11-19 09:00:56 -0800754void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2) {
755 size_t size = mNotificationClients.size();
756 for (size_t i = 0; i < size; i++) {
757 sp<IBinder> binder = mNotificationClients.itemAt(i);
758 LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
759 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
760 client->ioConfigChanged(event, ioHandle, param2);
Eric Laurenta553c252009-07-17 12:17:14 -0700761 }
762}
763
Eric Laurentb9481d82009-09-17 05:12:56 -0700764// removeClient_l() must be called with AudioFlinger::mLock held
765void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700766{
Eric Laurentb9481d82009-09-17 05:12:56 -0700767 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 -0700768 mClients.removeItem(pid);
769}
770
Eric Laurenta553c252009-07-17 12:17:14 -0700771// ----------------------------------------------------------------------------
772
Eric Laurent49f02be2009-11-19 09:00:56 -0800773AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurenta553c252009-07-17 12:17:14 -0700774 : Thread(false),
775 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent49f02be2009-11-19 09:00:56 -0800776 mFormat(0), mFrameSize(1), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700777{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778}
779
Eric Laurenta553c252009-07-17 12:17:14 -0700780AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700782 mParamCond.broadcast();
783 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784}
785
Eric Laurenta553c252009-07-17 12:17:14 -0700786void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700787{
Eric Laurentb7d94602009-09-29 11:12:57 -0700788 // keep a strong ref on ourself so that we wont get
Eric Laurenta553c252009-07-17 12:17:14 -0700789 // destroyed in the middle of requestExitAndWait()
790 sp <ThreadBase> strongMe = this;
791
792 LOGV("ThreadBase::exit");
793 {
794 AutoMutex lock(&mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -0800795 mExiting = true;
Eric Laurenta553c252009-07-17 12:17:14 -0700796 requestExit();
797 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700798 }
Eric Laurenta553c252009-07-17 12:17:14 -0700799 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700800}
Eric Laurenta553c252009-07-17 12:17:14 -0700801
802uint32_t AudioFlinger::ThreadBase::sampleRate() const
803{
804 return mSampleRate;
805}
806
807int AudioFlinger::ThreadBase::channelCount() const
808{
809 return mChannelCount;
810}
811
812int AudioFlinger::ThreadBase::format() const
813{
814 return mFormat;
815}
816
817size_t AudioFlinger::ThreadBase::frameCount() const
818{
819 return mFrameCount;
820}
821
822status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
823{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700824 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700825
Eric Laurent8fce46a2009-08-04 09:45:33 -0700826 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700827 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700828
Eric Laurent8fce46a2009-08-04 09:45:33 -0700829 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700830 mWaitWorkCV.signal();
Eric Laurentb7d94602009-09-29 11:12:57 -0700831 // wait condition with timeout in case the thread loop has exited
832 // before the request could be processed
833 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
834 status = mParamStatus;
835 mWaitWorkCV.signal();
836 } else {
837 status = TIMED_OUT;
838 }
Eric Laurent8fce46a2009-08-04 09:45:33 -0700839 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700840}
841
842void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
843{
844 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700845 sendConfigEvent_l(event, param);
846}
847
848// sendConfigEvent_l() must be called with ThreadBase::mLock held
849void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
850{
Eric Laurenta553c252009-07-17 12:17:14 -0700851 ConfigEvent *configEvent = new ConfigEvent();
852 configEvent->mEvent = event;
853 configEvent->mParam = param;
854 mConfigEvents.add(configEvent);
855 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
856 mWaitWorkCV.signal();
857}
858
859void AudioFlinger::ThreadBase::processConfigEvents()
860{
861 mLock.lock();
862 while(!mConfigEvents.isEmpty()) {
863 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
864 ConfigEvent *configEvent = mConfigEvents[0];
865 mConfigEvents.removeAt(0);
Eric Laurent296a0ec2009-09-15 07:10:12 -0700866 // release mLock because audioConfigChanged() will lock AudioFlinger mLock
867 // before calling Audioflinger::audioConfigChanged_l() thus creating
Eric Laurenta553c252009-07-17 12:17:14 -0700868 // potential cross deadlock between AudioFlinger::mLock and mLock
869 mLock.unlock();
870 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
871 delete configEvent;
872 mLock.lock();
873 }
874 mLock.unlock();
875}
876
Eric Laurent3fdb1262009-11-07 00:01:32 -0800877status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
878{
879 const size_t SIZE = 256;
880 char buffer[SIZE];
881 String8 result;
882
883 bool locked = tryLock(mLock);
884 if (!locked) {
885 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
886 write(fd, buffer, strlen(buffer));
887 }
888
889 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
890 result.append(buffer);
891 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
892 result.append(buffer);
893 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
894 result.append(buffer);
895 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
896 result.append(buffer);
897 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
898 result.append(buffer);
899 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
900 result.append(buffer);
901
902 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
903 result.append(buffer);
904 result.append(" Index Command");
905 for (size_t i = 0; i < mNewParameters.size(); ++i) {
906 snprintf(buffer, SIZE, "\n %02d ", i);
907 result.append(buffer);
908 result.append(mNewParameters[i]);
909 }
910
911 snprintf(buffer, SIZE, "\n\nPending config events: \n");
912 result.append(buffer);
913 snprintf(buffer, SIZE, " Index event param\n");
914 result.append(buffer);
915 for (size_t i = 0; i < mConfigEvents.size(); i++) {
916 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
917 result.append(buffer);
918 }
919 result.append("\n");
920
921 write(fd, result.string(), result.size());
922
923 if (locked) {
924 mLock.unlock();
925 }
926 return NO_ERROR;
927}
928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929
930// ----------------------------------------------------------------------------
931
Eric Laurent49f02be2009-11-19 09:00:56 -0800932AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
933 : ThreadBase(audioFlinger, id),
Eric Laurentd5603c12009-08-06 08:49:39 -0700934 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent2c817f52009-07-23 13:17:39 -0700935 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936{
Eric Laurenta553c252009-07-17 12:17:14 -0700937 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938
Eric Laurenta553c252009-07-17 12:17:14 -0700939 mMasterVolume = mAudioFlinger->masterVolume();
940 mMasterMute = mAudioFlinger->masterMute();
941
942 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
943 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
944 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
Eric Laurenta553c252009-07-17 12:17:14 -0700946 // notify client processes that a new input has been opened
947 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948}
949
Eric Laurenta553c252009-07-17 12:17:14 -0700950AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951{
952 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953}
954
Eric Laurenta553c252009-07-17 12:17:14 -0700955status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956{
957 dumpInternals(fd, args);
958 dumpTracks(fd, args);
959 return NO_ERROR;
960}
961
Eric Laurenta553c252009-07-17 12:17:14 -0700962status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963{
964 const size_t SIZE = 256;
965 char buffer[SIZE];
966 String8 result;
967
Eric Laurenta553c252009-07-17 12:17:14 -0700968 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -0800970 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -0700972 sp<Track> track = mTracks[i];
973 if (track != 0) {
974 track->dump(buffer, SIZE);
975 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977 }
978
Eric Laurenta553c252009-07-17 12:17:14 -0700979 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -0800981 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -0700983 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 if (wTrack != 0) {
985 sp<Track> track = wTrack.promote();
986 if (track != 0) {
987 track->dump(buffer, SIZE);
988 result.append(buffer);
989 }
990 }
991 }
992 write(fd, result.string(), result.size());
993 return NO_ERROR;
994}
995
Eric Laurenta553c252009-07-17 12:17:14 -0700996status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997{
998 const size_t SIZE = 256;
999 char buffer[SIZE];
1000 String8 result;
1001
Eric Laurent3fdb1262009-11-07 00:01:32 -08001002 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 result.append(buffer);
1004 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
1005 result.append(buffer);
1006 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
1007 result.append(buffer);
1008 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
1009 result.append(buffer);
1010 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
1011 result.append(buffer);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001012 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
1013 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08001015
1016 dumpBase(fd, args);
1017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 return NO_ERROR;
1019}
1020
1021// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -07001022status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023{
1024 if (mSampleRate == 0) {
1025 LOGE("No working audio driver found.");
1026 return NO_INIT;
1027 }
Eric Laurenta553c252009-07-17 12:17:14 -07001028 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 return NO_ERROR;
1030}
1031
Eric Laurenta553c252009-07-17 12:17:14 -07001032void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033{
1034 const size_t SIZE = 256;
1035 char buffer[SIZE];
1036
Eric Laurenta553c252009-07-17 12:17:14 -07001037 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038
1039 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
1040}
1041
Eric Laurenta553c252009-07-17 12:17:14 -07001042// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1043sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 const sp<AudioFlinger::Client>& client,
1045 int streamType,
1046 uint32_t sampleRate,
1047 int format,
1048 int channelCount,
1049 int frameCount,
1050 const sp<IMemory>& sharedBuffer,
1051 status_t *status)
1052{
1053 sp<Track> track;
1054 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001055
1056 if (mType == DIRECT) {
1057 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
1058 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
1059 sampleRate, format, channelCount, mOutput);
1060 lStatus = BAD_VALUE;
1061 goto Exit;
1062 }
1063 } else {
1064 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1065 if (sampleRate > mSampleRate*2) {
1066 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1067 lStatus = BAD_VALUE;
1068 goto Exit;
1069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
1071
Eric Laurenta553c252009-07-17 12:17:14 -07001072 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001073 LOGE("Audio driver not initialized.");
1074 lStatus = NO_INIT;
1075 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077
Eric Laurenta553c252009-07-17 12:17:14 -07001078 { // scope for mLock
1079 Mutex::Autolock _l(mLock);
1080 track = new Track(this, client, streamType, sampleRate, format,
1081 channelCount, frameCount, sharedBuffer);
Eric Laurent73b60352009-11-09 04:45:39 -08001082 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07001083 lStatus = NO_MEMORY;
1084 goto Exit;
1085 }
1086 mTracks.add(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001087 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001088 lStatus = NO_ERROR;
1089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090Exit:
1091 if(status) {
1092 *status = lStatus;
1093 }
1094 return track;
1095}
1096
Eric Laurenta553c252009-07-17 12:17:14 -07001097uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098{
1099 if (mOutput) {
1100 return mOutput->latency();
1101 }
1102 else {
1103 return 0;
1104 }
1105}
1106
Eric Laurenta553c252009-07-17 12:17:14 -07001107status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001109#ifdef LVMX
1110 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1111 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1112 LifeVibes::setMasterVolume(audioOutputType, value);
1113 }
1114#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 mMasterVolume = value;
1116 return NO_ERROR;
1117}
1118
Eric Laurenta553c252009-07-17 12:17:14 -07001119status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001121#ifdef LVMX
1122 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1123 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1124 LifeVibes::setMasterMute(audioOutputType, muted);
1125 }
1126#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 mMasterMute = muted;
1128 return NO_ERROR;
1129}
1130
Eric Laurenta553c252009-07-17 12:17:14 -07001131float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132{
1133 return mMasterVolume;
1134}
1135
Eric Laurenta553c252009-07-17 12:17:14 -07001136bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137{
1138 return mMasterMute;
1139}
1140
Eric Laurenta553c252009-07-17 12:17:14 -07001141status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001143#ifdef LVMX
1144 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1145 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1146 LifeVibes::setStreamVolume(audioOutputType, stream, value);
1147 }
1148#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 mStreamTypes[stream].volume = value;
1150 return NO_ERROR;
1151}
1152
Eric Laurenta553c252009-07-17 12:17:14 -07001153status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154{
Glenn Kasten871c16c2010-03-05 12:18:01 -08001155#ifdef LVMX
1156 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1157 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1158 LifeVibes::setStreamMute(audioOutputType, stream, muted);
1159 }
1160#endif
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 mStreamTypes[stream].mute = muted;
1162 return NO_ERROR;
1163}
1164
Eric Laurenta553c252009-07-17 12:17:14 -07001165float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166{
1167 return mStreamTypes[stream].volume;
1168}
1169
Eric Laurenta553c252009-07-17 12:17:14 -07001170bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171{
1172 return mStreamTypes[stream].mute;
1173}
1174
Eric Laurent23f25cd2010-01-25 08:49:09 -08001175bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176{
Eric Laurenta553c252009-07-17 12:17:14 -07001177 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 size_t count = mActiveTracks.size();
1179 for (size_t i = 0 ; i < count ; ++i) {
1180 sp<Track> t = mActiveTracks[i].promote();
1181 if (t == 0) continue;
1182 Track* const track = t.get();
Eric Laurent23f25cd2010-01-25 08:49:09 -08001183 if (t->type() == stream)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 return true;
1185 }
1186 return false;
1187}
1188
Eric Laurenta553c252009-07-17 12:17:14 -07001189// addTrack_l() must be called with ThreadBase::mLock held
1190status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191{
1192 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001193
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001194 // set retry count for buffer fill
1195 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001196 if (mActiveTracks.indexOf(track) < 0) {
1197 // the track is newly added, make sure it fills up all its
1198 // buffers before playing. This is to ensure the client will
1199 // effectively get the latency it requested.
1200 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001201 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001202 mActiveTracks.add(track);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001204 }
Eric Laurenta553c252009-07-17 12:17:14 -07001205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001207 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208
1209 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001210}
1211
Eric Laurenta553c252009-07-17 12:17:14 -07001212// destroyTrack_l() must be called with ThreadBase::mLock held
1213void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001214{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001215 track->mState = TrackBase::TERMINATED;
1216 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001217 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001218 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001219 }
1220}
1221
Eric Laurenta553c252009-07-17 12:17:14 -07001222String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001223{
Eric Laurenta553c252009-07-17 12:17:14 -07001224 return mOutput->getParameters(keys);
1225}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001226
Eric Laurenta553c252009-07-17 12:17:14 -07001227void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1228 AudioSystem::OutputDescriptor desc;
1229 void *param2 = 0;
1230
1231 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1232
1233 switch (event) {
1234 case AudioSystem::OUTPUT_OPENED:
1235 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1236 desc.channels = mChannelCount;
1237 desc.samplingRate = mSampleRate;
1238 desc.format = mFormat;
1239 desc.frameCount = mFrameCount;
1240 desc.latency = latency();
1241 param2 = &desc;
1242 break;
1243
1244 case AudioSystem::STREAM_CONFIG_CHANGED:
1245 param2 = &param;
1246 case AudioSystem::OUTPUT_CLOSED:
1247 default:
1248 break;
1249 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07001250 Mutex::Autolock _l(mAudioFlinger->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08001251 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07001252}
1253
1254void AudioFlinger::PlaybackThread::readOutputParameters()
1255{
1256 mSampleRate = mOutput->sampleRate();
1257 mChannelCount = AudioSystem::popCount(mOutput->channels());
1258
1259 mFormat = mOutput->format();
1260 mFrameSize = mOutput->frameSize();
1261 mFrameCount = mOutput->bufferSize() / mFrameSize;
1262
Eric Laurenta553c252009-07-17 12:17:14 -07001263 // FIXME - Current mixer implementation only supports stereo output: Always
1264 // Allocate a stereo buffer even if HW output is mono.
1265 if (mMixBuffer != NULL) delete mMixBuffer;
1266 mMixBuffer = new int16_t[mFrameCount * 2];
1267 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1268}
1269
Eric Laurent0986e792010-01-19 17:37:09 -08001270status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1271{
1272 if (halFrames == 0 || dspFrames == 0) {
1273 return BAD_VALUE;
1274 }
1275 if (mOutput == 0) {
1276 return INVALID_OPERATION;
1277 }
1278 *halFrames = mBytesWritten/mOutput->frameSize();
1279
1280 return mOutput->getRenderPosition(dspFrames);
1281}
1282
Eric Laurenta553c252009-07-17 12:17:14 -07001283// ----------------------------------------------------------------------------
1284
Eric Laurent49f02be2009-11-19 09:00:56 -08001285AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
1286 : PlaybackThread(audioFlinger, output, id),
Eric Laurenta553c252009-07-17 12:17:14 -07001287 mAudioMixer(0)
1288{
1289 mType = PlaybackThread::MIXER;
1290 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1291
1292 // FIXME - Current mixer implementation only supports stereo output
1293 if (mChannelCount == 1) {
1294 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001296}
1297
Eric Laurenta553c252009-07-17 12:17:14 -07001298AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001299{
Eric Laurenta553c252009-07-17 12:17:14 -07001300 delete mAudioMixer;
1301}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302
Eric Laurenta553c252009-07-17 12:17:14 -07001303bool AudioFlinger::MixerThread::threadLoop()
1304{
Eric Laurenta553c252009-07-17 12:17:14 -07001305 int16_t* curBuf = mMixBuffer;
1306 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08001307 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001308 nsecs_t standbyTime = systemTime();
1309 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001310 // FIXME: Relaxed timing because of a certain device that can't meet latency
1311 // Should be reduced to 2x after the vendor fixes the driver issue
1312 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1313 nsecs_t lastWarning = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001314 bool longStandbyExit = false;
1315 uint32_t activeSleepTime = activeSleepTimeUs();
1316 uint32_t idleSleepTime = idleSleepTimeUs();
1317 uint32_t sleepTime = idleSleepTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318
Eric Laurenta553c252009-07-17 12:17:14 -07001319 while (!exitPending())
1320 {
1321 processConfigEvents();
1322
Eric Laurent059b4be2009-11-09 23:32:22 -08001323 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001324 { // scope for mLock
1325
1326 Mutex::Autolock _l(mLock);
1327
1328 if (checkForNewParameters_l()) {
1329 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001330 // FIXME: Relaxed timing because of a certain device that can't meet latency
1331 // Should be reduced to 2x after the vendor fixes the driver issue
1332 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent059b4be2009-11-09 23:32:22 -08001333 activeSleepTime = activeSleepTimeUs();
1334 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07001335 }
1336
1337 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1338
1339 // put audio hardware into standby after short delay
1340 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1341 mSuspended) {
1342 if (!mStandby) {
1343 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1344 mOutput->standby();
1345 mStandby = true;
1346 mBytesWritten = 0;
1347 }
1348
1349 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1350 // we're about to wait, flush the binder command buffer
1351 IPCThreadState::self()->flushCommands();
1352
1353 if (exitPending()) break;
1354
1355 // wait until we have something to do...
1356 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1357 mWaitWorkCV.wait(mLock);
1358 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1359
1360 if (mMasterMute == false) {
1361 char value[PROPERTY_VALUE_MAX];
1362 property_get("ro.audio.silent", value, "0");
1363 if (atoi(value)) {
1364 LOGD("Silence is golden");
1365 setMasterMute(true);
1366 }
1367 }
1368
1369 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08001370 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001371 continue;
1372 }
1373 }
1374
Eric Laurent059b4be2009-11-09 23:32:22 -08001375 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurenta553c252009-07-17 12:17:14 -07001376 }
1377
Eric Laurent059b4be2009-11-09 23:32:22 -08001378 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001379 // mix buffers...
1380 mAudioMixer->process(curBuf);
1381 sleepTime = 0;
1382 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent96c08a62009-09-07 08:38:38 -07001383 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001384 // If no tracks are ready, sleep once for the duration of an output
1385 // buffer size, then write 0s to the output
1386 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001387 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1388 sleepTime = activeSleepTime;
1389 } else {
1390 sleepTime = idleSleepTime;
1391 }
1392 } else if (mBytesWritten != 0 ||
1393 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001394 memset (curBuf, 0, mixBufferSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001395 sleepTime = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08001396 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent96c08a62009-09-07 08:38:38 -07001397 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001398 }
1399
1400 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001401 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001402 }
1403 // sleepTime == 0 means we must write to audio hardware
1404 if (sleepTime == 0) {
1405 mLastWriteTime = systemTime();
1406 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08001407 mBytesWritten += mixBufferSize;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001408#ifdef LVMX
1409 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1410 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType)) {
1411 LifeVibes::process(audioOutputType, curBuf, mixBufferSize);
1412 }
1413#endif
Eric Laurentf69a3f82009-09-22 00:35:48 -07001414 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001415 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001416 mNumWrites++;
1417 mInWrite = false;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001418 nsecs_t now = systemTime();
1419 nsecs_t delta = now - mLastWriteTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001420 if (delta > maxPeriod) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001421 mNumDelayedWrites++;
Dave Sparksd0ac8c02009-09-30 03:09:03 -07001422 if ((now - lastWarning) > kWarningThrottle) {
1423 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1424 ns2ms(delta), mNumDelayedWrites, this);
1425 lastWarning = now;
1426 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001427 if (mStandby) {
1428 longStandbyExit = true;
1429 }
Eric Laurenta553c252009-07-17 12:17:14 -07001430 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001431 mStandby = false;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001432 } else {
1433 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001434 }
1435
1436 // finally let go of all our tracks, without the lock held
1437 // since we can't guarantee the destructors won't acquire that
1438 // same lock.
1439 tracksToRemove.clear();
1440 }
1441
1442 if (!mStandby) {
1443 mOutput->standby();
1444 }
Eric Laurenta553c252009-07-17 12:17:14 -07001445
1446 LOGV("MixerThread %p exiting", this);
1447 return false;
1448}
1449
1450// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent059b4be2009-11-09 23:32:22 -08001451uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurenta553c252009-07-17 12:17:14 -07001452{
1453
Eric Laurent059b4be2009-11-09 23:32:22 -08001454 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001455 // find out which tracks need to be processed
1456 size_t count = activeTracks.size();
Glenn Kasten871c16c2010-03-05 12:18:01 -08001457
1458 float masterVolume = mMasterVolume;
1459 bool masterMute = mMasterMute;
1460
1461#ifdef LVMX
1462 bool tracksConnectedChanged = false;
1463 bool stateChanged = false;
1464
1465 int audioOutputType = LifeVibes::getMixerType(mId, mType);
1466 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1467 {
1468 int activeTypes = 0;
1469 for (size_t i=0 ; i<count ; i++) {
1470 sp<Track> t = activeTracks[i].promote();
1471 if (t == 0) continue;
1472 Track* const track = t.get();
1473 int iTracktype=track->type();
1474 activeTypes |= 1<<track->type();
1475 }
1476 LifeVibes::computeVolumes(audioOutputType, activeTypes, tracksConnectedChanged, stateChanged, masterVolume, masterMute);
1477 }
1478#endif
1479
Eric Laurenta553c252009-07-17 12:17:14 -07001480 for (size_t i=0 ; i<count ; i++) {
1481 sp<Track> t = activeTracks[i].promote();
1482 if (t == 0) continue;
1483
1484 Track* const track = t.get();
1485 audio_track_cblk_t* cblk = track->cblk();
1486
1487 // The first time a track is added we wait
1488 // for all its buffers to be filled before processing it
1489 mAudioMixer->setActiveTrack(track->name());
1490 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1491 !track->isPaused())
1492 {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001493 //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 -07001494
1495 // compute volume for this track
1496 int16_t left, right;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001497 if (track->isMuted() || masterMute || track->isPausing() ||
Eric Laurenta553c252009-07-17 12:17:14 -07001498 mStreamTypes[track->type()].mute) {
1499 left = right = 0;
1500 if (track->isPausing()) {
1501 track->setPaused();
1502 }
1503 } else {
Glenn Kasten871c16c2010-03-05 12:18:01 -08001504 // read original volumes with volume control
Eric Laurenta553c252009-07-17 12:17:14 -07001505 float typeVolume = mStreamTypes[track->type()].volume;
Glenn Kasten871c16c2010-03-05 12:18:01 -08001506#ifdef LVMX
1507 bool streamMute=false;
1508 // read the volume from the LivesVibes audio engine.
1509 if (LifeVibes::audioOutputTypeIsLifeVibes(audioOutputType))
1510 {
1511 LifeVibes::getStreamVolumes(audioOutputType, track->type(), &typeVolume, &streamMute);
1512 if (streamMute) {
1513 typeVolume = 0;
1514 }
1515 }
1516#endif
1517 float v = masterVolume * typeVolume;
Eric Laurenta553c252009-07-17 12:17:14 -07001518 float v_clamped = v * cblk->volume[0];
1519 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1520 left = int16_t(v_clamped);
1521 v_clamped = v * cblk->volume[1];
1522 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1523 right = int16_t(v_clamped);
1524 }
1525
1526 // XXX: these things DON'T need to be done each time
1527 mAudioMixer->setBufferProvider(track);
1528 mAudioMixer->enable(AudioMixer::MIXING);
1529
Eric Laurenta160c6e2009-09-03 03:45:52 -07001530 int param = AudioMixer::VOLUME;
1531 if (track->mFillingUpStatus == Track::FS_FILLED) {
Eric Laurenta553c252009-07-17 12:17:14 -07001532 // no ramp for the first volume setting
1533 track->mFillingUpStatus = Track::FS_ACTIVE;
1534 if (track->mState == TrackBase::RESUMING) {
1535 track->mState = TrackBase::ACTIVE;
1536 param = AudioMixer::RAMP_VOLUME;
Eric Laurenta553c252009-07-17 12:17:14 -07001537 }
Eric Laurenta160c6e2009-09-03 03:45:52 -07001538 } else if (cblk->server != 0) {
1539 // If the track is stopped before the first frame was mixed,
1540 // do not apply ramp
Eric Laurenta553c252009-07-17 12:17:14 -07001541 param = AudioMixer::RAMP_VOLUME;
1542 }
Glenn Kasten871c16c2010-03-05 12:18:01 -08001543#ifdef LVMX
1544 if ( tracksConnectedChanged || stateChanged )
1545 {
1546 // only do the ramp when the volume is changed by the user / application
1547 param = AudioMixer::VOLUME;
1548 }
1549#endif
Eric Laurenta553c252009-07-17 12:17:14 -07001550 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1551 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1552 mAudioMixer->setParameter(
1553 AudioMixer::TRACK,
1554 AudioMixer::FORMAT, track->format());
1555 mAudioMixer->setParameter(
1556 AudioMixer::TRACK,
1557 AudioMixer::CHANNEL_COUNT, track->channelCount());
1558 mAudioMixer->setParameter(
1559 AudioMixer::RESAMPLE,
1560 AudioMixer::SAMPLE_RATE,
1561 int(cblk->sampleRate));
1562
1563 // reset retry count
1564 track->mRetryCount = kMaxTrackRetries;
Eric Laurent059b4be2009-11-09 23:32:22 -08001565 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001566 } else {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08001567 //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 -07001568 if (track->isStopped()) {
1569 track->reset();
1570 }
1571 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1572 // We have consumed all the buffers of this track.
1573 // Remove it from the list of active tracks.
1574 tracksToRemove->add(track);
1575 mAudioMixer->disable(AudioMixer::MIXING);
1576 } else {
1577 // No buffers for this track. Give it a few chances to
1578 // fill a buffer, then remove it from active list.
1579 if (--(track->mRetryCount) <= 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07001580 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurenta553c252009-07-17 12:17:14 -07001581 tracksToRemove->add(track);
Eric Laurent059b4be2009-11-09 23:32:22 -08001582 } else if (mixerStatus != MIXER_TRACKS_READY) {
1583 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001584 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001585
1586 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurenta553c252009-07-17 12:17:14 -07001587 }
1588 }
1589 }
1590
1591 // remove all the tracks that need to be...
1592 count = tracksToRemove->size();
1593 if (UNLIKELY(count)) {
1594 for (size_t i=0 ; i<count ; i++) {
1595 const sp<Track>& track = tracksToRemove->itemAt(i);
1596 mActiveTracks.remove(track);
1597 if (track->isTerminated()) {
1598 mTracks.remove(track);
1599 deleteTrackName_l(track->mName);
1600 }
1601 }
1602 }
1603
Eric Laurent059b4be2009-11-09 23:32:22 -08001604 return mixerStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07001605}
1606
1607void AudioFlinger::MixerThread::getTracks(
1608 SortedVector < sp<Track> >& tracks,
1609 SortedVector < wp<Track> >& activeTracks,
1610 int streamType)
1611{
1612 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1613 Mutex::Autolock _l(mLock);
1614 size_t size = mTracks.size();
1615 for (size_t i = 0; i < size; i++) {
1616 sp<Track> t = mTracks[i];
1617 if (t->type() == streamType) {
1618 tracks.add(t);
1619 int j = mActiveTracks.indexOf(t);
1620 if (j >= 0) {
1621 t = mActiveTracks[j].promote();
1622 if (t != NULL) {
1623 activeTracks.add(t);
1624 }
1625 }
1626 }
1627 }
1628
1629 size = activeTracks.size();
1630 for (size_t i = 0; i < size; i++) {
1631 mActiveTracks.remove(activeTracks[i]);
1632 }
1633
1634 size = tracks.size();
1635 for (size_t i = 0; i < size; i++) {
1636 sp<Track> t = tracks[i];
1637 mTracks.remove(t);
1638 deleteTrackName_l(t->name());
1639 }
1640}
1641
1642void AudioFlinger::MixerThread::putTracks(
1643 SortedVector < sp<Track> >& tracks,
1644 SortedVector < wp<Track> >& activeTracks)
1645{
1646 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1647 Mutex::Autolock _l(mLock);
1648 size_t size = tracks.size();
1649 for (size_t i = 0; i < size ; i++) {
1650 sp<Track> t = tracks[i];
1651 int name = getTrackName_l();
1652
1653 if (name < 0) return;
1654
1655 t->mName = name;
1656 t->mThread = this;
1657 mTracks.add(t);
1658
1659 int j = activeTracks.indexOf(t);
1660 if (j >= 0) {
1661 mActiveTracks.add(t);
Eric Laurentd069f322009-09-01 05:56:26 -07001662 // force buffer refilling and no ramp volume when the track is mixed for the first time
1663 t->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 }
1665 }
1666}
1667
Eric Laurenta553c252009-07-17 12:17:14 -07001668// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001669int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670{
1671 return mAudioMixer->getTrackName();
1672}
1673
Eric Laurenta553c252009-07-17 12:17:14 -07001674// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001675void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676{
Eric Laurent0a080292009-12-07 10:53:10 -08001677 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 mAudioMixer->deleteTrackName(name);
1679}
1680
Eric Laurenta553c252009-07-17 12:17:14 -07001681// checkForNewParameters_l() must be called with ThreadBase::mLock held
1682bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683{
Eric Laurenta553c252009-07-17 12:17:14 -07001684 bool reconfig = false;
1685
Eric Laurent8fce46a2009-08-04 09:45:33 -07001686 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001687 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001688 String8 keyValuePair = mNewParameters[0];
1689 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001690 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001691
Eric Laurenta553c252009-07-17 12:17:14 -07001692 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1693 reconfig = true;
1694 }
1695 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1696 if (value != AudioSystem::PCM_16_BIT) {
1697 status = BAD_VALUE;
1698 } else {
1699 reconfig = true;
1700 }
1701 }
1702 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1703 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1704 status = BAD_VALUE;
1705 } else {
1706 reconfig = true;
1707 }
1708 }
1709 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1710 // do not accept frame count changes if tracks are open as the track buffer
1711 // size depends on frame count and correct behavior would not be garantied
1712 // if frame count is changed after track creation
1713 if (!mTracks.isEmpty()) {
1714 status = INVALID_OPERATION;
1715 } else {
1716 reconfig = true;
1717 }
1718 }
1719 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001720 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001721 if (!mStandby && status == INVALID_OPERATION) {
1722 mOutput->standby();
1723 mStandby = true;
1724 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001725 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001726 }
1727 if (status == NO_ERROR && reconfig) {
1728 delete mAudioMixer;
1729 readOutputParameters();
1730 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1731 for (size_t i = 0; i < mTracks.size() ; i++) {
1732 int name = getTrackName_l();
1733 if (name < 0) break;
1734 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001735 // limit track sample rate to 2 x new output sample rate
1736 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1737 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1738 }
Eric Laurenta553c252009-07-17 12:17:14 -07001739 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001740 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001741 }
1742 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08001743
1744 mNewParameters.removeAt(0);
1745
Eric Laurenta553c252009-07-17 12:17:14 -07001746 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001747 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001748 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001749 }
1750 return reconfig;
1751}
1752
1753status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1754{
1755 const size_t SIZE = 256;
1756 char buffer[SIZE];
1757 String8 result;
1758
1759 PlaybackThread::dumpInternals(fd, args);
1760
1761 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1762 result.append(buffer);
1763 write(fd, result.string(), result.size());
1764 return NO_ERROR;
1765}
1766
Eric Laurent059b4be2009-11-09 23:32:22 -08001767uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07001768{
Eric Laurent059b4be2009-11-09 23:32:22 -08001769 return (uint32_t)(mOutput->latency() * 1000) / 2;
1770}
1771
1772uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1773{
1774 return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07001775}
1776
Eric Laurenta553c252009-07-17 12:17:14 -07001777// ----------------------------------------------------------------------------
Eric Laurent49f02be2009-11-19 09:00:56 -08001778AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
1779 : PlaybackThread(audioFlinger, output, id),
Eric Laurenta553c252009-07-17 12:17:14 -07001780 mLeftVolume (1.0), mRightVolume(1.0)
1781{
1782 mType = PlaybackThread::DIRECT;
1783}
1784
1785AudioFlinger::DirectOutputThread::~DirectOutputThread()
1786{
1787}
1788
1789
1790bool AudioFlinger::DirectOutputThread::threadLoop()
1791{
Eric Laurent059b4be2009-11-09 23:32:22 -08001792 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07001793 sp<Track> trackToRemove;
1794 sp<Track> activeTrack;
1795 nsecs_t standbyTime = systemTime();
1796 int8_t *curBuf;
1797 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08001798 uint32_t activeSleepTime = activeSleepTimeUs();
1799 uint32_t idleSleepTime = idleSleepTimeUs();
1800 uint32_t sleepTime = idleSleepTime;
Eric Laurentef9500f2010-03-11 14:47:00 -08001801 // use shorter standby delay as on normal output to release
1802 // hardware resources as soon as possible
1803 nsecs_t standbyDelay = microseconds(activeSleepTime*2);
Eric Laurent059b4be2009-11-09 23:32:22 -08001804
Eric Laurenta553c252009-07-17 12:17:14 -07001805
1806 while (!exitPending())
1807 {
1808 processConfigEvents();
1809
Eric Laurent059b4be2009-11-09 23:32:22 -08001810 mixerStatus = MIXER_IDLE;
1811
Eric Laurenta553c252009-07-17 12:17:14 -07001812 { // scope for the mLock
1813
1814 Mutex::Autolock _l(mLock);
1815
1816 if (checkForNewParameters_l()) {
1817 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent059b4be2009-11-09 23:32:22 -08001818 activeSleepTime = activeSleepTimeUs();
1819 idleSleepTime = idleSleepTimeUs();
Eric Laurentef9500f2010-03-11 14:47:00 -08001820 standbyDelay = microseconds(activeSleepTime*2);
Eric Laurenta553c252009-07-17 12:17:14 -07001821 }
1822
1823 // put audio hardware into standby after short delay
1824 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1825 mSuspended) {
1826 // wait until we have something to do...
1827 if (!mStandby) {
1828 LOGV("Audio hardware entering standby, mixer %p\n", this);
1829 mOutput->standby();
1830 mStandby = true;
1831 mBytesWritten = 0;
1832 }
1833
1834 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1835 // we're about to wait, flush the binder command buffer
1836 IPCThreadState::self()->flushCommands();
1837
1838 if (exitPending()) break;
1839
1840 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1841 mWaitWorkCV.wait(mLock);
1842 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1843
1844 if (mMasterMute == false) {
1845 char value[PROPERTY_VALUE_MAX];
1846 property_get("ro.audio.silent", value, "0");
1847 if (atoi(value)) {
1848 LOGD("Silence is golden");
1849 setMasterMute(true);
1850 }
1851 }
1852
Eric Laurentef9500f2010-03-11 14:47:00 -08001853 standbyTime = systemTime() + standbyDelay;
Eric Laurent059b4be2009-11-09 23:32:22 -08001854 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07001855 continue;
1856 }
1857 }
1858
1859 // find out which tracks need to be processed
1860 if (mActiveTracks.size() != 0) {
1861 sp<Track> t = mActiveTracks[0].promote();
1862 if (t == 0) continue;
1863
1864 Track* const track = t.get();
1865 audio_track_cblk_t* cblk = track->cblk();
1866
1867 // The first time a track is added we wait
1868 // for all its buffers to be filled before processing it
1869 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1870 !track->isPaused())
1871 {
1872 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1873
1874 // compute volume for this track
1875 float left, right;
1876 if (track->isMuted() || mMasterMute || track->isPausing() ||
1877 mStreamTypes[track->type()].mute) {
1878 left = right = 0;
1879 if (track->isPausing()) {
1880 track->setPaused();
1881 }
1882 } else {
1883 float typeVolume = mStreamTypes[track->type()].volume;
1884 float v = mMasterVolume * typeVolume;
1885 float v_clamped = v * cblk->volume[0];
1886 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1887 left = v_clamped/MAX_GAIN;
1888 v_clamped = v * cblk->volume[1];
1889 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1890 right = v_clamped/MAX_GAIN;
1891 }
1892
1893 if (left != mLeftVolume || right != mRightVolume) {
1894 mOutput->setVolume(left, right);
1895 left = mLeftVolume;
1896 right = mRightVolume;
1897 }
1898
1899 if (track->mFillingUpStatus == Track::FS_FILLED) {
1900 track->mFillingUpStatus = Track::FS_ACTIVE;
1901 if (track->mState == TrackBase::RESUMING) {
1902 track->mState = TrackBase::ACTIVE;
1903 }
1904 }
1905
1906 // reset retry count
Eric Laurentef9500f2010-03-11 14:47:00 -08001907 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurenta553c252009-07-17 12:17:14 -07001908 activeTrack = t;
Eric Laurent059b4be2009-11-09 23:32:22 -08001909 mixerStatus = MIXER_TRACKS_READY;
Eric Laurenta553c252009-07-17 12:17:14 -07001910 } else {
1911 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1912 if (track->isStopped()) {
1913 track->reset();
1914 }
1915 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1916 // We have consumed all the buffers of this track.
1917 // Remove it from the list of active tracks.
1918 trackToRemove = track;
1919 } else {
1920 // No buffers for this track. Give it a few chances to
1921 // fill a buffer, then remove it from active list.
1922 if (--(track->mRetryCount) <= 0) {
1923 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1924 trackToRemove = track;
Eric Laurent059b4be2009-11-09 23:32:22 -08001925 } else {
1926 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurenta553c252009-07-17 12:17:14 -07001927 }
Eric Laurent059b4be2009-11-09 23:32:22 -08001928 }
Eric Laurenta553c252009-07-17 12:17:14 -07001929 }
1930 }
1931
1932 // remove all the tracks that need to be...
1933 if (UNLIKELY(trackToRemove != 0)) {
1934 mActiveTracks.remove(trackToRemove);
1935 if (trackToRemove->isTerminated()) {
1936 mTracks.remove(trackToRemove);
1937 deleteTrackName_l(trackToRemove->mName);
1938 }
1939 }
1940 }
1941
Eric Laurent059b4be2009-11-09 23:32:22 -08001942 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001943 AudioBufferProvider::Buffer buffer;
1944 size_t frameCount = mFrameCount;
1945 curBuf = (int8_t *)mMixBuffer;
1946 // output audio to hardware
1947 while(frameCount) {
1948 buffer.frameCount = frameCount;
1949 activeTrack->getNextBuffer(&buffer);
1950 if (UNLIKELY(buffer.raw == 0)) {
1951 memset(curBuf, 0, frameCount * mFrameSize);
1952 break;
1953 }
1954 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1955 frameCount -= buffer.frameCount;
1956 curBuf += buffer.frameCount * mFrameSize;
1957 activeTrack->releaseBuffer(&buffer);
1958 }
1959 sleepTime = 0;
Eric Laurentef9500f2010-03-11 14:47:00 -08001960 standbyTime = systemTime() + standbyDelay;
Eric Laurent96c08a62009-09-07 08:38:38 -07001961 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07001962 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001963 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1964 sleepTime = activeSleepTime;
1965 } else {
1966 sleepTime = idleSleepTime;
1967 }
Eric Laurent62443f52009-10-05 20:29:18 -07001968 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentf69a3f82009-09-22 00:35:48 -07001969 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent96c08a62009-09-07 08:38:38 -07001970 sleepTime = 0;
Eric Laurent96c08a62009-09-07 08:38:38 -07001971 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07001972 }
Eric Laurent96c08a62009-09-07 08:38:38 -07001973
Eric Laurentf69a3f82009-09-22 00:35:48 -07001974 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08001975 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001976 }
1977 // sleepTime == 0 means we must write to audio hardware
1978 if (sleepTime == 0) {
1979 mLastWriteTime = systemTime();
1980 mInWrite = true;
Eric Laurent0986e792010-01-19 17:37:09 -08001981 mBytesWritten += mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001982 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurent0986e792010-01-19 17:37:09 -08001983 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentf69a3f82009-09-22 00:35:48 -07001984 mNumWrites++;
1985 mInWrite = false;
1986 mStandby = false;
1987 } else {
1988 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07001989 }
1990
1991 // finally let go of removed track, without the lock held
1992 // since we can't guarantee the destructors won't acquire that
1993 // same lock.
1994 trackToRemove.clear();
1995 activeTrack.clear();
1996 }
1997
1998 if (!mStandby) {
1999 mOutput->standby();
2000 }
Eric Laurenta553c252009-07-17 12:17:14 -07002001
2002 LOGV("DirectOutputThread %p exiting", this);
2003 return false;
2004}
2005
2006// getTrackName_l() must be called with ThreadBase::mLock held
2007int AudioFlinger::DirectOutputThread::getTrackName_l()
2008{
2009 return 0;
2010}
2011
2012// deleteTrackName_l() must be called with ThreadBase::mLock held
2013void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
2014{
2015}
2016
2017// checkForNewParameters_l() must be called with ThreadBase::mLock held
2018bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
2019{
2020 bool reconfig = false;
2021
Eric Laurent8fce46a2009-08-04 09:45:33 -07002022 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07002023 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002024 String8 keyValuePair = mNewParameters[0];
2025 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002026 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002027
Eric Laurenta553c252009-07-17 12:17:14 -07002028 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
2029 // do not accept frame count changes if tracks are open as the track buffer
2030 // size depends on frame count and correct behavior would not be garantied
2031 // if frame count is changed after track creation
2032 if (!mTracks.isEmpty()) {
2033 status = INVALID_OPERATION;
2034 } else {
2035 reconfig = true;
2036 }
2037 }
2038 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07002039 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002040 if (!mStandby && status == INVALID_OPERATION) {
2041 mOutput->standby();
2042 mStandby = true;
2043 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07002044 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07002045 }
2046 if (status == NO_ERROR && reconfig) {
2047 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002048 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07002049 }
2050 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08002051
2052 mNewParameters.removeAt(0);
2053
Eric Laurenta553c252009-07-17 12:17:14 -07002054 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07002055 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07002056 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002057 }
2058 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08002059}
2060
Eric Laurent059b4be2009-11-09 23:32:22 -08002061uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurent62443f52009-10-05 20:29:18 -07002062{
2063 uint32_t time;
2064 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002065 time = (uint32_t)(mOutput->latency() * 1000) / 2;
2066 } else {
2067 time = 10000;
2068 }
2069 return time;
2070}
2071
2072uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
2073{
2074 uint32_t time;
2075 if (AudioSystem::isLinearPCM(mFormat)) {
2076 time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurent62443f52009-10-05 20:29:18 -07002077 } else {
2078 time = 10000;
2079 }
2080 return time;
2081}
2082
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002083// ----------------------------------------------------------------------------
2084
Eric Laurent49f02be2009-11-19 09:00:56 -08002085AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002086 : MixerThread(audioFlinger, mainThread->getOutput(), id), mWaitTimeMs(UINT_MAX)
Eric Laurenta553c252009-07-17 12:17:14 -07002087{
2088 mType = PlaybackThread::DUPLICATING;
2089 addOutputTrack(mainThread);
2090}
2091
2092AudioFlinger::DuplicatingThread::~DuplicatingThread()
2093{
Eric Laurent0a080292009-12-07 10:53:10 -08002094 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2095 mOutputTracks[i]->destroy();
2096 }
Eric Laurenta553c252009-07-17 12:17:14 -07002097 mOutputTracks.clear();
2098}
2099
2100bool AudioFlinger::DuplicatingThread::threadLoop()
2101{
Eric Laurenta553c252009-07-17 12:17:14 -07002102 int16_t* curBuf = mMixBuffer;
2103 Vector< sp<Track> > tracksToRemove;
Eric Laurent059b4be2009-11-09 23:32:22 -08002104 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002105 nsecs_t standbyTime = systemTime();
2106 size_t mixBufferSize = mFrameCount*mFrameSize;
2107 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurent62443f52009-10-05 20:29:18 -07002108 uint32_t writeFrames = 0;
Eric Laurent059b4be2009-11-09 23:32:22 -08002109 uint32_t activeSleepTime = activeSleepTimeUs();
2110 uint32_t idleSleepTime = idleSleepTimeUs();
2111 uint32_t sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002112
2113 while (!exitPending())
2114 {
2115 processConfigEvents();
2116
Eric Laurent059b4be2009-11-09 23:32:22 -08002117 mixerStatus = MIXER_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -07002118 { // scope for the mLock
2119
2120 Mutex::Autolock _l(mLock);
2121
2122 if (checkForNewParameters_l()) {
2123 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002124 updateWaitTime();
Eric Laurent059b4be2009-11-09 23:32:22 -08002125 activeSleepTime = activeSleepTimeUs();
2126 idleSleepTime = idleSleepTimeUs();
Eric Laurenta553c252009-07-17 12:17:14 -07002127 }
2128
2129 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
2130
2131 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2132 outputTracks.add(mOutputTracks[i]);
2133 }
2134
2135 // put audio hardware into standby after short delay
2136 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
2137 mSuspended) {
2138 if (!mStandby) {
2139 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurenta553c252009-07-17 12:17:14 -07002140 outputTracks[i]->stop();
Eric Laurenta553c252009-07-17 12:17:14 -07002141 }
2142 mStandby = true;
2143 mBytesWritten = 0;
2144 }
2145
2146 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2147 // we're about to wait, flush the binder command buffer
2148 IPCThreadState::self()->flushCommands();
2149 outputTracks.clear();
2150
2151 if (exitPending()) break;
2152
2153 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2154 mWaitWorkCV.wait(mLock);
2155 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2156 if (mMasterMute == false) {
2157 char value[PROPERTY_VALUE_MAX];
2158 property_get("ro.audio.silent", value, "0");
2159 if (atoi(value)) {
2160 LOGD("Silence is golden");
2161 setMasterMute(true);
2162 }
2163 }
2164
2165 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent059b4be2009-11-09 23:32:22 -08002166 sleepTime = idleSleepTime;
Eric Laurenta553c252009-07-17 12:17:14 -07002167 continue;
2168 }
2169 }
2170
Eric Laurent059b4be2009-11-09 23:32:22 -08002171 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurentf69a3f82009-09-22 00:35:48 -07002172 }
Eric Laurenta553c252009-07-17 12:17:14 -07002173
Eric Laurent059b4be2009-11-09 23:32:22 -08002174 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurenta553c252009-07-17 12:17:14 -07002175 // mix buffers...
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002176 if (outputsReady(outputTracks)) {
2177 mAudioMixer->process(curBuf);
2178 } else {
2179 memset(curBuf, 0, mixBufferSize);
2180 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002181 sleepTime = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002182 writeFrames = mFrameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002183 } else {
Eric Laurent62443f52009-10-05 20:29:18 -07002184 if (sleepTime == 0) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002185 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2186 sleepTime = activeSleepTime;
2187 } else {
2188 sleepTime = idleSleepTime;
2189 }
Eric Laurent62443f52009-10-05 20:29:18 -07002190 } else if (mBytesWritten != 0) {
2191 // flush remaining overflow buffers in output tracks
2192 for (size_t i = 0; i < outputTracks.size(); i++) {
2193 if (outputTracks[i]->isActive()) {
2194 sleepTime = 0;
2195 writeFrames = 0;
2196 break;
2197 }
2198 }
Eric Laurenta553c252009-07-17 12:17:14 -07002199 }
2200 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002201
2202 if (mSuspended) {
Eric Laurent059b4be2009-11-09 23:32:22 -08002203 sleepTime = idleSleepTime;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002204 }
2205 // sleepTime == 0 means we must write to audio hardware
2206 if (sleepTime == 0) {
Eric Laurent62443f52009-10-05 20:29:18 -07002207 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentf69a3f82009-09-22 00:35:48 -07002208 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent62443f52009-10-05 20:29:18 -07002209 outputTracks[i]->write(curBuf, writeFrames);
Eric Laurenta553c252009-07-17 12:17:14 -07002210 }
Eric Laurentf69a3f82009-09-22 00:35:48 -07002211 mStandby = false;
2212 mBytesWritten += mixBufferSize;
Eric Laurenta553c252009-07-17 12:17:14 -07002213 } else {
Eric Laurentf69a3f82009-09-22 00:35:48 -07002214 usleep(sleepTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002215 }
2216
2217 // finally let go of all our tracks, without the lock held
2218 // since we can't guarantee the destructors won't acquire that
2219 // same lock.
2220 tracksToRemove.clear();
2221 outputTracks.clear();
2222 }
2223
Eric Laurenta553c252009-07-17 12:17:14 -07002224 return false;
2225}
2226
2227void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2228{
2229 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2230 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002231 this,
Eric Laurenta553c252009-07-17 12:17:14 -07002232 mSampleRate,
2233 mFormat,
2234 mChannelCount,
2235 frameCount);
Eric Laurent6c30a712009-08-10 23:22:32 -07002236 if (outputTrack->cblk() != NULL) {
2237 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2238 mOutputTracks.add(outputTrack);
2239 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002240 updateWaitTime();
Eric Laurent6c30a712009-08-10 23:22:32 -07002241 }
Eric Laurenta553c252009-07-17 12:17:14 -07002242}
2243
2244void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2245{
2246 Mutex::Autolock _l(mLock);
2247 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2248 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurent6c30a712009-08-10 23:22:32 -07002249 mOutputTracks[i]->destroy();
Eric Laurenta553c252009-07-17 12:17:14 -07002250 mOutputTracks.removeAt(i);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002251 updateWaitTime();
Eric Laurenta553c252009-07-17 12:17:14 -07002252 return;
2253 }
2254 }
2255 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2256}
2257
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002258void AudioFlinger::DuplicatingThread::updateWaitTime()
2259{
2260 mWaitTimeMs = UINT_MAX;
2261 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2262 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2263 if (strong != NULL) {
2264 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2265 if (waitTimeMs < mWaitTimeMs) {
2266 mWaitTimeMs = waitTimeMs;
2267 }
2268 }
2269 }
2270}
2271
2272
2273bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2274{
2275 for (size_t i = 0; i < outputTracks.size(); i++) {
2276 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2277 if (thread == 0) {
2278 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2279 return false;
2280 }
2281 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2282 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2283 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2284 return false;
2285 }
2286 }
2287 return true;
2288}
2289
2290uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2291{
2292 return (mWaitTimeMs * 1000) / 2;
2293}
2294
Eric Laurenta553c252009-07-17 12:17:14 -07002295// ----------------------------------------------------------------------------
2296
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002297// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002298AudioFlinger::ThreadBase::TrackBase::TrackBase(
2299 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002300 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002301 uint32_t sampleRate,
2302 int format,
2303 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002304 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 uint32_t flags,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002306 const sp<IMemory>& sharedBuffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002307 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07002308 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002309 mClient(client),
Eric Laurent8a77a992009-09-09 05:16:08 -07002310 mCblk(0),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002311 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002312 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002313 mClientTid(-1),
2314 mFormat(format),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002315 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002316{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002317 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2318
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002319 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002320 size_t size = sizeof(audio_track_cblk_t);
2321 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2322 if (sharedBuffer == 0) {
2323 size += bufferSize;
2324 }
2325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 if (client != NULL) {
2327 mCblkMemory = client->heap()->allocate(size);
2328 if (mCblkMemory != 0) {
2329 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2330 if (mCblk) { // construct the shared structure in-place.
2331 new(mCblk) audio_track_cblk_t();
2332 // clear all buffers
2333 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002334 mCblk->sampleRate = sampleRate;
2335 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 if (sharedBuffer == 0) {
2337 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2338 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2339 // Force underrun condition to avoid false underrun callback until first data is
2340 // written to buffer
2341 mCblk->flowControlFlag = 1;
2342 } else {
2343 mBuffer = sharedBuffer->pointer();
2344 }
2345 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 } else {
2348 LOGE("not enough memory for AudioTrack size=%u", size);
2349 client->heap()->dump("AudioTrack");
2350 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 } else {
2353 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2354 if (mCblk) { // construct the shared structure in-place.
2355 new(mCblk) audio_track_cblk_t();
2356 // clear all buffers
2357 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002358 mCblk->sampleRate = sampleRate;
2359 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2361 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2362 // Force underrun condition to avoid false underrun callback until first data is
2363 // written to buffer
2364 mCblk->flowControlFlag = 1;
2365 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2366 }
2367 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002368}
2369
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002370AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002371{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002373 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2374 if (mClient == NULL) {
2375 delete mCblk;
2376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002378 mCblkMemory.clear(); // and free the shared memory
Eric Laurentb9481d82009-09-17 05:12:56 -07002379 if (mClient != NULL) {
2380 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2381 mClient.clear();
2382 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002383}
2384
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002385void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002386{
2387 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002388 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002389 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002390 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002391}
2392
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002393bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002394 bool result;
2395 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002396
2397 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002398 if (!result) {
2399 LOGV("stepServer failed acquiring cblk mutex");
2400 mFlags |= STEPSERVER_FAILED;
2401 }
2402 return result;
2403}
2404
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002405void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002406 audio_track_cblk_t* cblk = this->cblk();
2407
2408 cblk->user = 0;
2409 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002410 cblk->userBase = 0;
2411 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002412 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002413 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002414}
2415
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002416sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002417{
2418 return mCblkMemory;
2419}
2420
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002421int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002422 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002423}
2424
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002425int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurent88e209d2009-07-07 07:10:45 -07002426 return (int)mCblk->channels;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002427}
2428
Eric Laurent2bb6b2a2009-09-16 06:02:45 -07002429void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002430 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002431 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2432 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002433
2434 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002435 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2436 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002437 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2438 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002439 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project10592532009-03-18 17:39:46 -07002440 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002441 return 0;
2442 }
2443
2444 return bufferStart;
2445}
2446
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002447// ----------------------------------------------------------------------------
2448
Eric Laurenta553c252009-07-17 12:17:14 -07002449// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2450AudioFlinger::PlaybackThread::Track::Track(
2451 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002452 const sp<Client>& client,
2453 int streamType,
2454 uint32_t sampleRate,
2455 int format,
2456 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002457 int frameCount,
2458 const sp<IMemory>& sharedBuffer)
Eric Laurenta553c252009-07-17 12:17:14 -07002459 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2460 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002461{
Eric Laurent8a77a992009-09-09 05:16:08 -07002462 if (mCblk != NULL) {
2463 sp<ThreadBase> baseThread = thread.promote();
2464 if (baseThread != 0) {
2465 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2466 mName = playbackThread->getTrackName_l();
2467 }
2468 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2469 if (mName < 0) {
2470 LOGE("no more track names available");
2471 }
2472 mVolume[0] = 1.0f;
2473 mVolume[1] = 1.0f;
2474 mStreamType = streamType;
2475 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2476 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2477 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurenta553c252009-07-17 12:17:14 -07002478 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002479}
2480
Eric Laurenta553c252009-07-17 12:17:14 -07002481AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002482{
Eric Laurenta553c252009-07-17 12:17:14 -07002483 LOGV("PlaybackThread::Track destructor");
2484 sp<ThreadBase> thread = mThread.promote();
2485 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002486 Mutex::Autolock _l(thread->mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002487 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002488 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002489}
2490
Eric Laurenta553c252009-07-17 12:17:14 -07002491void AudioFlinger::PlaybackThread::Track::destroy()
2492{
2493 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2494 // by removing it from mTracks vector, so there is a risk that this Tracks's
2495 // desctructor is called. As the destructor needs to lock mLock,
2496 // we must acquire a strong reference on this Track before locking mLock
2497 // here so that the destructor is called only when exiting this function.
2498 // On the other hand, as long as Track::destroy() is only called by
2499 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2500 // this Track with its member mTrack.
2501 sp<Track> keep(this);
2502 { // scope for mLock
2503 sp<ThreadBase> thread = mThread.promote();
2504 if (thread != 0) {
Eric Laurentac196e12009-12-01 02:17:41 -08002505 if (!isOutputTrack()) {
2506 if (mState == ACTIVE || mState == RESUMING) {
2507 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2508 }
2509 AudioSystem::releaseOutput(thread->id());
Eric Laurent49f02be2009-11-19 09:00:56 -08002510 }
Eric Laurenta553c252009-07-17 12:17:14 -07002511 Mutex::Autolock _l(thread->mLock);
2512 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2513 playbackThread->destroyTrack_l(this);
2514 }
2515 }
2516}
2517
2518void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002519{
Eric Laurent3fdb1262009-11-07 00:01:32 -08002520 snprintf(buffer, size, " %5d %5d %3u %3u %3u %04u %1d %1d %1d %5u %5u %5u %08x %08x\n",
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002521 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002523 mStreamType,
2524 mFormat,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002525 mCblk->channels,
2526 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002527 mState,
2528 mMute,
2529 mFillingUpStatus,
2530 mCblk->sampleRate,
2531 mCblk->volume[0],
2532 mCblk->volume[1],
2533 mCblk->server,
2534 mCblk->user);
2535}
2536
Eric Laurenta553c252009-07-17 12:17:14 -07002537status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002538{
2539 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002540 uint32_t framesReady;
2541 uint32_t framesReq = buffer->frameCount;
2542
2543 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002544 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2545 if (!step()) goto getNextBuffer_exit;
2546 LOGV("stepServer recovered");
2547 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2548 }
2549
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002550 framesReady = cblk->framesReady();
2551
2552 if (LIKELY(framesReady)) {
2553 uint32_t s = cblk->server;
2554 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2555
2556 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2557 if (framesReq > framesReady) {
2558 framesReq = framesReady;
2559 }
2560 if (s + framesReq > bufferEnd) {
2561 framesReq = bufferEnd - s;
2562 }
2563
2564 buffer->raw = getBuffer(s, framesReq);
2565 if (buffer->raw == 0) goto getNextBuffer_exit;
2566
2567 buffer->frameCount = framesReq;
2568 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002569 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002570
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002571getNextBuffer_exit:
2572 buffer->raw = 0;
2573 buffer->frameCount = 0;
Eric Laurent62443f52009-10-05 20:29:18 -07002574 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 -07002575 return NOT_ENOUGH_DATA;
2576}
2577
Eric Laurenta553c252009-07-17 12:17:14 -07002578bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002579 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002580
2581 if (mCblk->framesReady() >= mCblk->frameCount ||
2582 mCblk->forceReady) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002583 mFillingUpStatus = FS_FILLED;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002584 mCblk->forceReady = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002585 return true;
2586 }
2587 return false;
2588}
2589
Eric Laurenta553c252009-07-17 12:17:14 -07002590status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002591{
Eric Laurent49f02be2009-11-19 09:00:56 -08002592 status_t status = NO_ERROR;
Eric Laurenta553c252009-07-17 12:17:14 -07002593 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2594 sp<ThreadBase> thread = mThread.promote();
2595 if (thread != 0) {
2596 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002597 int state = mState;
2598 // here the track could be either new, or restarted
2599 // in both cases "unstop" the track
2600 if (mState == PAUSED) {
2601 mState = TrackBase::RESUMING;
2602 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2603 } else {
2604 mState = TrackBase::ACTIVE;
2605 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2606 }
2607
2608 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2609 thread->mLock.unlock();
2610 status = AudioSystem::startOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2611 thread->mLock.lock();
2612 }
2613 if (status == NO_ERROR) {
2614 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2615 playbackThread->addTrack_l(this);
2616 } else {
2617 mState = state;
2618 }
2619 } else {
2620 status = BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07002621 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002622 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002623}
2624
Eric Laurenta553c252009-07-17 12:17:14 -07002625void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002626{
Eric Laurenta553c252009-07-17 12:17:14 -07002627 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2628 sp<ThreadBase> thread = mThread.promote();
2629 if (thread != 0) {
2630 Mutex::Autolock _l(thread->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08002631 int state = mState;
Eric Laurenta553c252009-07-17 12:17:14 -07002632 if (mState > STOPPED) {
2633 mState = STOPPED;
2634 // If the track is not active (PAUSED and buffers full), flush buffers
2635 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2636 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2637 reset();
2638 }
Eric Laurent62443f52009-10-05 20:29:18 -07002639 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002640 }
Eric Laurent49f02be2009-11-19 09:00:56 -08002641 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
2642 thread->mLock.unlock();
2643 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2644 thread->mLock.lock();
2645 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002646 }
2647}
2648
Eric Laurenta553c252009-07-17 12:17:14 -07002649void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002650{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07002652 sp<ThreadBase> thread = mThread.promote();
2653 if (thread != 0) {
2654 Mutex::Autolock _l(thread->mLock);
2655 if (mState == ACTIVE || mState == RESUMING) {
2656 mState = PAUSING;
Eric Laurent62443f52009-10-05 20:29:18 -07002657 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent49f02be2009-11-19 09:00:56 -08002658 if (!isOutputTrack()) {
2659 thread->mLock.unlock();
2660 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2661 thread->mLock.lock();
2662 }
Eric Laurenta553c252009-07-17 12:17:14 -07002663 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002664 }
2665}
2666
Eric Laurenta553c252009-07-17 12:17:14 -07002667void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002668{
2669 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07002670 sp<ThreadBase> thread = mThread.promote();
2671 if (thread != 0) {
2672 Mutex::Autolock _l(thread->mLock);
2673 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2674 return;
2675 }
2676 // No point remaining in PAUSED state after a flush => go to
2677 // STOPPED state
2678 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002679
Eric Laurenta553c252009-07-17 12:17:14 -07002680 mCblk->lock.lock();
2681 // NOTE: reset() will reset cblk->user and cblk->server with
2682 // the risk that at the same time, the AudioMixer is trying to read
2683 // data. In this case, getNextBuffer() would return a NULL pointer
2684 // as audio buffer => the AudioMixer code MUST always test that pointer
2685 // returned by getNextBuffer() is not NULL!
2686 reset();
2687 mCblk->lock.unlock();
2688 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002689}
2690
Eric Laurenta553c252009-07-17 12:17:14 -07002691void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002692{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002693 // Do not reset twice to avoid discarding data written just after a flush and before
2694 // the audioflinger thread detects the track is stopped.
2695 if (!mResetDone) {
2696 TrackBase::reset();
2697 // Force underrun condition to avoid false underrun callback until first data is
2698 // written to buffer
2699 mCblk->flowControlFlag = 1;
2700 mCblk->forceReady = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002701 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002702 mResetDone = true;
2703 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002704}
2705
Eric Laurenta553c252009-07-17 12:17:14 -07002706void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002707{
2708 mMute = muted;
2709}
2710
Eric Laurenta553c252009-07-17 12:17:14 -07002711void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002712{
2713 mVolume[0] = left;
2714 mVolume[1] = right;
2715}
2716
2717// ----------------------------------------------------------------------------
2718
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002719// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002720AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2721 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 uint32_t sampleRate,
2724 int format,
2725 int channelCount,
2726 int frameCount,
2727 uint32_t flags)
Eric Laurenta553c252009-07-17 12:17:14 -07002728 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 channelCount, frameCount, flags, 0),
Eric Laurenta553c252009-07-17 12:17:14 -07002730 mOverflow(false)
2731{
Eric Laurent8a77a992009-09-09 05:16:08 -07002732 if (mCblk != NULL) {
2733 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2734 if (format == AudioSystem::PCM_16_BIT) {
2735 mCblk->frameSize = channelCount * sizeof(int16_t);
2736 } else if (format == AudioSystem::PCM_8_BIT) {
2737 mCblk->frameSize = channelCount * sizeof(int8_t);
2738 } else {
2739 mCblk->frameSize = sizeof(int8_t);
2740 }
2741 }
Eric Laurenta553c252009-07-17 12:17:14 -07002742}
2743
2744AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745{
Eric Laurent49f02be2009-11-19 09:00:56 -08002746 sp<ThreadBase> thread = mThread.promote();
2747 if (thread != 0) {
2748 AudioSystem::releaseInput(thread->id());
2749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750}
2751
Eric Laurenta553c252009-07-17 12:17:14 -07002752status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753{
2754 audio_track_cblk_t* cblk = this->cblk();
2755 uint32_t framesAvail;
2756 uint32_t framesReq = buffer->frameCount;
2757
2758 // Check if last stepServer failed, try to step now
2759 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2760 if (!step()) goto getNextBuffer_exit;
2761 LOGV("stepServer recovered");
2762 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2763 }
2764
2765 framesAvail = cblk->framesAvailable_l();
2766
2767 if (LIKELY(framesAvail)) {
2768 uint32_t s = cblk->server;
2769 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2770
2771 if (framesReq > framesAvail) {
2772 framesReq = framesAvail;
2773 }
2774 if (s + framesReq > bufferEnd) {
2775 framesReq = bufferEnd - s;
2776 }
2777
2778 buffer->raw = getBuffer(s, framesReq);
2779 if (buffer->raw == 0) goto getNextBuffer_exit;
2780
2781 buffer->frameCount = framesReq;
2782 return NO_ERROR;
2783 }
2784
2785getNextBuffer_exit:
2786 buffer->raw = 0;
2787 buffer->frameCount = 0;
2788 return NOT_ENOUGH_DATA;
2789}
2790
Eric Laurenta553c252009-07-17 12:17:14 -07002791status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792{
Eric Laurenta553c252009-07-17 12:17:14 -07002793 sp<ThreadBase> thread = mThread.promote();
2794 if (thread != 0) {
2795 RecordThread *recordThread = (RecordThread *)thread.get();
2796 return recordThread->start(this);
Eric Laurent49f02be2009-11-19 09:00:56 -08002797 } else {
2798 return BAD_VALUE;
Eric Laurenta553c252009-07-17 12:17:14 -07002799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800}
2801
Eric Laurenta553c252009-07-17 12:17:14 -07002802void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803{
Eric Laurenta553c252009-07-17 12:17:14 -07002804 sp<ThreadBase> thread = mThread.promote();
2805 if (thread != 0) {
2806 RecordThread *recordThread = (RecordThread *)thread.get();
2807 recordThread->stop(this);
2808 TrackBase::reset();
2809 // Force overerrun condition to avoid false overrun callback until first data is
2810 // read from buffer
2811 mCblk->flowControlFlag = 1;
2812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002813}
2814
Eric Laurent3fdb1262009-11-07 00:01:32 -08002815void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
2816{
2817 snprintf(buffer, size, " %05d %03u %03u %04u %01d %05u %08x %08x\n",
2818 (mClient == NULL) ? getpid() : mClient->pid(),
2819 mFormat,
2820 mCblk->channels,
2821 mFrameCount,
2822 mState,
2823 mCblk->sampleRate,
2824 mCblk->server,
2825 mCblk->user);
2826}
2827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828
2829// ----------------------------------------------------------------------------
2830
Eric Laurenta553c252009-07-17 12:17:14 -07002831AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2832 const wp<ThreadBase>& thread,
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002833 DuplicatingThread *sourceThread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 uint32_t sampleRate,
2835 int format,
2836 int channelCount,
2837 int frameCount)
Eric Laurenta553c252009-07-17 12:17:14 -07002838 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002839 mActive(false), mSourceThread(sourceThread)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840{
Eric Laurenta553c252009-07-17 12:17:14 -07002841
2842 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurent6c30a712009-08-10 23:22:32 -07002843 if (mCblk != NULL) {
2844 mCblk->out = 1;
2845 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2846 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2847 mOutBuffer.frameCount = 0;
Eric Laurent6c30a712009-08-10 23:22:32 -07002848 playbackThread->mTracks.add(this);
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002849 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p",
2850 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd);
Eric Laurent6c30a712009-08-10 23:22:32 -07002851 } else {
2852 LOGW("Error creating output track on thread %p", playbackThread);
2853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854}
2855
Eric Laurenta553c252009-07-17 12:17:14 -07002856AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857{
Eric Laurent6c30a712009-08-10 23:22:32 -07002858 clearBufferQueue();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859}
2860
Eric Laurenta553c252009-07-17 12:17:14 -07002861status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862{
2863 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07002864 if (status != NO_ERROR) {
2865 return status;
2866 }
2867
2868 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 mRetryCount = 127;
2870 return status;
2871}
2872
Eric Laurenta553c252009-07-17 12:17:14 -07002873void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874{
2875 Track::stop();
2876 clearBufferQueue();
2877 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002878 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879}
2880
Eric Laurenta553c252009-07-17 12:17:14 -07002881bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882{
2883 Buffer *pInBuffer;
2884 Buffer inBuffer;
2885 uint32_t channels = mCblk->channels;
Eric Laurenta553c252009-07-17 12:17:14 -07002886 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 inBuffer.frameCount = frames;
2888 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07002889
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002890 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurenta553c252009-07-17 12:17:14 -07002891
Eric Laurent62443f52009-10-05 20:29:18 -07002892 if (!mActive && frames != 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07002893 start();
2894 sp<ThreadBase> thread = mThread.promote();
2895 if (thread != 0) {
2896 MixerThread *mixerThread = (MixerThread *)thread.get();
2897 if (mCblk->frameCount > frames){
2898 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2899 uint32_t startFrames = (mCblk->frameCount - frames);
2900 pInBuffer = new Buffer;
2901 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2902 pInBuffer->frameCount = startFrames;
2903 pInBuffer->i16 = pInBuffer->mBuffer;
2904 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2905 mBufferQueue.add(pInBuffer);
2906 } else {
2907 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 }
Eric Laurenta553c252009-07-17 12:17:14 -07002910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 }
2912
Eric Laurenta553c252009-07-17 12:17:14 -07002913 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 // First write pending buffers, then new data
2915 if (mBufferQueue.size()) {
2916 pInBuffer = mBufferQueue.itemAt(0);
2917 } else {
2918 pInBuffer = &inBuffer;
2919 }
Eric Laurenta553c252009-07-17 12:17:14 -07002920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 if (pInBuffer->frameCount == 0) {
2922 break;
2923 }
Eric Laurenta553c252009-07-17 12:17:14 -07002924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 if (mOutBuffer.frameCount == 0) {
2926 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002927 nsecs_t startTime = systemTime();
2928 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002929 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurenta553c252009-07-17 12:17:14 -07002930 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 break;
2932 }
Eric Laurenta553c252009-07-17 12:17:14 -07002933 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurenta553c252009-07-17 12:17:14 -07002934 if (waitTimeLeftMs >= waitTimeMs) {
2935 waitTimeLeftMs -= waitTimeMs;
2936 } else {
2937 waitTimeLeftMs = 0;
2938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 }
Eric Laurenta553c252009-07-17 12:17:14 -07002940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2942 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2943 mCblk->stepUser(outFrames);
2944 pInBuffer->frameCount -= outFrames;
2945 pInBuffer->i16 += outFrames * channels;
2946 mOutBuffer.frameCount -= outFrames;
Eric Laurenta553c252009-07-17 12:17:14 -07002947 mOutBuffer.i16 += outFrames * channels;
2948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 if (pInBuffer->frameCount == 0) {
2950 if (mBufferQueue.size()) {
2951 mBufferQueue.removeAt(0);
2952 delete [] pInBuffer->mBuffer;
2953 delete pInBuffer;
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002954 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 -08002955 } else {
2956 break;
2957 }
2958 }
2959 }
Eric Laurenta553c252009-07-17 12:17:14 -07002960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 // If we could not write all frames, allocate a buffer and queue it for next time.
2962 if (inBuffer.frameCount) {
Eric Laurent8ac9f8d2009-12-18 05:47:48 -08002963 sp<ThreadBase> thread = mThread.promote();
2964 if (thread != 0 && !thread->standby()) {
2965 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2966 pInBuffer = new Buffer;
2967 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2968 pInBuffer->frameCount = inBuffer.frameCount;
2969 pInBuffer->i16 = pInBuffer->mBuffer;
2970 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2971 mBufferQueue.add(pInBuffer);
2972 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
2973 } else {
2974 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
2975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 }
2977 }
Eric Laurenta553c252009-07-17 12:17:14 -07002978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07002980 // 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 -08002981 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07002982 if (frames == 0 && mBufferQueue.size() == 0) {
2983 if (mCblk->user < mCblk->frameCount) {
2984 frames = mCblk->frameCount - mCblk->user;
2985 pInBuffer = new Buffer;
2986 pInBuffer->mBuffer = new int16_t[frames * channels];
2987 pInBuffer->frameCount = frames;
2988 pInBuffer->i16 = pInBuffer->mBuffer;
2989 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2990 mBufferQueue.add(pInBuffer);
Eric Laurent62443f52009-10-05 20:29:18 -07002991 } else if (mActive) {
Eric Laurenta553c252009-07-17 12:17:14 -07002992 stop();
2993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 }
2995
Eric Laurenta553c252009-07-17 12:17:14 -07002996 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997}
2998
Eric Laurenta553c252009-07-17 12:17:14 -07002999status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000{
3001 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 status_t result;
3003 audio_track_cblk_t* cblk = mCblk;
3004 uint32_t framesReq = buffer->frameCount;
3005
Eric Laurenta553c252009-07-17 12:17:14 -07003006// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 uint32_t framesAvail = cblk->framesAvailable();
3010
Eric Laurenta553c252009-07-17 12:17:14 -07003011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003013 Mutex::Autolock _l(cblk->lock);
3014 goto start_loop_here;
3015 while (framesAvail == 0) {
3016 active = mActive;
3017 if (UNLIKELY(!active)) {
3018 LOGV("Not active and NO_MORE_BUFFERS");
3019 return AudioTrack::NO_MORE_BUFFERS;
3020 }
3021 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
3022 if (result != NO_ERROR) {
3023 return AudioTrack::NO_MORE_BUFFERS;
3024 }
3025 // read the server count again
3026 start_loop_here:
3027 framesAvail = cblk->framesAvailable_l();
3028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
3030
Eric Laurenta553c252009-07-17 12:17:14 -07003031// if (framesAvail < framesReq) {
3032// return AudioTrack::NO_MORE_BUFFERS;
3033// }
3034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 if (framesReq > framesAvail) {
3036 framesReq = framesAvail;
3037 }
3038
3039 uint32_t u = cblk->user;
3040 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
3041
3042 if (u + framesReq > bufferEnd) {
3043 framesReq = bufferEnd - u;
3044 }
3045
3046 buffer->frameCount = framesReq;
3047 buffer->raw = (void *)cblk->buffer(u);
3048 return NO_ERROR;
3049}
3050
3051
Eric Laurenta553c252009-07-17 12:17:14 -07003052void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053{
3054 size_t size = mBufferQueue.size();
3055 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 for (size_t i = 0; i < size; i++) {
3058 pBuffer = mBufferQueue.itemAt(i);
3059 delete [] pBuffer->mBuffer;
3060 delete pBuffer;
3061 }
3062 mBufferQueue.clear();
3063}
3064
3065// ----------------------------------------------------------------------------
3066
3067AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
3068 : RefBase(),
3069 mAudioFlinger(audioFlinger),
Mathias Agopian6faf7892010-01-25 19:00:00 -08003070 mMemoryDealer(new MemoryDealer(1024*1024, "AudioFlinger::Client")),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 mPid(pid)
3072{
3073 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
3074}
3075
Eric Laurentb9481d82009-09-17 05:12:56 -07003076// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077AudioFlinger::Client::~Client()
3078{
Eric Laurentb9481d82009-09-17 05:12:56 -07003079 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080}
3081
3082const sp<MemoryDealer>& AudioFlinger::Client::heap() const
3083{
3084 return mMemoryDealer;
3085}
3086
3087// ----------------------------------------------------------------------------
3088
Eric Laurenta553c252009-07-17 12:17:14 -07003089AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003090 : BnAudioTrack(),
3091 mTrack(track)
3092{
3093}
3094
3095AudioFlinger::TrackHandle::~TrackHandle() {
3096 // just stop the track on deletion, associated resources
3097 // will be freed from the main thread once all pending buffers have
3098 // been played. Unless it's not in the active track list, in which
3099 // case we free everything now...
3100 mTrack->destroy();
3101}
3102
3103status_t AudioFlinger::TrackHandle::start() {
3104 return mTrack->start();
3105}
3106
3107void AudioFlinger::TrackHandle::stop() {
3108 mTrack->stop();
3109}
3110
3111void AudioFlinger::TrackHandle::flush() {
3112 mTrack->flush();
3113}
3114
3115void AudioFlinger::TrackHandle::mute(bool e) {
3116 mTrack->mute(e);
3117}
3118
3119void AudioFlinger::TrackHandle::pause() {
3120 mTrack->pause();
3121}
3122
3123void AudioFlinger::TrackHandle::setVolume(float left, float right) {
3124 mTrack->setVolume(left, right);
3125}
3126
3127sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
3128 return mTrack->getCblk();
3129}
3130
3131status_t AudioFlinger::TrackHandle::onTransact(
3132 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3133{
3134 return BnAudioTrack::onTransact(code, data, reply, flags);
3135}
3136
3137// ----------------------------------------------------------------------------
3138
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003139sp<IAudioRecord> AudioFlinger::openRecord(
3140 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07003141 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003142 uint32_t sampleRate,
3143 int format,
3144 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003145 int frameCount,
3146 uint32_t flags,
3147 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003148{
Eric Laurenta553c252009-07-17 12:17:14 -07003149 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003150 sp<RecordHandle> recordHandle;
3151 sp<Client> client;
3152 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003153 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07003154 RecordThread *thread;
3155 size_t inFrameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003156
3157 // check calling permissions
3158 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003159 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003160 goto Exit;
3161 }
3162
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003163 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003164 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003165 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003166 thread = checkRecordThread_l(input);
3167 if (thread == NULL) {
3168 lStatus = BAD_VALUE;
3169 goto Exit;
3170 }
3171
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003172 wclient = mClients.valueFor(pid);
3173 if (wclient != NULL) {
3174 client = wclient.promote();
3175 } else {
3176 client = new Client(this, pid);
3177 mClients.add(pid, client);
3178 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003179
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003180 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07003181 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07003182 format, channelCount, frameCount, flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 if (recordTrack->getCblk() == NULL) {
Eric Laurentb9481d82009-09-17 05:12:56 -07003185 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3186 // destructor is called by the TrackBase destructor with mLock held
3187 client.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 recordTrack.clear();
3189 lStatus = NO_MEMORY;
3190 goto Exit;
3191 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003192
3193 // return to handle to client
3194 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003195 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003196
3197Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003198 if (status) {
3199 *status = lStatus;
3200 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003201 return recordHandle;
3202}
3203
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003204// ----------------------------------------------------------------------------
3205
Eric Laurenta553c252009-07-17 12:17:14 -07003206AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003207 : BnAudioRecord(),
3208 mRecordTrack(recordTrack)
3209{
3210}
3211
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003212AudioFlinger::RecordHandle::~RecordHandle() {
3213 stop();
3214}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003215
3216status_t AudioFlinger::RecordHandle::start() {
3217 LOGV("RecordHandle::start()");
3218 return mRecordTrack->start();
3219}
3220
3221void AudioFlinger::RecordHandle::stop() {
3222 LOGV("RecordHandle::stop()");
3223 mRecordTrack->stop();
3224}
3225
3226sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3227 return mRecordTrack->getCblk();
3228}
3229
3230status_t AudioFlinger::RecordHandle::onTransact(
3231 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3232{
3233 return BnAudioRecord::onTransact(code, data, reply, flags);
3234}
3235
3236// ----------------------------------------------------------------------------
3237
Eric Laurent49f02be2009-11-19 09:00:56 -08003238AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3239 ThreadBase(audioFlinger, id),
Eric Laurenta553c252009-07-17 12:17:14 -07003240 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003241{
Eric Laurenta553c252009-07-17 12:17:14 -07003242 mReqChannelCount = AudioSystem::popCount(channels);
3243 mReqSampleRate = sampleRate;
3244 readInputParameters();
3245 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003246}
3247
Eric Laurenta553c252009-07-17 12:17:14 -07003248
3249AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003250{
Eric Laurenta553c252009-07-17 12:17:14 -07003251 delete[] mRsmpInBuffer;
3252 if (mResampler != 0) {
3253 delete mResampler;
3254 delete[] mRsmpOutBuffer;
3255 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003256}
3257
Eric Laurenta553c252009-07-17 12:17:14 -07003258void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003259{
Eric Laurenta553c252009-07-17 12:17:14 -07003260 const size_t SIZE = 256;
3261 char buffer[SIZE];
3262
3263 snprintf(buffer, SIZE, "Record Thread %p", this);
3264
3265 run(buffer, PRIORITY_URGENT_AUDIO);
3266}
Eric Laurent49f02be2009-11-19 09:00:56 -08003267
Eric Laurenta553c252009-07-17 12:17:14 -07003268bool AudioFlinger::RecordThread::threadLoop()
3269{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003270 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07003271 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003272
3273 // start recording
3274 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003275
Eric Laurenta553c252009-07-17 12:17:14 -07003276 processConfigEvents();
3277
3278 { // scope for mLock
3279 Mutex::Autolock _l(mLock);
3280 checkForNewParameters_l();
3281 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3282 if (!mStandby) {
3283 mInput->standby();
3284 mStandby = true;
3285 }
3286
3287 if (exitPending()) break;
3288
3289 LOGV("RecordThread: loop stopping");
3290 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003291 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003292 LOGV("RecordThread: loop starting");
3293 continue;
3294 }
3295 if (mActiveTrack != 0) {
3296 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003297 if (!mStandby) {
3298 mInput->standby();
3299 mStandby = true;
3300 }
Eric Laurenta553c252009-07-17 12:17:14 -07003301 mActiveTrack.clear();
3302 mStartStopCond.broadcast();
3303 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurenta553c252009-07-17 12:17:14 -07003304 if (mReqChannelCount != mActiveTrack->channelCount()) {
3305 mActiveTrack.clear();
Eric Laurent9cc489a2009-12-05 05:20:01 -08003306 mStartStopCond.broadcast();
3307 } else if (mBytesRead != 0) {
3308 // record start succeeds only if first read from audio input
3309 // succeeds
3310 if (mBytesRead > 0) {
3311 mActiveTrack->mState = TrackBase::ACTIVE;
3312 } else {
3313 mActiveTrack.clear();
3314 }
3315 mStartStopCond.broadcast();
Eric Laurenta553c252009-07-17 12:17:14 -07003316 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08003317 mStandby = false;
Eric Laurenta553c252009-07-17 12:17:14 -07003318 }
Eric Laurenta553c252009-07-17 12:17:14 -07003319 }
3320 }
3321
3322 if (mActiveTrack != 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003323 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3324 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003325 usleep(5000);
3326 continue;
3327 }
Eric Laurenta553c252009-07-17 12:17:14 -07003328 buffer.frameCount = mFrameCount;
3329 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3330 size_t framesOut = buffer.frameCount;
3331 if (mResampler == 0) {
3332 // no resampling
3333 while (framesOut) {
3334 size_t framesIn = mFrameCount - mRsmpInIndex;
3335 if (framesIn) {
3336 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3337 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3338 if (framesIn > framesOut)
3339 framesIn = framesOut;
3340 mRsmpInIndex += framesIn;
3341 framesOut -= framesIn;
3342 if (mChannelCount == mReqChannelCount ||
3343 mFormat != AudioSystem::PCM_16_BIT) {
3344 memcpy(dst, src, framesIn * mFrameSize);
3345 } else {
3346 int16_t *src16 = (int16_t *)src;
3347 int16_t *dst16 = (int16_t *)dst;
3348 if (mChannelCount == 1) {
3349 while (framesIn--) {
3350 *dst16++ = *src16;
3351 *dst16++ = *src16++;
3352 }
3353 } else {
3354 while (framesIn--) {
3355 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3356 src16 += 2;
3357 }
3358 }
3359 }
3360 }
3361 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurenta553c252009-07-17 12:17:14 -07003362 if (framesOut == mFrameCount &&
3363 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003364 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003365 framesOut = 0;
3366 } else {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003367 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurenta553c252009-07-17 12:17:14 -07003368 mRsmpInIndex = 0;
3369 }
Eric Laurent9cc489a2009-12-05 05:20:01 -08003370 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003371 LOGE("Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08003372 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003373 // Force input into standby so that it tries to
3374 // recover at next read attempt
3375 mInput->standby();
3376 usleep(5000);
Eric Laurent9cc489a2009-12-05 05:20:01 -08003377 }
Eric Laurenta553c252009-07-17 12:17:14 -07003378 mRsmpInIndex = mFrameCount;
3379 framesOut = 0;
3380 buffer.frameCount = 0;
3381 }
3382 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003383 }
3384 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07003385 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003386
Eric Laurenta553c252009-07-17 12:17:14 -07003387 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3388 // alter output frame count as if we were expecting stereo samples
3389 if (mChannelCount == 1 && mReqChannelCount == 1) {
3390 framesOut >>= 1;
3391 }
3392 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3393 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3394 // are 32 bit aligned which should be always true.
3395 if (mChannelCount == 2 && mReqChannelCount == 1) {
3396 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3397 // the resampler always outputs stereo samples: do post stereo to mono conversion
3398 int16_t *src = (int16_t *)mRsmpOutBuffer;
3399 int16_t *dst = buffer.i16;
3400 while (framesOut--) {
3401 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3402 src += 2;
3403 }
3404 } else {
3405 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3406 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003407
Eric Laurenta553c252009-07-17 12:17:14 -07003408 }
3409 mActiveTrack->releaseBuffer(&buffer);
3410 mActiveTrack->overflow();
3411 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003412 // client isn't retrieving buffers fast enough
3413 else {
Eric Laurenta553c252009-07-17 12:17:14 -07003414 if (!mActiveTrack->setOverflow())
3415 LOGW("RecordThread: buffer overflow");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003416 // Release the processor for a while before asking for a new buffer.
3417 // This will give the application more chance to read from the buffer and
3418 // clear the overflow.
3419 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003420 }
3421 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003422 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003423
Eric Laurenta553c252009-07-17 12:17:14 -07003424 if (!mStandby) {
3425 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003426 }
Eric Laurenta553c252009-07-17 12:17:14 -07003427 mActiveTrack.clear();
3428
Eric Laurent49f02be2009-11-19 09:00:56 -08003429 mStartStopCond.broadcast();
3430
Eric Laurenta553c252009-07-17 12:17:14 -07003431 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003432 return false;
3433}
3434
Eric Laurenta553c252009-07-17 12:17:14 -07003435status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003436{
Eric Laurenta553c252009-07-17 12:17:14 -07003437 LOGV("RecordThread::start");
Eric Laurent49f02be2009-11-19 09:00:56 -08003438 sp <ThreadBase> strongMe = this;
3439 status_t status = NO_ERROR;
3440 {
3441 AutoMutex lock(&mLock);
3442 if (mActiveTrack != 0) {
3443 if (recordTrack != mActiveTrack.get()) {
3444 status = -EBUSY;
3445 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003446 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent49f02be2009-11-19 09:00:56 -08003447 }
3448 return status;
3449 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003450
Eric Laurent49f02be2009-11-19 09:00:56 -08003451 recordTrack->mState = TrackBase::IDLE;
3452 mActiveTrack = recordTrack;
3453 mLock.unlock();
3454 status_t status = AudioSystem::startInput(mId);
3455 mLock.lock();
3456 if (status != NO_ERROR) {
3457 mActiveTrack.clear();
3458 return status;
3459 }
3460 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent9cc489a2009-12-05 05:20:01 -08003461 mRsmpInIndex = mFrameCount;
3462 mBytesRead = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003463 // signal thread to start
3464 LOGV("Signal record thread");
3465 mWaitWorkCV.signal();
3466 // do not wait for mStartStopCond if exiting
3467 if (mExiting) {
3468 mActiveTrack.clear();
3469 status = INVALID_OPERATION;
3470 goto startError;
3471 }
3472 mStartStopCond.wait(mLock);
3473 if (mActiveTrack == 0) {
3474 LOGV("Record failed to start");
3475 status = BAD_VALUE;
3476 goto startError;
3477 }
Eric Laurenta553c252009-07-17 12:17:14 -07003478 LOGV("Record started OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003479 return status;
Eric Laurenta553c252009-07-17 12:17:14 -07003480 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003481startError:
3482 AudioSystem::stopInput(mId);
3483 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003484}
3485
Eric Laurenta553c252009-07-17 12:17:14 -07003486void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3487 LOGV("RecordThread::stop");
Eric Laurent49f02be2009-11-19 09:00:56 -08003488 sp <ThreadBase> strongMe = this;
3489 {
3490 AutoMutex lock(&mLock);
3491 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3492 mActiveTrack->mState = TrackBase::PAUSING;
3493 // do not wait for mStartStopCond if exiting
3494 if (mExiting) {
3495 return;
3496 }
3497 mStartStopCond.wait(mLock);
3498 // if we have been restarted, recordTrack == mActiveTrack.get() here
3499 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3500 mLock.unlock();
3501 AudioSystem::stopInput(mId);
3502 mLock.lock();
Eric Laurent9cc489a2009-12-05 05:20:01 -08003503 LOGV("Record stopped OK");
Eric Laurent49f02be2009-11-19 09:00:56 -08003504 }
3505 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003506 }
3507}
3508
Eric Laurenta553c252009-07-17 12:17:14 -07003509status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510{
3511 const size_t SIZE = 256;
3512 char buffer[SIZE];
3513 String8 result;
3514 pid_t pid = 0;
3515
Eric Laurent3fdb1262009-11-07 00:01:32 -08003516 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3517 result.append(buffer);
3518
3519 if (mActiveTrack != 0) {
3520 result.append("Active Track:\n");
3521 result.append(" Clien Fmt Chn Buf S SRate Serv User\n");
3522 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 result.append(buffer);
Eric Laurent3fdb1262009-11-07 00:01:32 -08003524
3525 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3526 result.append(buffer);
3527 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3528 result.append(buffer);
3529 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3530 result.append(buffer);
3531 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3532 result.append(buffer);
3533 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3534 result.append(buffer);
3535
3536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 } else {
3538 result.append("No record client\n");
3539 }
3540 write(fd, result.string(), result.size());
Eric Laurent3fdb1262009-11-07 00:01:32 -08003541
3542 dumpBase(fd, args);
3543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 return NO_ERROR;
3545}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003546
Eric Laurenta553c252009-07-17 12:17:14 -07003547status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3548{
3549 size_t framesReq = buffer->frameCount;
3550 size_t framesReady = mFrameCount - mRsmpInIndex;
3551 int channelCount;
3552
3553 if (framesReady == 0) {
Eric Laurent9cc489a2009-12-05 05:20:01 -08003554 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3555 if (mBytesRead < 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07003556 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent9cc489a2009-12-05 05:20:01 -08003557 if (mActiveTrack->mState == TrackBase::ACTIVE) {
Eric Laurentba8811f2010-03-02 18:38:06 -08003558 // Force input into standby so that it tries to
3559 // recover at next read attempt
3560 mInput->standby();
3561 usleep(5000);
Eric Laurent9cc489a2009-12-05 05:20:01 -08003562 }
Eric Laurenta553c252009-07-17 12:17:14 -07003563 buffer->raw = 0;
3564 buffer->frameCount = 0;
3565 return NOT_ENOUGH_DATA;
3566 }
3567 mRsmpInIndex = 0;
3568 framesReady = mFrameCount;
3569 }
3570
3571 if (framesReq > framesReady) {
3572 framesReq = framesReady;
3573 }
3574
3575 if (mChannelCount == 1 && mReqChannelCount == 2) {
3576 channelCount = 1;
3577 } else {
3578 channelCount = 2;
3579 }
3580 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3581 buffer->frameCount = framesReq;
3582 return NO_ERROR;
3583}
3584
3585void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3586{
3587 mRsmpInIndex += buffer->frameCount;
3588 buffer->frameCount = 0;
3589}
3590
3591bool AudioFlinger::RecordThread::checkForNewParameters_l()
3592{
3593 bool reconfig = false;
3594
Eric Laurent8fce46a2009-08-04 09:45:33 -07003595 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07003596 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003597 String8 keyValuePair = mNewParameters[0];
3598 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003599 int value;
3600 int reqFormat = mFormat;
3601 int reqSamplingRate = mReqSampleRate;
3602 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003603
Eric Laurenta553c252009-07-17 12:17:14 -07003604 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3605 reqSamplingRate = value;
3606 reconfig = true;
3607 }
3608 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3609 reqFormat = value;
3610 reconfig = true;
3611 }
3612 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3613 reqChannelCount = AudioSystem::popCount(value);
3614 reconfig = true;
3615 }
3616 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3617 // do not accept frame count changes if tracks are open as the track buffer
3618 // size depends on frame count and correct behavior would not be garantied
3619 // if frame count is changed after track creation
3620 if (mActiveTrack != 0) {
3621 status = INVALID_OPERATION;
3622 } else {
3623 reconfig = true;
3624 }
3625 }
3626 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07003627 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003628 if (status == INVALID_OPERATION) {
3629 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003630 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003631 }
3632 if (reconfig) {
3633 if (status == BAD_VALUE &&
3634 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3635 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3636 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3637 status = NO_ERROR;
3638 }
3639 if (status == NO_ERROR) {
3640 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003641 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07003642 }
3643 }
3644 }
Eric Laurent3fdb1262009-11-07 00:01:32 -08003645
3646 mNewParameters.removeAt(0);
3647
Eric Laurenta553c252009-07-17 12:17:14 -07003648 mParamStatus = status;
3649 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003650 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003651 }
3652 return reconfig;
3653}
3654
3655String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3656{
3657 return mInput->getParameters(keys);
3658}
3659
3660void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3661 AudioSystem::OutputDescriptor desc;
3662 void *param2 = 0;
3663
3664 switch (event) {
3665 case AudioSystem::INPUT_OPENED:
3666 case AudioSystem::INPUT_CONFIG_CHANGED:
3667 desc.channels = mChannelCount;
3668 desc.samplingRate = mSampleRate;
3669 desc.format = mFormat;
3670 desc.frameCount = mFrameCount;
3671 desc.latency = 0;
3672 param2 = &desc;
3673 break;
3674
3675 case AudioSystem::INPUT_CLOSED:
3676 default:
3677 break;
3678 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07003679 Mutex::Autolock _l(mAudioFlinger->mLock);
Eric Laurent49f02be2009-11-19 09:00:56 -08003680 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurenta553c252009-07-17 12:17:14 -07003681}
3682
3683void AudioFlinger::RecordThread::readInputParameters()
3684{
3685 if (mRsmpInBuffer) delete mRsmpInBuffer;
3686 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3687 if (mResampler) delete mResampler;
3688 mResampler = 0;
3689
3690 mSampleRate = mInput->sampleRate();
3691 mChannelCount = AudioSystem::popCount(mInput->channels());
3692 mFormat = mInput->format();
3693 mFrameSize = mInput->frameSize();
3694 mInputBytes = mInput->bufferSize();
3695 mFrameCount = mInputBytes / mFrameSize;
3696 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3697
3698 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3699 {
3700 int channelCount;
3701 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3702 // stereo to mono post process as the resampler always outputs stereo.
3703 if (mChannelCount == 1 && mReqChannelCount == 2) {
3704 channelCount = 1;
3705 } else {
3706 channelCount = 2;
3707 }
3708 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3709 mResampler->setSampleRate(mSampleRate);
3710 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3711 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3712
3713 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3714 if (mChannelCount == 1 && mReqChannelCount == 1) {
3715 mFrameCount >>= 1;
3716 }
3717
3718 }
3719 mRsmpInIndex = mFrameCount;
3720}
3721
Eric Laurent47d0a922010-02-26 02:47:27 -08003722unsigned int AudioFlinger::RecordThread::getInputFramesLost()
3723{
3724 return mInput->getInputFramesLost();
3725}
3726
Eric Laurenta553c252009-07-17 12:17:14 -07003727// ----------------------------------------------------------------------------
3728
Eric Laurentddb78e72009-07-28 08:44:33 -07003729int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07003730 uint32_t *pSamplingRate,
3731 uint32_t *pFormat,
3732 uint32_t *pChannels,
3733 uint32_t *pLatencyMs,
3734 uint32_t flags)
3735{
3736 status_t status;
3737 PlaybackThread *thread = NULL;
3738 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3739 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3740 uint32_t format = pFormat ? *pFormat : 0;
3741 uint32_t channels = pChannels ? *pChannels : 0;
3742 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3743
3744 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3745 pDevices ? *pDevices : 0,
3746 samplingRate,
3747 format,
3748 channels,
3749 flags);
3750
3751 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003752 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003753 }
3754 Mutex::Autolock _l(mLock);
3755
3756 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3757 (int *)&format,
3758 &channels,
3759 &samplingRate,
3760 &status);
3761 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3762 output,
3763 samplingRate,
3764 format,
3765 channels,
3766 status);
3767
3768 mHardwareStatus = AUDIO_HW_IDLE;
3769 if (output != 0) {
3770 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3771 (format != AudioSystem::PCM_16_BIT) ||
3772 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent49f02be2009-11-19 09:00:56 -08003773 thread = new DirectOutputThread(this, output, ++mNextThreadId);
3774 LOGV("openOutput() created direct output: ID %d thread %p", mNextThreadId, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003775 } else {
Eric Laurent49f02be2009-11-19 09:00:56 -08003776 thread = new MixerThread(this, output, ++mNextThreadId);
3777 LOGV("openOutput() created mixer output: ID %d thread %p", mNextThreadId, thread);
Glenn Kasten871c16c2010-03-05 12:18:01 -08003778
3779#ifdef LVMX
3780 unsigned bitsPerSample =
3781 (format == AudioSystem::PCM_16_BIT) ? 16 :
3782 ((format == AudioSystem::PCM_8_BIT) ? 8 : 0);
3783 unsigned channelCount = (channels == AudioSystem::CHANNEL_OUT_STEREO) ? 2 : 1;
3784 int audioOutputType = LifeVibes::threadIdToAudioOutputType(thread->id());
3785
3786 LifeVibes::init_aot(audioOutputType, samplingRate, bitsPerSample, channelCount);
3787 LifeVibes::setDevice(audioOutputType, *pDevices);
3788#endif
3789
Eric Laurenta553c252009-07-17 12:17:14 -07003790 }
Eric Laurent49f02be2009-11-19 09:00:56 -08003791 mPlaybackThreads.add(mNextThreadId, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003792
3793 if (pSamplingRate) *pSamplingRate = samplingRate;
3794 if (pFormat) *pFormat = format;
3795 if (pChannels) *pChannels = channels;
3796 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent9cc489a2009-12-05 05:20:01 -08003797
3798 return mNextThreadId;
Eric Laurenta553c252009-07-17 12:17:14 -07003799 }
3800
Eric Laurent9cc489a2009-12-05 05:20:01 -08003801 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003802}
3803
Eric Laurentddb78e72009-07-28 08:44:33 -07003804int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07003805{
3806 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07003807 MixerThread *thread1 = checkMixerThread_l(output1);
3808 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07003809
Eric Laurentddb78e72009-07-28 08:44:33 -07003810 if (thread1 == NULL || thread2 == NULL) {
3811 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3812 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003813 }
3814
Eric Laurentddb78e72009-07-28 08:44:33 -07003815
Eric Laurent49f02be2009-11-19 09:00:56 -08003816 DuplicatingThread *thread = new DuplicatingThread(this, thread1, ++mNextThreadId);
Eric Laurentddb78e72009-07-28 08:44:33 -07003817 thread->addOutputTrack(thread2);
Eric Laurent49f02be2009-11-19 09:00:56 -08003818 mPlaybackThreads.add(mNextThreadId, thread);
Eric Laurentddb78e72009-07-28 08:44:33 -07003819 return mNextThreadId;
Eric Laurenta553c252009-07-17 12:17:14 -07003820}
3821
Eric Laurentddb78e72009-07-28 08:44:33 -07003822status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003823{
Eric Laurent49018a52009-08-04 08:37:05 -07003824 // keep strong reference on the playback thread so that
3825 // it is not destroyed while exit() is executed
3826 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07003827 {
3828 Mutex::Autolock _l(mLock);
3829 thread = checkPlaybackThread_l(output);
3830 if (thread == NULL) {
3831 return BAD_VALUE;
3832 }
3833
Eric Laurentddb78e72009-07-28 08:44:33 -07003834 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003835
3836 if (thread->type() == PlaybackThread::MIXER) {
3837 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003838 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3839 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07003840 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07003841 }
3842 }
3843 }
Eric Laurent296a0ec2009-09-15 07:10:12 -07003844 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003845 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07003846 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07003847 }
3848 thread->exit();
3849
Eric Laurent49018a52009-08-04 08:37:05 -07003850 if (thread->type() != PlaybackThread::DUPLICATING) {
3851 mAudioHardware->closeOutputStream(thread->getOutput());
3852 }
Eric Laurenta553c252009-07-17 12:17:14 -07003853 return NO_ERROR;
3854}
3855
Eric Laurentddb78e72009-07-28 08:44:33 -07003856status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003857{
3858 Mutex::Autolock _l(mLock);
3859 PlaybackThread *thread = checkPlaybackThread_l(output);
3860
3861 if (thread == NULL) {
3862 return BAD_VALUE;
3863 }
3864
Eric Laurentddb78e72009-07-28 08:44:33 -07003865 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003866 thread->suspend();
3867
3868 return NO_ERROR;
3869}
3870
Eric Laurentddb78e72009-07-28 08:44:33 -07003871status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003872{
3873 Mutex::Autolock _l(mLock);
3874 PlaybackThread *thread = checkPlaybackThread_l(output);
3875
3876 if (thread == NULL) {
3877 return BAD_VALUE;
3878 }
3879
Eric Laurentddb78e72009-07-28 08:44:33 -07003880 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003881
3882 thread->restore();
3883
3884 return NO_ERROR;
3885}
3886
Eric Laurentddb78e72009-07-28 08:44:33 -07003887int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07003888 uint32_t *pSamplingRate,
3889 uint32_t *pFormat,
3890 uint32_t *pChannels,
3891 uint32_t acoustics)
3892{
3893 status_t status;
3894 RecordThread *thread = NULL;
3895 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3896 uint32_t format = pFormat ? *pFormat : 0;
3897 uint32_t channels = pChannels ? *pChannels : 0;
3898 uint32_t reqSamplingRate = samplingRate;
3899 uint32_t reqFormat = format;
3900 uint32_t reqChannels = channels;
3901
3902 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003903 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003904 }
3905 Mutex::Autolock _l(mLock);
3906
3907 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3908 (int *)&format,
3909 &channels,
3910 &samplingRate,
3911 &status,
3912 (AudioSystem::audio_in_acoustics)acoustics);
3913 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3914 input,
3915 samplingRate,
3916 format,
3917 channels,
3918 acoustics,
3919 status);
3920
3921 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3922 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3923 // or stereo to mono conversions on 16 bit PCM inputs.
3924 if (input == 0 && status == BAD_VALUE &&
3925 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3926 (samplingRate <= 2 * reqSamplingRate) &&
3927 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3928 LOGV("openInput() reopening with proposed sampling rate and channels");
3929 input = mAudioHardware->openInputStream(*pDevices,
3930 (int *)&format,
3931 &channels,
3932 &samplingRate,
3933 &status,
3934 (AudioSystem::audio_in_acoustics)acoustics);
3935 }
3936
3937 if (input != 0) {
3938 // Start record thread
Eric Laurent49f02be2009-11-19 09:00:56 -08003939 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, ++mNextThreadId);
3940 mRecordThreads.add(mNextThreadId, thread);
Eric Laurentddb78e72009-07-28 08:44:33 -07003941 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003942 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3943 if (pFormat) *pFormat = format;
3944 if (pChannels) *pChannels = reqChannels;
3945
3946 input->standby();
Eric Laurent9cc489a2009-12-05 05:20:01 -08003947
3948 return mNextThreadId;
Eric Laurenta553c252009-07-17 12:17:14 -07003949 }
3950
Eric Laurent9cc489a2009-12-05 05:20:01 -08003951 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003952}
3953
Eric Laurentddb78e72009-07-28 08:44:33 -07003954status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07003955{
Eric Laurent49018a52009-08-04 08:37:05 -07003956 // keep strong reference on the record thread so that
3957 // it is not destroyed while exit() is executed
3958 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07003959 {
3960 Mutex::Autolock _l(mLock);
3961 thread = checkRecordThread_l(input);
3962 if (thread == NULL) {
3963 return BAD_VALUE;
3964 }
3965
Eric Laurentddb78e72009-07-28 08:44:33 -07003966 LOGV("closeInput() %d", input);
Eric Laurent296a0ec2009-09-15 07:10:12 -07003967 void *param2 = 0;
Eric Laurent49f02be2009-11-19 09:00:56 -08003968 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurentddb78e72009-07-28 08:44:33 -07003969 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07003970 }
3971 thread->exit();
3972
Eric Laurent49018a52009-08-04 08:37:05 -07003973 mAudioHardware->closeInputStream(thread->getInput());
3974
Eric Laurenta553c252009-07-17 12:17:14 -07003975 return NO_ERROR;
3976}
3977
Eric Laurentddb78e72009-07-28 08:44:33 -07003978status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003979{
3980 Mutex::Autolock _l(mLock);
3981 MixerThread *dstThread = checkMixerThread_l(output);
3982 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003983 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003984 return BAD_VALUE;
3985 }
3986
Eric Laurentddb78e72009-07-28 08:44:33 -07003987 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenta553c252009-07-17 12:17:14 -07003988
3989 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003990 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07003991 if (thread != dstThread &&
3992 thread->type() != PlaybackThread::DIRECT) {
3993 MixerThread *srcThread = (MixerThread *)thread;
3994 SortedVector < sp<MixerThread::Track> > tracks;
3995 SortedVector < wp<MixerThread::Track> > activeTracks;
3996 srcThread->getTracks(tracks, activeTracks, stream);
3997 if (tracks.size()) {
3998 dstThread->putTracks(tracks, activeTracks);
Eric Laurenta553c252009-07-17 12:17:14 -07003999 }
4000 }
4001 }
4002
Eric Laurentd069f322009-09-01 05:56:26 -07004003 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
4004
Eric Laurenta553c252009-07-17 12:17:14 -07004005 return NO_ERROR;
4006}
4007
4008// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004009AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004010{
4011 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004012 if (mPlaybackThreads.indexOfKey(output) >= 0) {
4013 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004014 }
Eric Laurenta553c252009-07-17 12:17:14 -07004015 return thread;
4016}
4017
4018// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004019AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07004020{
4021 PlaybackThread *thread = checkPlaybackThread_l(output);
4022 if (thread != NULL) {
4023 if (thread->type() == PlaybackThread::DIRECT) {
4024 thread = NULL;
4025 }
4026 }
4027 return (MixerThread *)thread;
4028}
4029
4030// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07004031AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07004032{
4033 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07004034 if (mRecordThreads.indexOfKey(input) >= 0) {
4035 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07004036 }
Eric Laurenta553c252009-07-17 12:17:14 -07004037 return thread;
4038}
4039
4040// ----------------------------------------------------------------------------
4041
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004042status_t AudioFlinger::onTransact(
4043 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4044{
4045 return BnAudioFlinger::onTransact(code, data, reply, flags);
4046}
4047
4048// ----------------------------------------------------------------------------
Eric Laurenta553c252009-07-17 12:17:14 -07004049
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07004050void AudioFlinger::instantiate() {
4051 defaultServiceManager()->addService(
4052 String16("media.audio_flinger"), new AudioFlinger());
4053}
4054
4055}; // namespace android