blob: 650079141284761cb788a1a41eb31f1211748683 [file] [log] [blame]
The Android Open Source Project7c1b96a2008-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 Agopianc5b2c0b2009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project7c1b96a2008-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 Project8a7a6752009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050// ----------------------------------------------------------------------------
51// the sim build doesn't have gettid
52
53#ifndef HAVE_GETTID
54# define gettid getpid
55#endif
56
57// ----------------------------------------------------------------------------
58
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070059namespace android {
60
The Android Open Source Project4f68be12009-03-18 17:39:46 -070061static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
62static const char* kHardwareLockedString = "Hardware lock is taken\n";
63
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080064//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070065static const unsigned long kBufferRecoveryInUsecs = 2000;
66static const unsigned long kMaxBufferRecoveryInUsecs = 20000;
67static const float MAX_GAIN = 4096.0f;
68
69// retry counts for buffer fill timeout
70// 50 * ~20msecs = 1 second
71static const int8_t kMaxTrackRetries = 50;
72static const int8_t kMaxTrackStartupRetries = 50;
73
The Android Open Source Project22f8def2009-03-09 11:52:12 -070074static const int kDumpLockRetries = 50;
75static const int kDumpLockSleep = 20000;
76
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070078#define AUDIOFLINGER_SECURITY_ENABLED 1
79
80// ----------------------------------------------------------------------------
81
82static bool recordingAllowed() {
83#ifndef HAVE_ANDROID_OS
84 return true;
85#endif
86#if AUDIOFLINGER_SECURITY_ENABLED
87 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
88 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
89 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
90 return ok;
91#else
92 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
93 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
94 return true;
95#endif
96}
97
98static bool settingsAllowed() {
99#ifndef HAVE_ANDROID_OS
100 return true;
101#endif
102#if AUDIOFLINGER_SECURITY_ENABLED
103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
105 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
106 return ok;
107#else
108 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
109 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
110 return true;
111#endif
112}
113
114// ----------------------------------------------------------------------------
115
116AudioFlinger::AudioFlinger()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117 : BnAudioFlinger(),
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700118 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700119{
120 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700121
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700122 mAudioHardware = AudioHardwareInterface::create();
Eric Laurent9d91ad52009-07-17 12:17:14 -0700123
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700124 mHardwareStatus = AUDIO_HW_INIT;
125 if (mAudioHardware->initCheck() == NO_ERROR) {
126 // open 16-bit output stream for s/w mixer
Eric Laurent9d91ad52009-07-17 12:17:14 -0700127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 setMode(AudioSystem::MODE_NORMAL);
129
130 setMasterVolume(1.0f);
131 setMasterMute(false);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700132 } else {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700133 LOGE("Couldn't even initialize the stubbed audio hardware!");
134 }
135}
136
137AudioFlinger::~AudioFlinger()
138{
Eric Laurentc80b1a02009-08-28 10:39:03 -0700139 while (!mRecordThreads.isEmpty()) {
140 // closeInput() will remove first entry from mRecordThreads
141 closeInput(mRecordThreads.keyAt(0));
142 }
143 while (!mPlaybackThreads.isEmpty()) {
144 // closeOutput() will remove first entry from mPlaybackThreads
145 closeOutput(mPlaybackThreads.keyAt(0));
146 }
147 if (mAudioHardware) {
148 delete mAudioHardware;
149 }
The Android Open Source Project27629322009-01-09 17:51:23 -0800150}
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800151
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700152
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700153
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700154status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
155{
156 const size_t SIZE = 256;
157 char buffer[SIZE];
158 String8 result;
159
160 result.append("Clients:\n");
161 for (size_t i = 0; i < mClients.size(); ++i) {
162 wp<Client> wClient = mClients.valueAt(i);
163 if (wClient != 0) {
164 sp<Client> client = wClient.promote();
165 if (client != 0) {
166 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
167 result.append(buffer);
168 }
169 }
170 }
171 write(fd, result.string(), result.size());
172 return NO_ERROR;
173}
174
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700175
176status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
177{
178 const size_t SIZE = 256;
179 char buffer[SIZE];
180 String8 result;
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700181 int hardwareStatus = mHardwareStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700182
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700183 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700184 result.append(buffer);
185 write(fd, result.string(), result.size());
186 return NO_ERROR;
187}
188
189status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
190{
191 const size_t SIZE = 256;
192 char buffer[SIZE];
193 String8 result;
194 snprintf(buffer, SIZE, "Permission Denial: "
195 "can't dump AudioFlinger from pid=%d, uid=%d\n",
196 IPCThreadState::self()->getCallingPid(),
197 IPCThreadState::self()->getCallingUid());
198 result.append(buffer);
199 write(fd, result.string(), result.size());
200 return NO_ERROR;
201}
202
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700203static bool tryLock(Mutex& mutex)
204{
205 bool locked = false;
206 for (int i = 0; i < kDumpLockRetries; ++i) {
207 if (mutex.tryLock() == NO_ERROR) {
208 locked = true;
209 break;
210 }
211 usleep(kDumpLockSleep);
212 }
213 return locked;
214}
215
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700216status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
217{
218 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
219 dumpPermissionDenial(fd, args);
220 } else {
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700221 // get state of hardware lock
222 bool hardwareLocked = tryLock(mHardwareLock);
223 if (!hardwareLocked) {
224 String8 result(kHardwareLockedString);
225 write(fd, result.string(), result.size());
226 } else {
227 mHardwareLock.unlock();
228 }
229
230 bool locked = tryLock(mLock);
231
232 // failed to lock - AudioFlinger is probably deadlocked
233 if (!locked) {
234 String8 result(kDeadlockedString);
235 write(fd, result.string(), result.size());
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700236 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700237
238 dumpClients(fd, args);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700239 dumpInternals(fd, args);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240
Eric Laurent9d91ad52009-07-17 12:17:14 -0700241 // dump playback threads
242 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700243 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700244 }
245
246 // dump record threads
Eric Laurentfd558a92009-07-23 13:35:01 -0700247 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700248 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700249 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700251 if (mAudioHardware) {
252 mAudioHardware->dumpState(fd, args);
253 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700254 if (locked) mLock.unlock();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700255 }
256 return NO_ERROR;
257}
258
Eric Laurent9d91ad52009-07-17 12:17:14 -0700259
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700260// IAudioFlinger interface
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261
262
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700263sp<IAudioTrack> AudioFlinger::createTrack(
264 pid_t pid,
265 int streamType,
266 uint32_t sampleRate,
267 int format,
268 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800269 int frameCount,
270 uint32_t flags,
271 const sp<IMemory>& sharedBuffer,
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700272 int output,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800273 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700274{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700275 sp<PlaybackThread::Track> track;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700276 sp<TrackHandle> trackHandle;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700277 sp<Client> client;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800278 wp<Client> wclient;
279 status_t lStatus;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700280
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800281 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800282 LOGE("invalid stream type");
283 lStatus = BAD_VALUE;
284 goto Exit;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700285 }
286
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800287 {
288 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700289 PlaybackThread *thread = checkPlaybackThread_l(output);
290 if (thread == NULL) {
291 LOGE("unknown output thread");
292 lStatus = BAD_VALUE;
293 goto Exit;
294 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800295
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800296 wclient = mClients.valueFor(pid);
297
298 if (wclient != NULL) {
299 client = wclient.promote();
300 } else {
301 client = new Client(this, pid);
302 mClients.add(pid, client);
303 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700304 track = thread->createTrack_l(client, streamType, sampleRate, format,
305 channelCount, frameCount, sharedBuffer, &lStatus);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700306 }
307 if (lStatus == NO_ERROR) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800308 trackHandle = new TrackHandle(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700309 } else {
Eric Laurent0f8ab672009-09-17 05:12:56 -0700310 // remove local strong reference to Client before deleting the Track so that the Client
311 // destructor is called by the TrackBase destructor with mLock held
312 client.clear();
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700313 track.clear();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800314 }
315
316Exit:
317 if(status) {
318 *status = lStatus;
319 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700320 return trackHandle;
321}
322
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700323uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700324{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700325 Mutex::Autolock _l(mLock);
326 PlaybackThread *thread = checkPlaybackThread_l(output);
327 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700328 LOGW("sampleRate() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700329 return 0;
330 }
331 return thread->sampleRate();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700332}
333
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700334int AudioFlinger::channelCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700335{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700336 Mutex::Autolock _l(mLock);
337 PlaybackThread *thread = checkPlaybackThread_l(output);
338 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700339 LOGW("channelCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700340 return 0;
341 }
342 return thread->channelCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700343}
344
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700345int AudioFlinger::format(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700346{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700347 Mutex::Autolock _l(mLock);
348 PlaybackThread *thread = checkPlaybackThread_l(output);
349 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700350 LOGW("format() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700351 return 0;
352 }
353 return thread->format();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700354}
355
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700356size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700357{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700358 Mutex::Autolock _l(mLock);
359 PlaybackThread *thread = checkPlaybackThread_l(output);
360 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700361 LOGW("frameCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700362 return 0;
363 }
364 return thread->frameCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700365}
366
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700367uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800368{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700369 Mutex::Autolock _l(mLock);
370 PlaybackThread *thread = checkPlaybackThread_l(output);
371 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700372 LOGW("latency() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700373 return 0;
374 }
375 return thread->latency();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800376}
377
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700378status_t AudioFlinger::setMasterVolume(float value)
379{
380 // check calling permissions
381 if (!settingsAllowed()) {
382 return PERMISSION_DENIED;
383 }
384
385 // when hw supports master volume, don't scale in sw mixer
386 AutoMutex lock(mHardwareLock);
387 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
388 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389 value = 1.0f;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700390 }
391 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700392
393 mMasterVolume = value;
394 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700395 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700396
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700397 return NO_ERROR;
398}
399
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700400status_t AudioFlinger::setMode(int mode)
401{
402 // check calling permissions
403 if (!settingsAllowed()) {
404 return PERMISSION_DENIED;
405 }
406 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
407 LOGW("Illegal value: setMode(%d)", mode);
408 return BAD_VALUE;
409 }
410
411 AutoMutex lock(mHardwareLock);
412 mHardwareStatus = AUDIO_HW_SET_MODE;
413 status_t ret = mAudioHardware->setMode(mode);
414 mHardwareStatus = AUDIO_HW_IDLE;
415 return ret;
416}
417
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700418status_t AudioFlinger::setMicMute(bool state)
419{
420 // check calling permissions
421 if (!settingsAllowed()) {
422 return PERMISSION_DENIED;
423 }
424
425 AutoMutex lock(mHardwareLock);
426 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
427 status_t ret = mAudioHardware->setMicMute(state);
428 mHardwareStatus = AUDIO_HW_IDLE;
429 return ret;
430}
431
432bool AudioFlinger::getMicMute() const
433{
434 bool state = AudioSystem::MODE_INVALID;
435 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
436 mAudioHardware->getMicMute(&state);
437 mHardwareStatus = AUDIO_HW_IDLE;
438 return state;
439}
440
441status_t AudioFlinger::setMasterMute(bool muted)
442{
443 // check calling permissions
444 if (!settingsAllowed()) {
445 return PERMISSION_DENIED;
446 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700447
448 mMasterMute = muted;
449 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700450 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700451
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700452 return NO_ERROR;
453}
454
455float AudioFlinger::masterVolume() const
456{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700457 return mMasterVolume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700458}
459
460bool AudioFlinger::masterMute() const
461{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700462 return mMasterMute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700463}
464
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700465status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700466{
467 // check calling permissions
468 if (!settingsAllowed()) {
469 return PERMISSION_DENIED;
470 }
471
Eric Laurent9d91ad52009-07-17 12:17:14 -0700472 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700473 return BAD_VALUE;
474 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800475
Eric Laurent9d91ad52009-07-17 12:17:14 -0700476 AutoMutex lock(mLock);
477 PlaybackThread *thread = NULL;
478 if (output) {
479 thread = checkPlaybackThread_l(output);
480 if (thread == NULL) {
481 return BAD_VALUE;
482 }
483 }
484
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700485 status_t ret = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487 if (stream == AudioSystem::VOICE_CALL ||
488 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700489 float hwValue;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800490 if (stream == AudioSystem::VOICE_CALL) {
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700491 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurent4dd495b2009-04-21 07:56:33 -0700492 // offset value to reflect actual hardware volume that never reaches 0
493 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
494 value = 0.01 + 0.99 * value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800495 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700496 hwValue = 1.0f;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800497 }
498
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700499 AutoMutex lock(mHardwareLock);
500 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700501 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700502 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503
Eric Laurent9d91ad52009-07-17 12:17:14 -0700504 }
505
506 mStreamTypes[stream].volume = value;
507
508 if (thread == NULL) {
509 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700510 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700511
512 } else {
513 thread->setStreamVolume(stream, value);
514 }
Eric Laurent4dd495b2009-04-21 07:56:33 -0700515
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700516 return ret;
517}
518
519status_t AudioFlinger::setStreamMute(int stream, bool muted)
520{
521 // check calling permissions
522 if (!settingsAllowed()) {
523 return PERMISSION_DENIED;
524 }
525
Eric Laurent9d91ad52009-07-17 12:17:14 -0700526 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurentb1596ee2009-03-26 01:57:59 -0700527 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700528 return BAD_VALUE;
529 }
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700530
Eric Laurent9d91ad52009-07-17 12:17:14 -0700531 mStreamTypes[stream].mute = muted;
532 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700533 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700535 return NO_ERROR;
536}
537
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700538float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700539{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700540 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700541 return 0.0f;
542 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700543
544 AutoMutex lock(mLock);
545 float volume;
546 if (output) {
547 PlaybackThread *thread = checkPlaybackThread_l(output);
548 if (thread == NULL) {
549 return 0.0f;
550 }
551 volume = thread->streamVolume(stream);
552 } else {
553 volume = mStreamTypes[stream].volume;
554 }
555
Eric Laurent4dd495b2009-04-21 07:56:33 -0700556 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700557 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700558 volume = (volume - 0.01) / 0.99 ;
James E. Blair6015dfc2009-01-17 13:30:20 -0800559 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700560
Eric Laurent4dd495b2009-04-21 07:56:33 -0700561 return volume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700562}
563
564bool AudioFlinger::streamMute(int stream) const
565{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700566 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700567 return true;
568 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700569
570 return mStreamTypes[stream].mute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700571}
572
573bool AudioFlinger::isMusicActive() const
574{
Eric Laurentb025ca02009-07-09 03:20:57 -0700575 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700576 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700577 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700578 return true;
579 }
580 }
581 return false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700582}
583
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700584status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700585{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700586 status_t result;
587
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700588 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700589 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
590 // check calling permissions
591 if (!settingsAllowed()) {
592 return PERMISSION_DENIED;
The Android Open Source Project8a7a6752009-01-15 16:12:10 -0800593 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700594
595 // ioHandle == 0 means the parameters are global to the audio hardware interface
596 if (ioHandle == 0) {
597 AutoMutex lock(mHardwareLock);
598 mHardwareStatus = AUDIO_SET_PARAMETER;
599 result = mAudioHardware->setParameters(keyValuePairs);
600 mHardwareStatus = AUDIO_HW_IDLE;
601 return result;
602 }
603
604 // Check if parameters are for an output
605 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
606 if (playbackThread != NULL) {
607 return playbackThread->setParameters(keyValuePairs);
608 }
609
610 // Check if parameters are for an input
611 RecordThread *recordThread = checkRecordThread_l(ioHandle);
612 if (recordThread != NULL) {
613 return recordThread->setParameters(keyValuePairs);
614 }
615
616 return BAD_VALUE;
617}
618
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700619String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700620{
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700621// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700622// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
623
624 if (ioHandle == 0) {
625 return mAudioHardware->getParameters(keys);
626 }
627 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
628 if (playbackThread != NULL) {
629 return playbackThread->getParameters(keys);
630 }
631 RecordThread *recordThread = checkRecordThread_l(ioHandle);
632 if (recordThread != NULL) {
633 return recordThread->getParameters(keys);
634 }
635 return String8("");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700636}
637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800638size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
639{
640 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
641}
642
643void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
644{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800646 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
647 Mutex::Autolock _l(mLock);
648
649 sp<IBinder> binder = client->asBinder();
650 if (mNotificationClients.indexOf(binder) < 0) {
651 LOGV("Adding notification client %p", binder.get());
652 binder->linkToDeath(this);
653 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700654 }
655
656 // the config change is always sent from playback or record threads to avoid deadlock
657 // with AudioSystem::gLock
658 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700659 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700660 }
661
662 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700663 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800664 }
665}
666
667void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700668
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800669 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
670 Mutex::Autolock _l(mLock);
671
672 IBinder *binder = who.unsafe_get();
673
674 if (binder != NULL) {
675 int index = mNotificationClients.indexOf(binder);
676 if (index >= 0) {
677 LOGV("Removing notification client %p", binder);
678 mNotificationClients.removeAt(index);
679 }
680 }
681}
682
Eric Laurentb3687ae2009-09-15 07:10:12 -0700683// audioConfigChanged_l() must be called with AudioFlinger::mLock held
684void AudioFlinger::audioConfigChanged_l(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700685 int ioHandle = 0;
686
687 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
688 if (mPlaybackThreads.valueAt(i) == thread) {
689 ioHandle = mPlaybackThreads.keyAt(i);
690 break;
691 }
692 }
693 if (ioHandle == 0) {
694 for (size_t i = 0; i < mRecordThreads.size(); i++) {
695 if (mRecordThreads.valueAt(i) == thread) {
696 ioHandle = mRecordThreads.keyAt(i);
697 break;
698 }
699 }
700 }
701
702 if (ioHandle != 0) {
703 size_t size = mNotificationClients.size();
704 for (size_t i = 0; i < size; i++) {
705 sp<IBinder> binder = mNotificationClients.itemAt(i);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700706 LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700707 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
708 client->ioConfigChanged(event, ioHandle, param2);
709 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700710 }
711}
712
Eric Laurent0f8ab672009-09-17 05:12:56 -0700713// removeClient_l() must be called with AudioFlinger::mLock held
714void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700715{
Eric Laurent0f8ab672009-09-17 05:12:56 -0700716 LOGV("removeClient_l() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700717 mClients.removeItem(pid);
718}
719
Eric Laurent9d91ad52009-07-17 12:17:14 -0700720// ----------------------------------------------------------------------------
721
722AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
723 : Thread(false),
724 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent3464c012009-08-04 09:45:33 -0700725 mFormat(0), mFrameSize(1), mStandby(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700726{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800727}
728
Eric Laurent9d91ad52009-07-17 12:17:14 -0700729AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730{
Eric Laurent3464c012009-08-04 09:45:33 -0700731 mParamCond.broadcast();
732 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800733}
734
Eric Laurent9d91ad52009-07-17 12:17:14 -0700735void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700736{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700737 // keep a strong ref on ourself so that we want get
738 // destroyed in the middle of requestExitAndWait()
739 sp <ThreadBase> strongMe = this;
740
741 LOGV("ThreadBase::exit");
742 {
743 AutoMutex lock(&mLock);
744 requestExit();
745 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700746 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700747 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700748}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700749
750uint32_t AudioFlinger::ThreadBase::sampleRate() const
751{
752 return mSampleRate;
753}
754
755int AudioFlinger::ThreadBase::channelCount() const
756{
757 return mChannelCount;
758}
759
760int AudioFlinger::ThreadBase::format() const
761{
762 return mFormat;
763}
764
765size_t AudioFlinger::ThreadBase::frameCount() const
766{
767 return mFrameCount;
768}
769
770status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
771{
Eric Laurent3464c012009-08-04 09:45:33 -0700772 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700773
Eric Laurent3464c012009-08-04 09:45:33 -0700774 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700775 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700776
Eric Laurent3464c012009-08-04 09:45:33 -0700777 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700778 mWaitWorkCV.signal();
779 mParamCond.wait(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700780 status = mParamStatus;
781 mWaitWorkCV.signal();
782 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700783}
784
785void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
786{
787 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700788 sendConfigEvent_l(event, param);
789}
790
791// sendConfigEvent_l() must be called with ThreadBase::mLock held
792void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
793{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700794 ConfigEvent *configEvent = new ConfigEvent();
795 configEvent->mEvent = event;
796 configEvent->mParam = param;
797 mConfigEvents.add(configEvent);
798 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
799 mWaitWorkCV.signal();
800}
801
802void AudioFlinger::ThreadBase::processConfigEvents()
803{
804 mLock.lock();
805 while(!mConfigEvents.isEmpty()) {
806 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
807 ConfigEvent *configEvent = mConfigEvents[0];
808 mConfigEvents.removeAt(0);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700809 // release mLock because audioConfigChanged() will lock AudioFlinger mLock
810 // before calling Audioflinger::audioConfigChanged_l() thus creating
Eric Laurent9d91ad52009-07-17 12:17:14 -0700811 // potential cross deadlock between AudioFlinger::mLock and mLock
812 mLock.unlock();
813 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
814 delete configEvent;
815 mLock.lock();
816 }
817 mLock.unlock();
818}
819
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800820
821// ----------------------------------------------------------------------------
822
Eric Laurent9d91ad52009-07-17 12:17:14 -0700823AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
824 : ThreadBase(audioFlinger),
Eric Laurentf9df2492009-08-06 08:49:39 -0700825 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700826 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800827{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700828 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800829
Eric Laurent9d91ad52009-07-17 12:17:14 -0700830 mMasterVolume = mAudioFlinger->masterVolume();
831 mMasterMute = mAudioFlinger->masterMute();
832
833 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
834 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
835 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800836 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700837 // notify client processes that a new input has been opened
838 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800839}
840
Eric Laurent9d91ad52009-07-17 12:17:14 -0700841AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800842{
843 delete [] mMixBuffer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800844}
845
Eric Laurent9d91ad52009-07-17 12:17:14 -0700846status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800847{
848 dumpInternals(fd, args);
849 dumpTracks(fd, args);
850 return NO_ERROR;
851}
852
Eric Laurent9d91ad52009-07-17 12:17:14 -0700853status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854{
855 const size_t SIZE = 256;
856 char buffer[SIZE];
857 String8 result;
858
Eric Laurent9d91ad52009-07-17 12:17:14 -0700859 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800860 result.append(buffer);
861 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
862 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700863 sp<Track> track = mTracks[i];
864 if (track != 0) {
865 track->dump(buffer, SIZE);
866 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800867 }
868 }
869
Eric Laurent9d91ad52009-07-17 12:17:14 -0700870 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800871 result.append(buffer);
872 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
873 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700874 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800875 if (wTrack != 0) {
876 sp<Track> track = wTrack.promote();
877 if (track != 0) {
878 track->dump(buffer, SIZE);
879 result.append(buffer);
880 }
881 }
882 }
883 write(fd, result.string(), result.size());
884 return NO_ERROR;
885}
886
Eric Laurent9d91ad52009-07-17 12:17:14 -0700887status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800888{
889 const size_t SIZE = 256;
890 char buffer[SIZE];
891 String8 result;
892
Eric Laurent9d91ad52009-07-17 12:17:14 -0700893 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800894 result.append(buffer);
895 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
896 result.append(buffer);
897 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
898 result.append(buffer);
899 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
900 result.append(buffer);
901 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
902 result.append(buffer);
903 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
904 result.append(buffer);
905 write(fd, result.string(), result.size());
906 return NO_ERROR;
907}
908
909// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700910status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800911{
912 if (mSampleRate == 0) {
913 LOGE("No working audio driver found.");
914 return NO_INIT;
915 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700916 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800917 return NO_ERROR;
918}
919
Eric Laurent9d91ad52009-07-17 12:17:14 -0700920void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800921{
922 const size_t SIZE = 256;
923 char buffer[SIZE];
924
Eric Laurent9d91ad52009-07-17 12:17:14 -0700925 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800926
927 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
928}
929
Eric Laurent9d91ad52009-07-17 12:17:14 -0700930// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
931sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800932 const sp<AudioFlinger::Client>& client,
933 int streamType,
934 uint32_t sampleRate,
935 int format,
936 int channelCount,
937 int frameCount,
938 const sp<IMemory>& sharedBuffer,
939 status_t *status)
940{
941 sp<Track> track;
942 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700943
944 if (mType == DIRECT) {
945 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
946 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
947 sampleRate, format, channelCount, mOutput);
948 lStatus = BAD_VALUE;
949 goto Exit;
950 }
951 } else {
952 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
953 if (sampleRate > mSampleRate*2) {
954 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
955 lStatus = BAD_VALUE;
956 goto Exit;
957 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800958 }
959
Eric Laurent9d91ad52009-07-17 12:17:14 -0700960 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700961 LOGE("Audio driver not initialized.");
962 lStatus = NO_INIT;
963 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800964 }
965
Eric Laurent9d91ad52009-07-17 12:17:14 -0700966 { // scope for mLock
967 Mutex::Autolock _l(mLock);
968 track = new Track(this, client, streamType, sampleRate, format,
969 channelCount, frameCount, sharedBuffer);
970 if (track->getCblk() == NULL) {
971 lStatus = NO_MEMORY;
972 goto Exit;
973 }
974 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700975 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700976 lStatus = NO_ERROR;
977
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800978Exit:
979 if(status) {
980 *status = lStatus;
981 }
982 return track;
983}
984
Eric Laurent9d91ad52009-07-17 12:17:14 -0700985uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800986{
987 if (mOutput) {
988 return mOutput->latency();
989 }
990 else {
991 return 0;
992 }
993}
994
Eric Laurent9d91ad52009-07-17 12:17:14 -0700995status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800996{
997 mMasterVolume = value;
998 return NO_ERROR;
999}
1000
Eric Laurent9d91ad52009-07-17 12:17:14 -07001001status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001002{
1003 mMasterMute = muted;
1004 return NO_ERROR;
1005}
1006
Eric Laurent9d91ad52009-07-17 12:17:14 -07001007float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001008{
1009 return mMasterVolume;
1010}
1011
Eric Laurent9d91ad52009-07-17 12:17:14 -07001012bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013{
1014 return mMasterMute;
1015}
1016
Eric Laurent9d91ad52009-07-17 12:17:14 -07001017status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001018{
1019 mStreamTypes[stream].volume = value;
1020 return NO_ERROR;
1021}
1022
Eric Laurent9d91ad52009-07-17 12:17:14 -07001023status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001024{
1025 mStreamTypes[stream].mute = muted;
1026 return NO_ERROR;
1027}
1028
Eric Laurent9d91ad52009-07-17 12:17:14 -07001029float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001030{
1031 return mStreamTypes[stream].volume;
1032}
1033
Eric Laurent9d91ad52009-07-17 12:17:14 -07001034bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001035{
1036 return mStreamTypes[stream].mute;
1037}
1038
Eric Laurent9d91ad52009-07-17 12:17:14 -07001039bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001040{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001041 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001042 size_t count = mActiveTracks.size();
1043 for (size_t i = 0 ; i < count ; ++i) {
1044 sp<Track> t = mActiveTracks[i].promote();
1045 if (t == 0) continue;
1046 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001047 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048 return true;
1049 }
1050 return false;
1051}
1052
Eric Laurent9d91ad52009-07-17 12:17:14 -07001053// addTrack_l() must be called with ThreadBase::mLock held
1054status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001055{
1056 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001057
1058 // here the track could be either new, or restarted
1059 // in both cases "unstop" the track
1060 if (track->isPaused()) {
1061 track->mState = TrackBase::RESUMING;
1062 LOGV("PAUSED => RESUMING (%d)", track->name());
1063 } else {
1064 track->mState = TrackBase::ACTIVE;
1065 LOGV("? => ACTIVE (%d)", track->name());
1066 }
1067 // set retry count for buffer fill
1068 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001069 if (mActiveTracks.indexOf(track) < 0) {
1070 // the track is newly added, make sure it fills up all its
1071 // buffers before playing. This is to ensure the client will
1072 // effectively get the latency it requested.
1073 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001074 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001075 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001076 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001077 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001079 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001080 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001081
1082 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001083}
1084
Eric Laurent9d91ad52009-07-17 12:17:14 -07001085// destroyTrack_l() must be called with ThreadBase::mLock held
1086void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001087{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001088 track->mState = TrackBase::TERMINATED;
1089 if (mActiveTracks.indexOf(track) < 0) {
1090 LOGV("remove track (%d) and delete from mixer", track->name());
1091 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001092 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001093 }
1094}
1095
Eric Laurent9d91ad52009-07-17 12:17:14 -07001096String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001097{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001098 return mOutput->getParameters(keys);
1099}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001100
Eric Laurent9d91ad52009-07-17 12:17:14 -07001101void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1102 AudioSystem::OutputDescriptor desc;
1103 void *param2 = 0;
1104
1105 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1106
1107 switch (event) {
1108 case AudioSystem::OUTPUT_OPENED:
1109 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1110 desc.channels = mChannelCount;
1111 desc.samplingRate = mSampleRate;
1112 desc.format = mFormat;
1113 desc.frameCount = mFrameCount;
1114 desc.latency = latency();
1115 param2 = &desc;
1116 break;
1117
1118 case AudioSystem::STREAM_CONFIG_CHANGED:
1119 param2 = &param;
1120 case AudioSystem::OUTPUT_CLOSED:
1121 default:
1122 break;
1123 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07001124 Mutex::Autolock _l(mAudioFlinger->mLock);
1125 mAudioFlinger->audioConfigChanged_l(event, this, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001126}
1127
1128void AudioFlinger::PlaybackThread::readOutputParameters()
1129{
1130 mSampleRate = mOutput->sampleRate();
1131 mChannelCount = AudioSystem::popCount(mOutput->channels());
1132
1133 mFormat = mOutput->format();
1134 mFrameSize = mOutput->frameSize();
1135 mFrameCount = mOutput->bufferSize() / mFrameSize;
1136
1137 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1138 // FIXME - Current mixer implementation only supports stereo output: Always
1139 // Allocate a stereo buffer even if HW output is mono.
1140 if (mMixBuffer != NULL) delete mMixBuffer;
1141 mMixBuffer = new int16_t[mFrameCount * 2];
1142 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1143}
1144
1145// ----------------------------------------------------------------------------
1146
1147AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1148 : PlaybackThread(audioFlinger, output),
1149 mAudioMixer(0)
1150{
1151 mType = PlaybackThread::MIXER;
1152 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1153
1154 // FIXME - Current mixer implementation only supports stereo output
1155 if (mChannelCount == 1) {
1156 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001157 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001158}
1159
Eric Laurent9d91ad52009-07-17 12:17:14 -07001160AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001161{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001162 delete mAudioMixer;
1163}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001164
Eric Laurent9d91ad52009-07-17 12:17:14 -07001165bool AudioFlinger::MixerThread::threadLoop()
1166{
Eric Laurent3522c802009-09-07 08:38:38 -07001167 unsigned long sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001168 int16_t* curBuf = mMixBuffer;
1169 Vector< sp<Track> > tracksToRemove;
1170 size_t enabledTracks = 0;
1171 nsecs_t standbyTime = systemTime();
1172 size_t mixBufferSize = mFrameCount * mFrameSize;
1173 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001174
Eric Laurent9d91ad52009-07-17 12:17:14 -07001175 while (!exitPending())
1176 {
1177 processConfigEvents();
1178
1179 enabledTracks = 0;
1180 { // scope for mLock
1181
1182 Mutex::Autolock _l(mLock);
1183
1184 if (checkForNewParameters_l()) {
1185 mixBufferSize = mFrameCount * mFrameSize;
1186 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1187 }
1188
1189 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1190
1191 // put audio hardware into standby after short delay
1192 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1193 mSuspended) {
1194 if (!mStandby) {
1195 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1196 mOutput->standby();
1197 mStandby = true;
1198 mBytesWritten = 0;
1199 }
1200
1201 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1202 // we're about to wait, flush the binder command buffer
1203 IPCThreadState::self()->flushCommands();
1204
1205 if (exitPending()) break;
1206
1207 // wait until we have something to do...
1208 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1209 mWaitWorkCV.wait(mLock);
1210 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1211
1212 if (mMasterMute == false) {
1213 char value[PROPERTY_VALUE_MAX];
1214 property_get("ro.audio.silent", value, "0");
1215 if (atoi(value)) {
1216 LOGD("Silence is golden");
1217 setMasterMute(true);
1218 }
1219 }
1220
1221 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001222 sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001223 continue;
1224 }
1225 }
1226
1227 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1228 }
1229
Eric Laurentaef692f2009-09-22 00:35:48 -07001230 if (LIKELY(enabledTracks)) {
1231 // mix buffers...
1232 mAudioMixer->process(curBuf);
1233 sleepTime = 0;
1234 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001235 } else {
Eric Laurentaef692f2009-09-22 00:35:48 -07001236 sleepTime += kBufferRecoveryInUsecs;
1237 if (sleepTime > kMaxBufferRecoveryInUsecs) {
1238 sleepTime = kMaxBufferRecoveryInUsecs;
1239 }
1240 // There was nothing to mix this round, which means all
1241 // active tracks were late. Sleep a little bit to give
1242 // them another chance. If we're too late, write 0s to audio
1243 // hardware to avoid underrun.
1244 if (mBytesWritten != 0 && sleepTime >= kMaxBufferRecoveryInUsecs) {
1245 memset (curBuf, 0, mixBufferSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001246 sleepTime = 0;
Eric Laurent3522c802009-09-07 08:38:38 -07001247 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001248 }
1249
1250 if (mSuspended) {
1251 sleepTime = kMaxBufferRecoveryInUsecs;
1252 }
1253 // sleepTime == 0 means we must write to audio hardware
1254 if (sleepTime == 0) {
1255 mLastWriteTime = systemTime();
1256 mInWrite = true;
1257 LOGV("mOutput->write() thread %p frames %d", this, mFrameCount);
1258 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1259 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1260 mNumWrites++;
1261 mInWrite = false;
1262 mStandby = false;
1263 nsecs_t delta = systemTime() - mLastWriteTime;
1264 if (delta > maxPeriod) {
1265 LOGW("write blocked for %llu msecs, thread %p", ns2ms(delta), this);
1266 mNumDelayedWrites++;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001267 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001268 } else {
1269 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001270 }
1271
1272 // finally let go of all our tracks, without the lock held
1273 // since we can't guarantee the destructors won't acquire that
1274 // same lock.
1275 tracksToRemove.clear();
1276 }
1277
1278 if (!mStandby) {
1279 mOutput->standby();
1280 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001281
1282 LOGV("MixerThread %p exiting", this);
1283 return false;
1284}
1285
1286// prepareTracks_l() must be called with ThreadBase::mLock held
1287size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1288{
1289
1290 size_t enabledTracks = 0;
1291 // find out which tracks need to be processed
1292 size_t count = activeTracks.size();
1293 for (size_t i=0 ; i<count ; i++) {
1294 sp<Track> t = activeTracks[i].promote();
1295 if (t == 0) continue;
1296
1297 Track* const track = t.get();
1298 audio_track_cblk_t* cblk = track->cblk();
1299
1300 // The first time a track is added we wait
1301 // for all its buffers to be filled before processing it
1302 mAudioMixer->setActiveTrack(track->name());
1303 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1304 !track->isPaused())
1305 {
1306 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1307
1308 // compute volume for this track
1309 int16_t left, right;
1310 if (track->isMuted() || mMasterMute || track->isPausing() ||
1311 mStreamTypes[track->type()].mute) {
1312 left = right = 0;
1313 if (track->isPausing()) {
1314 track->setPaused();
1315 }
1316 } else {
1317 float typeVolume = mStreamTypes[track->type()].volume;
1318 float v = mMasterVolume * typeVolume;
1319 float v_clamped = v * cblk->volume[0];
1320 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1321 left = int16_t(v_clamped);
1322 v_clamped = v * cblk->volume[1];
1323 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1324 right = int16_t(v_clamped);
1325 }
1326
1327 // XXX: these things DON'T need to be done each time
1328 mAudioMixer->setBufferProvider(track);
1329 mAudioMixer->enable(AudioMixer::MIXING);
1330
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001331 int param = AudioMixer::VOLUME;
1332 if (track->mFillingUpStatus == Track::FS_FILLED) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001333 // no ramp for the first volume setting
1334 track->mFillingUpStatus = Track::FS_ACTIVE;
1335 if (track->mState == TrackBase::RESUMING) {
1336 track->mState = TrackBase::ACTIVE;
1337 param = AudioMixer::RAMP_VOLUME;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001338 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001339 } else if (cblk->server != 0) {
1340 // If the track is stopped before the first frame was mixed,
1341 // do not apply ramp
Eric Laurent9d91ad52009-07-17 12:17:14 -07001342 param = AudioMixer::RAMP_VOLUME;
1343 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001344
Eric Laurent9d91ad52009-07-17 12:17:14 -07001345 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1346 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1347 mAudioMixer->setParameter(
1348 AudioMixer::TRACK,
1349 AudioMixer::FORMAT, track->format());
1350 mAudioMixer->setParameter(
1351 AudioMixer::TRACK,
1352 AudioMixer::CHANNEL_COUNT, track->channelCount());
1353 mAudioMixer->setParameter(
1354 AudioMixer::RESAMPLE,
1355 AudioMixer::SAMPLE_RATE,
1356 int(cblk->sampleRate));
1357
1358 // reset retry count
1359 track->mRetryCount = kMaxTrackRetries;
1360 enabledTracks++;
1361 } else {
1362 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1363 if (track->isStopped()) {
1364 track->reset();
1365 }
1366 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1367 // We have consumed all the buffers of this track.
1368 // Remove it from the list of active tracks.
1369 tracksToRemove->add(track);
1370 mAudioMixer->disable(AudioMixer::MIXING);
1371 } else {
1372 // No buffers for this track. Give it a few chances to
1373 // fill a buffer, then remove it from active list.
1374 if (--(track->mRetryCount) <= 0) {
1375 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1376 tracksToRemove->add(track);
1377 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001378 // For tracks using static shared memory buffer, make sure that we have
Eric Laurent9d91ad52009-07-17 12:17:14 -07001379 // written enough data to audio hardware before disabling the track
1380 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1381 // don't care about code removing track from active list above.
1382 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1383 mAudioMixer->disable(AudioMixer::MIXING);
1384 } else {
1385 enabledTracks++;
1386 }
1387 }
1388 }
1389 }
1390
1391 // remove all the tracks that need to be...
1392 count = tracksToRemove->size();
1393 if (UNLIKELY(count)) {
1394 for (size_t i=0 ; i<count ; i++) {
1395 const sp<Track>& track = tracksToRemove->itemAt(i);
1396 mActiveTracks.remove(track);
1397 if (track->isTerminated()) {
1398 mTracks.remove(track);
1399 deleteTrackName_l(track->mName);
1400 }
1401 }
1402 }
1403
1404 return enabledTracks;
1405}
1406
1407void AudioFlinger::MixerThread::getTracks(
1408 SortedVector < sp<Track> >& tracks,
1409 SortedVector < wp<Track> >& activeTracks,
1410 int streamType)
1411{
1412 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1413 Mutex::Autolock _l(mLock);
1414 size_t size = mTracks.size();
1415 for (size_t i = 0; i < size; i++) {
1416 sp<Track> t = mTracks[i];
1417 if (t->type() == streamType) {
1418 tracks.add(t);
1419 int j = mActiveTracks.indexOf(t);
1420 if (j >= 0) {
1421 t = mActiveTracks[j].promote();
1422 if (t != NULL) {
1423 activeTracks.add(t);
1424 }
1425 }
1426 }
1427 }
1428
1429 size = activeTracks.size();
1430 for (size_t i = 0; i < size; i++) {
1431 mActiveTracks.remove(activeTracks[i]);
1432 }
1433
1434 size = tracks.size();
1435 for (size_t i = 0; i < size; i++) {
1436 sp<Track> t = tracks[i];
1437 mTracks.remove(t);
1438 deleteTrackName_l(t->name());
1439 }
1440}
1441
1442void AudioFlinger::MixerThread::putTracks(
1443 SortedVector < sp<Track> >& tracks,
1444 SortedVector < wp<Track> >& activeTracks)
1445{
1446 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1447 Mutex::Autolock _l(mLock);
1448 size_t size = tracks.size();
1449 for (size_t i = 0; i < size ; i++) {
1450 sp<Track> t = tracks[i];
1451 int name = getTrackName_l();
1452
1453 if (name < 0) return;
1454
1455 t->mName = name;
1456 t->mThread = this;
1457 mTracks.add(t);
1458
1459 int j = activeTracks.indexOf(t);
1460 if (j >= 0) {
1461 mActiveTracks.add(t);
Eric Laurent06437712009-09-01 05:56:26 -07001462 // force buffer refilling and no ramp volume when the track is mixed for the first time
1463 t->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001464 }
1465 }
1466}
1467
Eric Laurent9d91ad52009-07-17 12:17:14 -07001468// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001469int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001470{
1471 return mAudioMixer->getTrackName();
1472}
1473
Eric Laurent9d91ad52009-07-17 12:17:14 -07001474// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001475void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001476{
1477 mAudioMixer->deleteTrackName(name);
1478}
1479
Eric Laurent9d91ad52009-07-17 12:17:14 -07001480// checkForNewParameters_l() must be called with ThreadBase::mLock held
1481bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001482{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001483 bool reconfig = false;
1484
Eric Laurent3464c012009-08-04 09:45:33 -07001485 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001486 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001487 String8 keyValuePair = mNewParameters[0];
1488 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001489 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001490
1491 mNewParameters.removeAt(0);
1492
Eric Laurent9d91ad52009-07-17 12:17:14 -07001493 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1494 reconfig = true;
1495 }
1496 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1497 if (value != AudioSystem::PCM_16_BIT) {
1498 status = BAD_VALUE;
1499 } else {
1500 reconfig = true;
1501 }
1502 }
1503 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1504 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1505 status = BAD_VALUE;
1506 } else {
1507 reconfig = true;
1508 }
1509 }
1510 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1511 // do not accept frame count changes if tracks are open as the track buffer
1512 // size depends on frame count and correct behavior would not be garantied
1513 // if frame count is changed after track creation
1514 if (!mTracks.isEmpty()) {
1515 status = INVALID_OPERATION;
1516 } else {
1517 reconfig = true;
1518 }
1519 }
1520 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001521 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001522 if (!mStandby && status == INVALID_OPERATION) {
1523 mOutput->standby();
1524 mStandby = true;
1525 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001526 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001527 }
1528 if (status == NO_ERROR && reconfig) {
1529 delete mAudioMixer;
1530 readOutputParameters();
1531 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1532 for (size_t i = 0; i < mTracks.size() ; i++) {
1533 int name = getTrackName_l();
1534 if (name < 0) break;
1535 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001536 // limit track sample rate to 2 x new output sample rate
1537 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1538 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1539 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001540 }
Eric Laurent3464c012009-08-04 09:45:33 -07001541 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001542 }
1543 }
1544 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001545 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001546 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001547 }
1548 return reconfig;
1549}
1550
1551status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1552{
1553 const size_t SIZE = 256;
1554 char buffer[SIZE];
1555 String8 result;
1556
1557 PlaybackThread::dumpInternals(fd, args);
1558
1559 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1560 result.append(buffer);
1561 write(fd, result.string(), result.size());
1562 return NO_ERROR;
1563}
1564
1565// ----------------------------------------------------------------------------
1566AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1567 : PlaybackThread(audioFlinger, output),
1568 mLeftVolume (1.0), mRightVolume(1.0)
1569{
1570 mType = PlaybackThread::DIRECT;
1571}
1572
1573AudioFlinger::DirectOutputThread::~DirectOutputThread()
1574{
1575}
1576
1577
1578bool AudioFlinger::DirectOutputThread::threadLoop()
1579{
Eric Laurent3522c802009-09-07 08:38:38 -07001580 unsigned long sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001581 sp<Track> trackToRemove;
1582 sp<Track> activeTrack;
1583 nsecs_t standbyTime = systemTime();
1584 int8_t *curBuf;
1585 size_t mixBufferSize = mFrameCount*mFrameSize;
1586
1587 while (!exitPending())
1588 {
1589 processConfigEvents();
1590
1591 { // scope for the mLock
1592
1593 Mutex::Autolock _l(mLock);
1594
1595 if (checkForNewParameters_l()) {
1596 mixBufferSize = mFrameCount*mFrameSize;
1597 }
1598
1599 // put audio hardware into standby after short delay
1600 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1601 mSuspended) {
1602 // wait until we have something to do...
1603 if (!mStandby) {
1604 LOGV("Audio hardware entering standby, mixer %p\n", this);
1605 mOutput->standby();
1606 mStandby = true;
1607 mBytesWritten = 0;
1608 }
1609
1610 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1611 // we're about to wait, flush the binder command buffer
1612 IPCThreadState::self()->flushCommands();
1613
1614 if (exitPending()) break;
1615
1616 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1617 mWaitWorkCV.wait(mLock);
1618 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1619
1620 if (mMasterMute == false) {
1621 char value[PROPERTY_VALUE_MAX];
1622 property_get("ro.audio.silent", value, "0");
1623 if (atoi(value)) {
1624 LOGD("Silence is golden");
1625 setMasterMute(true);
1626 }
1627 }
1628
1629 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001630 sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001631 continue;
1632 }
1633 }
1634
1635 // find out which tracks need to be processed
1636 if (mActiveTracks.size() != 0) {
1637 sp<Track> t = mActiveTracks[0].promote();
1638 if (t == 0) continue;
1639
1640 Track* const track = t.get();
1641 audio_track_cblk_t* cblk = track->cblk();
1642
1643 // The first time a track is added we wait
1644 // for all its buffers to be filled before processing it
1645 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1646 !track->isPaused())
1647 {
1648 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1649
1650 // compute volume for this track
1651 float left, right;
1652 if (track->isMuted() || mMasterMute || track->isPausing() ||
1653 mStreamTypes[track->type()].mute) {
1654 left = right = 0;
1655 if (track->isPausing()) {
1656 track->setPaused();
1657 }
1658 } else {
1659 float typeVolume = mStreamTypes[track->type()].volume;
1660 float v = mMasterVolume * typeVolume;
1661 float v_clamped = v * cblk->volume[0];
1662 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1663 left = v_clamped/MAX_GAIN;
1664 v_clamped = v * cblk->volume[1];
1665 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1666 right = v_clamped/MAX_GAIN;
1667 }
1668
1669 if (left != mLeftVolume || right != mRightVolume) {
1670 mOutput->setVolume(left, right);
1671 left = mLeftVolume;
1672 right = mRightVolume;
1673 }
1674
1675 if (track->mFillingUpStatus == Track::FS_FILLED) {
1676 track->mFillingUpStatus = Track::FS_ACTIVE;
1677 if (track->mState == TrackBase::RESUMING) {
1678 track->mState = TrackBase::ACTIVE;
1679 }
1680 }
1681
1682 // reset retry count
1683 track->mRetryCount = kMaxTrackRetries;
1684 activeTrack = t;
1685 } else {
1686 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1687 if (track->isStopped()) {
1688 track->reset();
1689 }
1690 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1691 // We have consumed all the buffers of this track.
1692 // Remove it from the list of active tracks.
1693 trackToRemove = track;
1694 } else {
1695 // No buffers for this track. Give it a few chances to
1696 // fill a buffer, then remove it from active list.
1697 if (--(track->mRetryCount) <= 0) {
1698 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1699 trackToRemove = track;
1700 }
1701
1702 // For tracks using static shared memry buffer, make sure that we have
1703 // written enough data to audio hardware before disabling the track
1704 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1705 // don't care about code removing track from active list above.
1706 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1707 activeTrack = t;
1708 }
1709 }
1710 }
1711 }
1712
1713 // remove all the tracks that need to be...
1714 if (UNLIKELY(trackToRemove != 0)) {
1715 mActiveTracks.remove(trackToRemove);
1716 if (trackToRemove->isTerminated()) {
1717 mTracks.remove(trackToRemove);
1718 deleteTrackName_l(trackToRemove->mName);
1719 }
1720 }
1721 }
1722
Eric Laurentaef692f2009-09-22 00:35:48 -07001723 if (activeTrack != 0) {
1724 AudioBufferProvider::Buffer buffer;
1725 size_t frameCount = mFrameCount;
1726 curBuf = (int8_t *)mMixBuffer;
1727 // output audio to hardware
1728 while(frameCount) {
1729 buffer.frameCount = frameCount;
1730 activeTrack->getNextBuffer(&buffer);
1731 if (UNLIKELY(buffer.raw == 0)) {
1732 memset(curBuf, 0, frameCount * mFrameSize);
1733 break;
1734 }
1735 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1736 frameCount -= buffer.frameCount;
1737 curBuf += buffer.frameCount * mFrameSize;
1738 activeTrack->releaseBuffer(&buffer);
1739 }
1740 sleepTime = 0;
1741 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001742 } else {
Eric Laurentaef692f2009-09-22 00:35:48 -07001743 sleepTime += kBufferRecoveryInUsecs;
1744 if (sleepTime > kMaxBufferRecoveryInUsecs) {
1745 sleepTime = kMaxBufferRecoveryInUsecs;
1746 }
1747 // There was nothing to mix this round, which means all
1748 // active tracks were late. Sleep a little bit to give
1749 // them another chance. If we're too late, write 0s to audio
1750 // hardware to avoid underrun.
1751 if (mBytesWritten != 0 && sleepTime >= kMaxBufferRecoveryInUsecs &&
1752 AudioSystem::isLinearPCM(mFormat)) {
1753 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001754 sleepTime = 0;
Eric Laurent3522c802009-09-07 08:38:38 -07001755 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001756 }
Eric Laurent3522c802009-09-07 08:38:38 -07001757
Eric Laurentaef692f2009-09-22 00:35:48 -07001758 if (mSuspended) {
1759 sleepTime = kMaxBufferRecoveryInUsecs;
1760 }
1761 // sleepTime == 0 means we must write to audio hardware
1762 if (sleepTime == 0) {
1763 mLastWriteTime = systemTime();
1764 mInWrite = true;
1765 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1766 if (bytesWritten) mBytesWritten += bytesWritten;
1767 mNumWrites++;
1768 mInWrite = false;
1769 mStandby = false;
1770 } else {
1771 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001772 }
1773
1774 // finally let go of removed track, without the lock held
1775 // since we can't guarantee the destructors won't acquire that
1776 // same lock.
1777 trackToRemove.clear();
1778 activeTrack.clear();
1779 }
1780
1781 if (!mStandby) {
1782 mOutput->standby();
1783 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001784
1785 LOGV("DirectOutputThread %p exiting", this);
1786 return false;
1787}
1788
1789// getTrackName_l() must be called with ThreadBase::mLock held
1790int AudioFlinger::DirectOutputThread::getTrackName_l()
1791{
1792 return 0;
1793}
1794
1795// deleteTrackName_l() must be called with ThreadBase::mLock held
1796void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1797{
1798}
1799
1800// checkForNewParameters_l() must be called with ThreadBase::mLock held
1801bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1802{
1803 bool reconfig = false;
1804
Eric Laurent3464c012009-08-04 09:45:33 -07001805 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001806 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001807 String8 keyValuePair = mNewParameters[0];
1808 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001809 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001810
1811 mNewParameters.removeAt(0);
1812
Eric Laurent9d91ad52009-07-17 12:17:14 -07001813 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1814 // do not accept frame count changes if tracks are open as the track buffer
1815 // size depends on frame count and correct behavior would not be garantied
1816 // if frame count is changed after track creation
1817 if (!mTracks.isEmpty()) {
1818 status = INVALID_OPERATION;
1819 } else {
1820 reconfig = true;
1821 }
1822 }
1823 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001824 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001825 if (!mStandby && status == INVALID_OPERATION) {
1826 mOutput->standby();
1827 mStandby = true;
1828 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001829 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001830 }
1831 if (status == NO_ERROR && reconfig) {
1832 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001833 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001834 }
1835 }
1836 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001837 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001838 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001839 }
1840 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001841}
1842
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001843// ----------------------------------------------------------------------------
1844
Eric Laurent9d91ad52009-07-17 12:17:14 -07001845AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1846 : MixerThread(audioFlinger, mainThread->getOutput())
1847{
1848 mType = PlaybackThread::DUPLICATING;
1849 addOutputTrack(mainThread);
1850}
1851
1852AudioFlinger::DuplicatingThread::~DuplicatingThread()
1853{
1854 mOutputTracks.clear();
1855}
1856
1857bool AudioFlinger::DuplicatingThread::threadLoop()
1858{
1859 unsigned long sleepTime = kBufferRecoveryInUsecs;
1860 int16_t* curBuf = mMixBuffer;
1861 Vector< sp<Track> > tracksToRemove;
1862 size_t enabledTracks = 0;
1863 nsecs_t standbyTime = systemTime();
1864 size_t mixBufferSize = mFrameCount*mFrameSize;
1865 SortedVector< sp<OutputTrack> > outputTracks;
1866
1867 while (!exitPending())
1868 {
1869 processConfigEvents();
1870
1871 enabledTracks = 0;
1872 { // scope for the mLock
1873
1874 Mutex::Autolock _l(mLock);
1875
1876 if (checkForNewParameters_l()) {
1877 mixBufferSize = mFrameCount*mFrameSize;
1878 }
1879
1880 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1881
1882 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1883 outputTracks.add(mOutputTracks[i]);
1884 }
1885
1886 // put audio hardware into standby after short delay
1887 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1888 mSuspended) {
1889 if (!mStandby) {
1890 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001891 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001892 }
1893 mStandby = true;
1894 mBytesWritten = 0;
1895 }
1896
1897 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1898 // we're about to wait, flush the binder command buffer
1899 IPCThreadState::self()->flushCommands();
1900 outputTracks.clear();
1901
1902 if (exitPending()) break;
1903
1904 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1905 mWaitWorkCV.wait(mLock);
1906 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1907 if (mMasterMute == false) {
1908 char value[PROPERTY_VALUE_MAX];
1909 property_get("ro.audio.silent", value, "0");
1910 if (atoi(value)) {
1911 LOGD("Silence is golden");
1912 setMasterMute(true);
1913 }
1914 }
1915
1916 standbyTime = systemTime() + kStandbyTimeInNsecs;
1917 sleepTime = kBufferRecoveryInUsecs;
1918 continue;
1919 }
1920 }
1921
1922 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurentaef692f2009-09-22 00:35:48 -07001923 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001924
Eric Laurent9d91ad52009-07-17 12:17:14 -07001925 if (LIKELY(enabledTracks)) {
1926 // mix buffers...
1927 mAudioMixer->process(curBuf);
Eric Laurentaef692f2009-09-22 00:35:48 -07001928 sleepTime = 0;
1929 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001930 } else {
Eric Laurentaef692f2009-09-22 00:35:48 -07001931 sleepTime += kBufferRecoveryInUsecs;
1932 if (sleepTime > kMaxBufferRecoveryInUsecs) {
1933 sleepTime = kMaxBufferRecoveryInUsecs;
1934 }
1935 // There was nothing to mix this round, which means all
1936 // active tracks were late. Sleep a little bit to give
1937 // them another chance. If we're too late, write 0s to audio
1938 // hardware to avoid underrun.
1939 if (mBytesWritten != 0 && sleepTime >= kMaxBufferRecoveryInUsecs) {
1940 memset (curBuf, 0, mixBufferSize);
1941 sleepTime = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001942 }
1943 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001944
1945 if (mSuspended) {
1946 sleepTime = kMaxBufferRecoveryInUsecs;
1947 }
1948 // sleepTime == 0 means we must write to audio hardware
1949 if (sleepTime == 0) {
1950 for (size_t i = 0; i < outputTracks.size(); i++) {
1951 outputTracks[i]->write(curBuf, mFrameCount);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001952 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001953 mStandby = false;
1954 mBytesWritten += mixBufferSize;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001955 } else {
Eric Laurentaef692f2009-09-22 00:35:48 -07001956 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001957 }
1958
1959 // finally let go of all our tracks, without the lock held
1960 // since we can't guarantee the destructors won't acquire that
1961 // same lock.
1962 tracksToRemove.clear();
1963 outputTracks.clear();
1964 }
1965
Eric Laurentf5aba822009-08-10 23:22:32 -07001966 { // scope for the mLock
1967
1968 Mutex::Autolock _l(mLock);
1969 if (!mStandby) {
1970 LOGV("DuplicatingThread() exiting out of standby");
1971 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1972 mOutputTracks[i]->destroy();
1973 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001974 }
1975 }
1976
Eric Laurent9d91ad52009-07-17 12:17:14 -07001977 return false;
1978}
1979
1980void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1981{
1982 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1983 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1984 mSampleRate,
1985 mFormat,
1986 mChannelCount,
1987 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07001988 if (outputTrack->cblk() != NULL) {
1989 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1990 mOutputTracks.add(outputTrack);
1991 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1992 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001993}
1994
1995void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1996{
1997 Mutex::Autolock _l(mLock);
1998 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1999 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07002000 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002001 mOutputTracks.removeAt(i);
2002 return;
2003 }
2004 }
2005 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2006}
2007
2008
2009// ----------------------------------------------------------------------------
2010
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002011// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002012AudioFlinger::ThreadBase::TrackBase::TrackBase(
2013 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002014 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002015 uint32_t sampleRate,
2016 int format,
2017 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002018 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002019 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002020 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002021 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002022 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002023 mClient(client),
Eric Laurent6ad8c642009-09-09 05:16:08 -07002024 mCblk(0),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002025 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002026 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002027 mClientTid(-1),
2028 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002029 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002030{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002031 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2032
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002033 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002034 size_t size = sizeof(audio_track_cblk_t);
2035 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2036 if (sharedBuffer == 0) {
2037 size += bufferSize;
2038 }
2039
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040 if (client != NULL) {
2041 mCblkMemory = client->heap()->allocate(size);
2042 if (mCblkMemory != 0) {
2043 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2044 if (mCblk) { // construct the shared structure in-place.
2045 new(mCblk) audio_track_cblk_t();
2046 // clear all buffers
2047 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002048 mCblk->sampleRate = sampleRate;
2049 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050 if (sharedBuffer == 0) {
2051 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2052 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2053 // Force underrun condition to avoid false underrun callback until first data is
2054 // written to buffer
2055 mCblk->flowControlFlag = 1;
2056 } else {
2057 mBuffer = sharedBuffer->pointer();
2058 }
2059 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002060 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002061 } else {
2062 LOGE("not enough memory for AudioTrack size=%u", size);
2063 client->heap()->dump("AudioTrack");
2064 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002065 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002066 } else {
2067 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2068 if (mCblk) { // construct the shared structure in-place.
2069 new(mCblk) audio_track_cblk_t();
2070 // clear all buffers
2071 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002072 mCblk->sampleRate = sampleRate;
2073 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002074 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2075 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2076 // Force underrun condition to avoid false underrun callback until first data is
2077 // written to buffer
2078 mCblk->flowControlFlag = 1;
2079 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2080 }
2081 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002082}
2083
Eric Laurentbdc0f842009-09-16 06:02:45 -07002084AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002085{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002087 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2088 if (mClient == NULL) {
2089 delete mCblk;
2090 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002092 mCblkMemory.clear(); // and free the shared memory
Eric Laurent0f8ab672009-09-17 05:12:56 -07002093 if (mClient != NULL) {
2094 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2095 mClient.clear();
2096 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002097}
2098
Eric Laurentbdc0f842009-09-16 06:02:45 -07002099void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002100{
2101 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002102 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002103 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002104 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002105}
2106
Eric Laurentbdc0f842009-09-16 06:02:45 -07002107bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002108 bool result;
2109 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002110
2111 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002112 if (!result) {
2113 LOGV("stepServer failed acquiring cblk mutex");
2114 mFlags |= STEPSERVER_FAILED;
2115 }
2116 return result;
2117}
2118
Eric Laurentbdc0f842009-09-16 06:02:45 -07002119void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002120 audio_track_cblk_t* cblk = this->cblk();
2121
2122 cblk->user = 0;
2123 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002124 cblk->userBase = 0;
2125 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002127 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002128}
2129
Eric Laurentbdc0f842009-09-16 06:02:45 -07002130sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002131{
2132 return mCblkMemory;
2133}
2134
Eric Laurentbdc0f842009-09-16 06:02:45 -07002135int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002136 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002137}
2138
Eric Laurentbdc0f842009-09-16 06:02:45 -07002139int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002140 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002141}
2142
Eric Laurentbdc0f842009-09-16 06:02:45 -07002143void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002144 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002145 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2146 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002147
2148 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002149 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2150 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002151 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2152 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002153 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002154 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002155 return 0;
2156 }
2157
2158 return bufferStart;
2159}
2160
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002161// ----------------------------------------------------------------------------
2162
Eric Laurent9d91ad52009-07-17 12:17:14 -07002163// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2164AudioFlinger::PlaybackThread::Track::Track(
2165 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002166 const sp<Client>& client,
2167 int streamType,
2168 uint32_t sampleRate,
2169 int format,
2170 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002171 int frameCount,
2172 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002173 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2174 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002175{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002176 if (mCblk != NULL) {
2177 sp<ThreadBase> baseThread = thread.promote();
2178 if (baseThread != 0) {
2179 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2180 mName = playbackThread->getTrackName_l();
2181 }
2182 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2183 if (mName < 0) {
2184 LOGE("no more track names available");
2185 }
2186 mVolume[0] = 1.0f;
2187 mVolume[1] = 1.0f;
2188 mStreamType = streamType;
2189 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2190 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2191 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002192 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002193}
2194
Eric Laurent9d91ad52009-07-17 12:17:14 -07002195AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002196{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002197 LOGV("PlaybackThread::Track destructor");
2198 sp<ThreadBase> thread = mThread.promote();
2199 if (thread != 0) {
2200 Mutex::Autolock _l(thread->mLock);
2201 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002202 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002203}
2204
Eric Laurent9d91ad52009-07-17 12:17:14 -07002205void AudioFlinger::PlaybackThread::Track::destroy()
2206{
2207 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2208 // by removing it from mTracks vector, so there is a risk that this Tracks's
2209 // desctructor is called. As the destructor needs to lock mLock,
2210 // we must acquire a strong reference on this Track before locking mLock
2211 // here so that the destructor is called only when exiting this function.
2212 // On the other hand, as long as Track::destroy() is only called by
2213 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2214 // this Track with its member mTrack.
2215 sp<Track> keep(this);
2216 { // scope for mLock
2217 sp<ThreadBase> thread = mThread.promote();
2218 if (thread != 0) {
2219 Mutex::Autolock _l(thread->mLock);
2220 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2221 playbackThread->destroyTrack_l(this);
2222 }
2223 }
2224}
2225
2226void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002227{
2228 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2229 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002231 mStreamType,
2232 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002233 mCblk->channels,
2234 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002235 mState,
2236 mMute,
2237 mFillingUpStatus,
2238 mCblk->sampleRate,
2239 mCblk->volume[0],
2240 mCblk->volume[1],
2241 mCblk->server,
2242 mCblk->user);
2243}
2244
Eric Laurent9d91ad52009-07-17 12:17:14 -07002245status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002246{
2247 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002248 uint32_t framesReady;
2249 uint32_t framesReq = buffer->frameCount;
2250
2251 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002252 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2253 if (!step()) goto getNextBuffer_exit;
2254 LOGV("stepServer recovered");
2255 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2256 }
2257
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002258 framesReady = cblk->framesReady();
2259
2260 if (LIKELY(framesReady)) {
2261 uint32_t s = cblk->server;
2262 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2263
2264 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2265 if (framesReq > framesReady) {
2266 framesReq = framesReady;
2267 }
2268 if (s + framesReq > bufferEnd) {
2269 framesReq = bufferEnd - s;
2270 }
2271
2272 buffer->raw = getBuffer(s, framesReq);
2273 if (buffer->raw == 0) goto getNextBuffer_exit;
2274
2275 buffer->frameCount = framesReq;
2276 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002277 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002278
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002279getNextBuffer_exit:
2280 buffer->raw = 0;
2281 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002282 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002283 return NOT_ENOUGH_DATA;
2284}
2285
Eric Laurent9d91ad52009-07-17 12:17:14 -07002286bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002287 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002288
2289 if (mCblk->framesReady() >= mCblk->frameCount ||
2290 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002291 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002292 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002293 return true;
2294 }
2295 return false;
2296}
2297
Eric Laurent9d91ad52009-07-17 12:17:14 -07002298status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002299{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002300 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2301 sp<ThreadBase> thread = mThread.promote();
2302 if (thread != 0) {
2303 Mutex::Autolock _l(thread->mLock);
2304 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2305 playbackThread->addTrack_l(this);
2306 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002307 return NO_ERROR;
2308}
2309
Eric Laurent9d91ad52009-07-17 12:17:14 -07002310void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002311{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002312 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2313 sp<ThreadBase> thread = mThread.promote();
2314 if (thread != 0) {
2315 Mutex::Autolock _l(thread->mLock);
2316 if (mState > STOPPED) {
2317 mState = STOPPED;
2318 // If the track is not active (PAUSED and buffers full), flush buffers
2319 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2320 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2321 reset();
2322 }
2323 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002324 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002325 }
2326}
2327
Eric Laurent9d91ad52009-07-17 12:17:14 -07002328void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002329{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002331 sp<ThreadBase> thread = mThread.promote();
2332 if (thread != 0) {
2333 Mutex::Autolock _l(thread->mLock);
2334 if (mState == ACTIVE || mState == RESUMING) {
2335 mState = PAUSING;
2336 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2337 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002338 }
2339}
2340
Eric Laurent9d91ad52009-07-17 12:17:14 -07002341void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002342{
2343 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002344 sp<ThreadBase> thread = mThread.promote();
2345 if (thread != 0) {
2346 Mutex::Autolock _l(thread->mLock);
2347 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2348 return;
2349 }
2350 // No point remaining in PAUSED state after a flush => go to
2351 // STOPPED state
2352 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002353
Eric Laurent9d91ad52009-07-17 12:17:14 -07002354 mCblk->lock.lock();
2355 // NOTE: reset() will reset cblk->user and cblk->server with
2356 // the risk that at the same time, the AudioMixer is trying to read
2357 // data. In this case, getNextBuffer() would return a NULL pointer
2358 // as audio buffer => the AudioMixer code MUST always test that pointer
2359 // returned by getNextBuffer() is not NULL!
2360 reset();
2361 mCblk->lock.unlock();
2362 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002363}
2364
Eric Laurent9d91ad52009-07-17 12:17:14 -07002365void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002366{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002367 // Do not reset twice to avoid discarding data written just after a flush and before
2368 // the audioflinger thread detects the track is stopped.
2369 if (!mResetDone) {
2370 TrackBase::reset();
2371 // Force underrun condition to avoid false underrun callback until first data is
2372 // written to buffer
2373 mCblk->flowControlFlag = 1;
2374 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002375 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002376 mResetDone = true;
2377 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002378}
2379
Eric Laurent9d91ad52009-07-17 12:17:14 -07002380void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002381{
2382 mMute = muted;
2383}
2384
Eric Laurent9d91ad52009-07-17 12:17:14 -07002385void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002386{
2387 mVolume[0] = left;
2388 mVolume[1] = right;
2389}
2390
2391// ----------------------------------------------------------------------------
2392
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002393// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002394AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2395 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397 uint32_t sampleRate,
2398 int format,
2399 int channelCount,
2400 int frameCount,
2401 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002402 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002404 mOverflow(false)
2405{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002406 if (mCblk != NULL) {
2407 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2408 if (format == AudioSystem::PCM_16_BIT) {
2409 mCblk->frameSize = channelCount * sizeof(int16_t);
2410 } else if (format == AudioSystem::PCM_8_BIT) {
2411 mCblk->frameSize = channelCount * sizeof(int8_t);
2412 } else {
2413 mCblk->frameSize = sizeof(int8_t);
2414 }
2415 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002416}
2417
2418AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419{
2420}
2421
Eric Laurent9d91ad52009-07-17 12:17:14 -07002422status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423{
2424 audio_track_cblk_t* cblk = this->cblk();
2425 uint32_t framesAvail;
2426 uint32_t framesReq = buffer->frameCount;
2427
2428 // Check if last stepServer failed, try to step now
2429 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2430 if (!step()) goto getNextBuffer_exit;
2431 LOGV("stepServer recovered");
2432 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2433 }
2434
2435 framesAvail = cblk->framesAvailable_l();
2436
2437 if (LIKELY(framesAvail)) {
2438 uint32_t s = cblk->server;
2439 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2440
2441 if (framesReq > framesAvail) {
2442 framesReq = framesAvail;
2443 }
2444 if (s + framesReq > bufferEnd) {
2445 framesReq = bufferEnd - s;
2446 }
2447
2448 buffer->raw = getBuffer(s, framesReq);
2449 if (buffer->raw == 0) goto getNextBuffer_exit;
2450
2451 buffer->frameCount = framesReq;
2452 return NO_ERROR;
2453 }
2454
2455getNextBuffer_exit:
2456 buffer->raw = 0;
2457 buffer->frameCount = 0;
2458 return NOT_ENOUGH_DATA;
2459}
2460
Eric Laurent9d91ad52009-07-17 12:17:14 -07002461status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002463 sp<ThreadBase> thread = mThread.promote();
2464 if (thread != 0) {
2465 RecordThread *recordThread = (RecordThread *)thread.get();
2466 return recordThread->start(this);
2467 }
2468 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469}
2470
Eric Laurent9d91ad52009-07-17 12:17:14 -07002471void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002473 sp<ThreadBase> thread = mThread.promote();
2474 if (thread != 0) {
2475 RecordThread *recordThread = (RecordThread *)thread.get();
2476 recordThread->stop(this);
2477 TrackBase::reset();
2478 // Force overerrun condition to avoid false overrun callback until first data is
2479 // read from buffer
2480 mCblk->flowControlFlag = 1;
2481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482}
2483
2484
2485// ----------------------------------------------------------------------------
2486
Eric Laurent9d91ad52009-07-17 12:17:14 -07002487AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2488 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 uint32_t sampleRate,
2490 int format,
2491 int channelCount,
2492 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002493 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2494 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002496
2497 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002498 if (mCblk != NULL) {
2499 mCblk->out = 1;
2500 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2501 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2502 mOutBuffer.frameCount = 0;
2503 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2504 playbackThread->mTracks.add(this);
2505 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2506 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2507 } else {
2508 LOGW("Error creating output track on thread %p", playbackThread);
2509 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510}
2511
Eric Laurent9d91ad52009-07-17 12:17:14 -07002512AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513{
Eric Laurentf5aba822009-08-10 23:22:32 -07002514 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515}
2516
Eric Laurent9d91ad52009-07-17 12:17:14 -07002517status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518{
2519 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002520 if (status != NO_ERROR) {
2521 return status;
2522 }
2523
2524 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525 mRetryCount = 127;
2526 return status;
2527}
2528
Eric Laurent9d91ad52009-07-17 12:17:14 -07002529void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530{
2531 Track::stop();
2532 clearBufferQueue();
2533 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002534 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535}
2536
Eric Laurent9d91ad52009-07-17 12:17:14 -07002537bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538{
2539 Buffer *pInBuffer;
2540 Buffer inBuffer;
2541 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002542 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 inBuffer.frameCount = frames;
2544 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002545
2546 uint32_t waitTimeLeftMs = mWaitTimeMs;
2547
2548 if (!mActive) {
2549 start();
2550 sp<ThreadBase> thread = mThread.promote();
2551 if (thread != 0) {
2552 MixerThread *mixerThread = (MixerThread *)thread.get();
2553 if (mCblk->frameCount > frames){
2554 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2555 uint32_t startFrames = (mCblk->frameCount - frames);
2556 pInBuffer = new Buffer;
2557 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2558 pInBuffer->frameCount = startFrames;
2559 pInBuffer->i16 = pInBuffer->mBuffer;
2560 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2561 mBufferQueue.add(pInBuffer);
2562 } else {
2563 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002566 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 }
2568
Eric Laurent9d91ad52009-07-17 12:17:14 -07002569 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570 // First write pending buffers, then new data
2571 if (mBufferQueue.size()) {
2572 pInBuffer = mBufferQueue.itemAt(0);
2573 } else {
2574 pInBuffer = &inBuffer;
2575 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002576
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577 if (pInBuffer->frameCount == 0) {
2578 break;
2579 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002580
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 if (mOutBuffer.frameCount == 0) {
2582 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002583 nsecs_t startTime = systemTime();
2584 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2585 LOGV ("OutputTrack::write() %p no more output buffers", this);
2586 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 break;
2588 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002589 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2590// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2591 if (waitTimeLeftMs >= waitTimeMs) {
2592 waitTimeLeftMs -= waitTimeMs;
2593 } else {
2594 waitTimeLeftMs = 0;
2595 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002597
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2599 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2600 mCblk->stepUser(outFrames);
2601 pInBuffer->frameCount -= outFrames;
2602 pInBuffer->i16 += outFrames * channels;
2603 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002604 mOutBuffer.i16 += outFrames * channels;
2605
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606 if (pInBuffer->frameCount == 0) {
2607 if (mBufferQueue.size()) {
2608 mBufferQueue.removeAt(0);
2609 delete [] pInBuffer->mBuffer;
2610 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002611 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612 } else {
2613 break;
2614 }
2615 }
2616 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002617
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618 // If we could not write all frames, allocate a buffer and queue it for next time.
2619 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002620 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 pInBuffer = new Buffer;
2622 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2623 pInBuffer->frameCount = inBuffer.frameCount;
2624 pInBuffer->i16 = pInBuffer->mBuffer;
2625 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2626 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002627 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002629 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630 }
2631 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002632
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002634 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002635 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002636 if (frames == 0 && mBufferQueue.size() == 0) {
2637 if (mCblk->user < mCblk->frameCount) {
2638 frames = mCblk->frameCount - mCblk->user;
2639 pInBuffer = new Buffer;
2640 pInBuffer->mBuffer = new int16_t[frames * channels];
2641 pInBuffer->frameCount = frames;
2642 pInBuffer->i16 = pInBuffer->mBuffer;
2643 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2644 mBufferQueue.add(pInBuffer);
2645 } else {
2646 stop();
2647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 }
2649
Eric Laurent9d91ad52009-07-17 12:17:14 -07002650 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651}
2652
Eric Laurent9d91ad52009-07-17 12:17:14 -07002653status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654{
2655 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 status_t result;
2657 audio_track_cblk_t* cblk = mCblk;
2658 uint32_t framesReq = buffer->frameCount;
2659
Eric Laurent9d91ad52009-07-17 12:17:14 -07002660// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002662
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 uint32_t framesAvail = cblk->framesAvailable();
2664
Eric Laurent9d91ad52009-07-17 12:17:14 -07002665
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002667 Mutex::Autolock _l(cblk->lock);
2668 goto start_loop_here;
2669 while (framesAvail == 0) {
2670 active = mActive;
2671 if (UNLIKELY(!active)) {
2672 LOGV("Not active and NO_MORE_BUFFERS");
2673 return AudioTrack::NO_MORE_BUFFERS;
2674 }
2675 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2676 if (result != NO_ERROR) {
2677 return AudioTrack::NO_MORE_BUFFERS;
2678 }
2679 // read the server count again
2680 start_loop_here:
2681 framesAvail = cblk->framesAvailable_l();
2682 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683 }
2684
Eric Laurent9d91ad52009-07-17 12:17:14 -07002685// if (framesAvail < framesReq) {
2686// return AudioTrack::NO_MORE_BUFFERS;
2687// }
2688
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 if (framesReq > framesAvail) {
2690 framesReq = framesAvail;
2691 }
2692
2693 uint32_t u = cblk->user;
2694 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2695
2696 if (u + framesReq > bufferEnd) {
2697 framesReq = bufferEnd - u;
2698 }
2699
2700 buffer->frameCount = framesReq;
2701 buffer->raw = (void *)cblk->buffer(u);
2702 return NO_ERROR;
2703}
2704
2705
Eric Laurent9d91ad52009-07-17 12:17:14 -07002706void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707{
2708 size_t size = mBufferQueue.size();
2709 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711 for (size_t i = 0; i < size; i++) {
2712 pBuffer = mBufferQueue.itemAt(i);
2713 delete [] pBuffer->mBuffer;
2714 delete pBuffer;
2715 }
2716 mBufferQueue.clear();
2717}
2718
2719// ----------------------------------------------------------------------------
2720
2721AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2722 : RefBase(),
2723 mAudioFlinger(audioFlinger),
2724 mMemoryDealer(new MemoryDealer(1024*1024)),
2725 mPid(pid)
2726{
2727 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2728}
2729
Eric Laurent0f8ab672009-09-17 05:12:56 -07002730// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731AudioFlinger::Client::~Client()
2732{
Eric Laurent0f8ab672009-09-17 05:12:56 -07002733 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734}
2735
2736const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2737{
2738 return mMemoryDealer;
2739}
2740
2741// ----------------------------------------------------------------------------
2742
Eric Laurent9d91ad52009-07-17 12:17:14 -07002743AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002744 : BnAudioTrack(),
2745 mTrack(track)
2746{
2747}
2748
2749AudioFlinger::TrackHandle::~TrackHandle() {
2750 // just stop the track on deletion, associated resources
2751 // will be freed from the main thread once all pending buffers have
2752 // been played. Unless it's not in the active track list, in which
2753 // case we free everything now...
2754 mTrack->destroy();
2755}
2756
2757status_t AudioFlinger::TrackHandle::start() {
2758 return mTrack->start();
2759}
2760
2761void AudioFlinger::TrackHandle::stop() {
2762 mTrack->stop();
2763}
2764
2765void AudioFlinger::TrackHandle::flush() {
2766 mTrack->flush();
2767}
2768
2769void AudioFlinger::TrackHandle::mute(bool e) {
2770 mTrack->mute(e);
2771}
2772
2773void AudioFlinger::TrackHandle::pause() {
2774 mTrack->pause();
2775}
2776
2777void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2778 mTrack->setVolume(left, right);
2779}
2780
2781sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2782 return mTrack->getCblk();
2783}
2784
2785status_t AudioFlinger::TrackHandle::onTransact(
2786 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2787{
2788 return BnAudioTrack::onTransact(code, data, reply, flags);
2789}
2790
2791// ----------------------------------------------------------------------------
2792
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002793sp<IAudioRecord> AudioFlinger::openRecord(
2794 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002795 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002796 uint32_t sampleRate,
2797 int format,
2798 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002799 int frameCount,
2800 uint32_t flags,
2801 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002802{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002803 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002804 sp<RecordHandle> recordHandle;
2805 sp<Client> client;
2806 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002807 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002808 RecordThread *thread;
2809 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002810
2811 // check calling permissions
2812 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002813 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002814 goto Exit;
2815 }
2816
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002817 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002818 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002819 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002820 thread = checkRecordThread_l(input);
2821 if (thread == NULL) {
2822 lStatus = BAD_VALUE;
2823 goto Exit;
2824 }
2825
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002826 wclient = mClients.valueFor(pid);
2827 if (wclient != NULL) {
2828 client = wclient.promote();
2829 } else {
2830 client = new Client(this, pid);
2831 mClients.add(pid, client);
2832 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002833
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002834 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002835 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002836 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002837 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 if (recordTrack->getCblk() == NULL) {
Eric Laurent0f8ab672009-09-17 05:12:56 -07002839 // remove local strong reference to Client before deleting the RecordTrack so that the Client
2840 // destructor is called by the TrackBase destructor with mLock held
2841 client.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 recordTrack.clear();
2843 lStatus = NO_MEMORY;
2844 goto Exit;
2845 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002846
2847 // return to handle to client
2848 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002849 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002850
2851Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002852 if (status) {
2853 *status = lStatus;
2854 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002855 return recordHandle;
2856}
2857
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002858// ----------------------------------------------------------------------------
2859
Eric Laurent9d91ad52009-07-17 12:17:14 -07002860AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002861 : BnAudioRecord(),
2862 mRecordTrack(recordTrack)
2863{
2864}
2865
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002866AudioFlinger::RecordHandle::~RecordHandle() {
2867 stop();
2868}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002869
2870status_t AudioFlinger::RecordHandle::start() {
2871 LOGV("RecordHandle::start()");
2872 return mRecordTrack->start();
2873}
2874
2875void AudioFlinger::RecordHandle::stop() {
2876 LOGV("RecordHandle::stop()");
2877 mRecordTrack->stop();
2878}
2879
2880sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2881 return mRecordTrack->getCblk();
2882}
2883
2884status_t AudioFlinger::RecordHandle::onTransact(
2885 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2886{
2887 return BnAudioRecord::onTransact(code, data, reply, flags);
2888}
2889
2890// ----------------------------------------------------------------------------
2891
Eric Laurent9d91ad52009-07-17 12:17:14 -07002892AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2893 ThreadBase(audioFlinger),
2894 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002895{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002896 mReqChannelCount = AudioSystem::popCount(channels);
2897 mReqSampleRate = sampleRate;
2898 readInputParameters();
2899 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002900}
2901
Eric Laurent9d91ad52009-07-17 12:17:14 -07002902
2903AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002904{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002905 delete[] mRsmpInBuffer;
2906 if (mResampler != 0) {
2907 delete mResampler;
2908 delete[] mRsmpOutBuffer;
2909 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002910}
2911
Eric Laurent9d91ad52009-07-17 12:17:14 -07002912void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002913{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002914 const size_t SIZE = 256;
2915 char buffer[SIZE];
2916
2917 snprintf(buffer, SIZE, "Record Thread %p", this);
2918
2919 run(buffer, PRIORITY_URGENT_AUDIO);
2920}
2921bool AudioFlinger::RecordThread::threadLoop()
2922{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002923 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002924 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002925
2926 // start recording
2927 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002928
Eric Laurent9d91ad52009-07-17 12:17:14 -07002929 processConfigEvents();
2930
2931 { // scope for mLock
2932 Mutex::Autolock _l(mLock);
2933 checkForNewParameters_l();
2934 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2935 if (!mStandby) {
2936 mInput->standby();
2937 mStandby = true;
2938 }
2939
2940 if (exitPending()) break;
2941
2942 LOGV("RecordThread: loop stopping");
2943 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002944 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002945 LOGV("RecordThread: loop starting");
2946 continue;
2947 }
2948 if (mActiveTrack != 0) {
2949 if (mActiveTrack->mState == TrackBase::PAUSING) {
2950 mActiveTrack.clear();
2951 mStartStopCond.broadcast();
2952 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2953 mRsmpInIndex = mFrameCount;
2954 if (mReqChannelCount != mActiveTrack->channelCount()) {
2955 mActiveTrack.clear();
2956 } else {
Eric Laurent9e7b8192009-08-10 02:41:54 -07002957 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002958 }
2959 mStartStopCond.broadcast();
2960 }
2961 mStandby = false;
2962 }
2963 }
2964
2965 if (mActiveTrack != 0) {
2966 buffer.frameCount = mFrameCount;
2967 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2968 size_t framesOut = buffer.frameCount;
2969 if (mResampler == 0) {
2970 // no resampling
2971 while (framesOut) {
2972 size_t framesIn = mFrameCount - mRsmpInIndex;
2973 if (framesIn) {
2974 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2975 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2976 if (framesIn > framesOut)
2977 framesIn = framesOut;
2978 mRsmpInIndex += framesIn;
2979 framesOut -= framesIn;
2980 if (mChannelCount == mReqChannelCount ||
2981 mFormat != AudioSystem::PCM_16_BIT) {
2982 memcpy(dst, src, framesIn * mFrameSize);
2983 } else {
2984 int16_t *src16 = (int16_t *)src;
2985 int16_t *dst16 = (int16_t *)dst;
2986 if (mChannelCount == 1) {
2987 while (framesIn--) {
2988 *dst16++ = *src16;
2989 *dst16++ = *src16++;
2990 }
2991 } else {
2992 while (framesIn--) {
2993 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2994 src16 += 2;
2995 }
2996 }
2997 }
2998 }
2999 if (framesOut && mFrameCount == mRsmpInIndex) {
3000 ssize_t bytesRead;
3001 if (framesOut == mFrameCount &&
3002 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
3003 bytesRead = mInput->read(buffer.raw, mInputBytes);
3004 framesOut = 0;
3005 } else {
3006 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3007 mRsmpInIndex = 0;
3008 }
3009 if (bytesRead < 0) {
3010 LOGE("Error reading audio input");
3011 sleep(1);
3012 mRsmpInIndex = mFrameCount;
3013 framesOut = 0;
3014 buffer.frameCount = 0;
3015 }
3016 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003017 }
3018 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003019 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003020
Eric Laurent9d91ad52009-07-17 12:17:14 -07003021 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3022 // alter output frame count as if we were expecting stereo samples
3023 if (mChannelCount == 1 && mReqChannelCount == 1) {
3024 framesOut >>= 1;
3025 }
3026 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3027 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3028 // are 32 bit aligned which should be always true.
3029 if (mChannelCount == 2 && mReqChannelCount == 1) {
3030 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3031 // the resampler always outputs stereo samples: do post stereo to mono conversion
3032 int16_t *src = (int16_t *)mRsmpOutBuffer;
3033 int16_t *dst = buffer.i16;
3034 while (framesOut--) {
3035 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3036 src += 2;
3037 }
3038 } else {
3039 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3040 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003041
Eric Laurent9d91ad52009-07-17 12:17:14 -07003042 }
3043 mActiveTrack->releaseBuffer(&buffer);
3044 mActiveTrack->overflow();
3045 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003046 // client isn't retrieving buffers fast enough
3047 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003048 if (!mActiveTrack->setOverflow())
3049 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003050 // Release the processor for a while before asking for a new buffer.
3051 // This will give the application more chance to read from the buffer and
3052 // clear the overflow.
3053 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003054 }
3055 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003056 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003057
Eric Laurent9d91ad52009-07-17 12:17:14 -07003058 if (!mStandby) {
3059 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003060 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003061 mActiveTrack.clear();
3062
Eric Laurent9d91ad52009-07-17 12:17:14 -07003063 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003064 return false;
3065}
3066
Eric Laurent9d91ad52009-07-17 12:17:14 -07003067status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003068{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003069 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003070 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003071
Eric Laurent9d91ad52009-07-17 12:17:14 -07003072 if (mActiveTrack != 0) {
3073 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003074
Eric Laurent9d91ad52009-07-17 12:17:14 -07003075 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003076
Eric Laurent9d91ad52009-07-17 12:17:14 -07003077 return NO_ERROR;
3078 }
3079
3080 mActiveTrack = recordTrack;
3081 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003082 // signal thread to start
3083 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003084 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003085 mStartStopCond.wait(mLock);
3086 if (mActiveTrack != 0) {
3087 LOGV("Record started OK");
3088 return NO_ERROR;
3089 } else {
3090 LOGV("Record failed to start");
3091 return BAD_VALUE;
3092 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003093}
3094
Eric Laurent9d91ad52009-07-17 12:17:14 -07003095void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3096 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003097 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003098 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3099 mActiveTrack->mState = TrackBase::PAUSING;
3100 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003101 }
3102}
3103
Eric Laurent9d91ad52009-07-17 12:17:14 -07003104status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105{
3106 const size_t SIZE = 256;
3107 char buffer[SIZE];
3108 String8 result;
3109 pid_t pid = 0;
3110
Eric Laurent9d91ad52009-07-17 12:17:14 -07003111 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3112 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113 result.append(buffer);
3114 } else {
3115 result.append("No record client\n");
3116 }
3117 write(fd, result.string(), result.size());
3118 return NO_ERROR;
3119}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003120
Eric Laurent9d91ad52009-07-17 12:17:14 -07003121status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3122{
3123 size_t framesReq = buffer->frameCount;
3124 size_t framesReady = mFrameCount - mRsmpInIndex;
3125 int channelCount;
3126
3127 if (framesReady == 0) {
3128 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3129 if (bytesRead < 0) {
3130 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3131 sleep(1);
3132 buffer->raw = 0;
3133 buffer->frameCount = 0;
3134 return NOT_ENOUGH_DATA;
3135 }
3136 mRsmpInIndex = 0;
3137 framesReady = mFrameCount;
3138 }
3139
3140 if (framesReq > framesReady) {
3141 framesReq = framesReady;
3142 }
3143
3144 if (mChannelCount == 1 && mReqChannelCount == 2) {
3145 channelCount = 1;
3146 } else {
3147 channelCount = 2;
3148 }
3149 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3150 buffer->frameCount = framesReq;
3151 return NO_ERROR;
3152}
3153
3154void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3155{
3156 mRsmpInIndex += buffer->frameCount;
3157 buffer->frameCount = 0;
3158}
3159
3160bool AudioFlinger::RecordThread::checkForNewParameters_l()
3161{
3162 bool reconfig = false;
3163
Eric Laurent3464c012009-08-04 09:45:33 -07003164 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003165 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003166 String8 keyValuePair = mNewParameters[0];
3167 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003168 int value;
3169 int reqFormat = mFormat;
3170 int reqSamplingRate = mReqSampleRate;
3171 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003172
3173 mNewParameters.removeAt(0);
3174
Eric Laurent9d91ad52009-07-17 12:17:14 -07003175 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3176 reqSamplingRate = value;
3177 reconfig = true;
3178 }
3179 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3180 reqFormat = value;
3181 reconfig = true;
3182 }
3183 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3184 reqChannelCount = AudioSystem::popCount(value);
3185 reconfig = true;
3186 }
3187 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3188 // do not accept frame count changes if tracks are open as the track buffer
3189 // size depends on frame count and correct behavior would not be garantied
3190 // if frame count is changed after track creation
3191 if (mActiveTrack != 0) {
3192 status = INVALID_OPERATION;
3193 } else {
3194 reconfig = true;
3195 }
3196 }
3197 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003198 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003199 if (status == INVALID_OPERATION) {
3200 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003201 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003202 }
3203 if (reconfig) {
3204 if (status == BAD_VALUE &&
3205 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3206 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3207 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3208 status = NO_ERROR;
3209 }
3210 if (status == NO_ERROR) {
3211 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003212 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003213 }
3214 }
3215 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003216 mParamStatus = status;
3217 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003218 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003219 }
3220 return reconfig;
3221}
3222
3223String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3224{
3225 return mInput->getParameters(keys);
3226}
3227
3228void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3229 AudioSystem::OutputDescriptor desc;
3230 void *param2 = 0;
3231
3232 switch (event) {
3233 case AudioSystem::INPUT_OPENED:
3234 case AudioSystem::INPUT_CONFIG_CHANGED:
3235 desc.channels = mChannelCount;
3236 desc.samplingRate = mSampleRate;
3237 desc.format = mFormat;
3238 desc.frameCount = mFrameCount;
3239 desc.latency = 0;
3240 param2 = &desc;
3241 break;
3242
3243 case AudioSystem::INPUT_CLOSED:
3244 default:
3245 break;
3246 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003247 Mutex::Autolock _l(mAudioFlinger->mLock);
3248 mAudioFlinger->audioConfigChanged_l(event, this, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003249}
3250
3251void AudioFlinger::RecordThread::readInputParameters()
3252{
3253 if (mRsmpInBuffer) delete mRsmpInBuffer;
3254 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3255 if (mResampler) delete mResampler;
3256 mResampler = 0;
3257
3258 mSampleRate = mInput->sampleRate();
3259 mChannelCount = AudioSystem::popCount(mInput->channels());
3260 mFormat = mInput->format();
3261 mFrameSize = mInput->frameSize();
3262 mInputBytes = mInput->bufferSize();
3263 mFrameCount = mInputBytes / mFrameSize;
3264 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3265
3266 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3267 {
3268 int channelCount;
3269 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3270 // stereo to mono post process as the resampler always outputs stereo.
3271 if (mChannelCount == 1 && mReqChannelCount == 2) {
3272 channelCount = 1;
3273 } else {
3274 channelCount = 2;
3275 }
3276 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3277 mResampler->setSampleRate(mSampleRate);
3278 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3279 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3280
3281 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3282 if (mChannelCount == 1 && mReqChannelCount == 1) {
3283 mFrameCount >>= 1;
3284 }
3285
3286 }
3287 mRsmpInIndex = mFrameCount;
3288}
3289
3290// ----------------------------------------------------------------------------
3291
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003292int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003293 uint32_t *pSamplingRate,
3294 uint32_t *pFormat,
3295 uint32_t *pChannels,
3296 uint32_t *pLatencyMs,
3297 uint32_t flags)
3298{
3299 status_t status;
3300 PlaybackThread *thread = NULL;
3301 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3302 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3303 uint32_t format = pFormat ? *pFormat : 0;
3304 uint32_t channels = pChannels ? *pChannels : 0;
3305 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3306
3307 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3308 pDevices ? *pDevices : 0,
3309 samplingRate,
3310 format,
3311 channels,
3312 flags);
3313
3314 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003315 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003316 }
3317 Mutex::Autolock _l(mLock);
3318
3319 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3320 (int *)&format,
3321 &channels,
3322 &samplingRate,
3323 &status);
3324 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3325 output,
3326 samplingRate,
3327 format,
3328 channels,
3329 status);
3330
3331 mHardwareStatus = AUDIO_HW_IDLE;
3332 if (output != 0) {
3333 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3334 (format != AudioSystem::PCM_16_BIT) ||
3335 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3336 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003337 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003338 } else {
3339 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003340 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003341 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003342 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003343
3344 if (pSamplingRate) *pSamplingRate = samplingRate;
3345 if (pFormat) *pFormat = format;
3346 if (pChannels) *pChannels = channels;
3347 if (pLatencyMs) *pLatencyMs = thread->latency();
3348 }
3349
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003350 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003351}
3352
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003353int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003354{
3355 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003356 MixerThread *thread1 = checkMixerThread_l(output1);
3357 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003358
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003359 if (thread1 == NULL || thread2 == NULL) {
3360 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3361 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003362 }
3363
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003364
3365 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3366 thread->addOutputTrack(thread2);
3367 mPlaybackThreads.add(++mNextThreadId, thread);
3368 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003369}
3370
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003371status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003372{
Eric Laurentdae20d92009-08-04 08:37:05 -07003373 // keep strong reference on the playback thread so that
3374 // it is not destroyed while exit() is executed
3375 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003376 {
3377 Mutex::Autolock _l(mLock);
3378 thread = checkPlaybackThread_l(output);
3379 if (thread == NULL) {
3380 return BAD_VALUE;
3381 }
3382
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003383 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003384
3385 if (thread->type() == PlaybackThread::MIXER) {
3386 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003387 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3388 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003389 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003390 }
3391 }
3392 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003393 void *param2 = 0;
3394 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, thread, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003395 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003396 }
3397 thread->exit();
3398
Eric Laurentdae20d92009-08-04 08:37:05 -07003399 if (thread->type() != PlaybackThread::DUPLICATING) {
3400 mAudioHardware->closeOutputStream(thread->getOutput());
3401 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003402 return NO_ERROR;
3403}
3404
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003405status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003406{
3407 Mutex::Autolock _l(mLock);
3408 PlaybackThread *thread = checkPlaybackThread_l(output);
3409
3410 if (thread == NULL) {
3411 return BAD_VALUE;
3412 }
3413
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003414 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003415 thread->suspend();
3416
3417 return NO_ERROR;
3418}
3419
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003420status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003421{
3422 Mutex::Autolock _l(mLock);
3423 PlaybackThread *thread = checkPlaybackThread_l(output);
3424
3425 if (thread == NULL) {
3426 return BAD_VALUE;
3427 }
3428
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003429 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003430
3431 thread->restore();
3432
3433 return NO_ERROR;
3434}
3435
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003436int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003437 uint32_t *pSamplingRate,
3438 uint32_t *pFormat,
3439 uint32_t *pChannels,
3440 uint32_t acoustics)
3441{
3442 status_t status;
3443 RecordThread *thread = NULL;
3444 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3445 uint32_t format = pFormat ? *pFormat : 0;
3446 uint32_t channels = pChannels ? *pChannels : 0;
3447 uint32_t reqSamplingRate = samplingRate;
3448 uint32_t reqFormat = format;
3449 uint32_t reqChannels = channels;
3450
3451 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003452 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003453 }
3454 Mutex::Autolock _l(mLock);
3455
3456 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3457 (int *)&format,
3458 &channels,
3459 &samplingRate,
3460 &status,
3461 (AudioSystem::audio_in_acoustics)acoustics);
3462 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3463 input,
3464 samplingRate,
3465 format,
3466 channels,
3467 acoustics,
3468 status);
3469
3470 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3471 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3472 // or stereo to mono conversions on 16 bit PCM inputs.
3473 if (input == 0 && status == BAD_VALUE &&
3474 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3475 (samplingRate <= 2 * reqSamplingRate) &&
3476 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3477 LOGV("openInput() reopening with proposed sampling rate and channels");
3478 input = mAudioHardware->openInputStream(*pDevices,
3479 (int *)&format,
3480 &channels,
3481 &samplingRate,
3482 &status,
3483 (AudioSystem::audio_in_acoustics)acoustics);
3484 }
3485
3486 if (input != 0) {
3487 // Start record thread
3488 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003489 mRecordThreads.add(++mNextThreadId, thread);
3490 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003491 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3492 if (pFormat) *pFormat = format;
3493 if (pChannels) *pChannels = reqChannels;
3494
3495 input->standby();
3496 }
3497
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003498 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003499}
3500
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003501status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003502{
Eric Laurentdae20d92009-08-04 08:37:05 -07003503 // keep strong reference on the record thread so that
3504 // it is not destroyed while exit() is executed
3505 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003506 {
3507 Mutex::Autolock _l(mLock);
3508 thread = checkRecordThread_l(input);
3509 if (thread == NULL) {
3510 return BAD_VALUE;
3511 }
3512
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003513 LOGV("closeInput() %d", input);
Eric Laurentb3687ae2009-09-15 07:10:12 -07003514 void *param2 = 0;
3515 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, thread, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003516 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003517 }
3518 thread->exit();
3519
Eric Laurentdae20d92009-08-04 08:37:05 -07003520 mAudioHardware->closeInputStream(thread->getInput());
3521
Eric Laurent9d91ad52009-07-17 12:17:14 -07003522 return NO_ERROR;
3523}
3524
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003525status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003526{
3527 Mutex::Autolock _l(mLock);
3528 MixerThread *dstThread = checkMixerThread_l(output);
3529 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003530 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003531 return BAD_VALUE;
3532 }
3533
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003534 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003535
3536 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003537 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003538 if (thread != dstThread &&
3539 thread->type() != PlaybackThread::DIRECT) {
3540 MixerThread *srcThread = (MixerThread *)thread;
3541 SortedVector < sp<MixerThread::Track> > tracks;
3542 SortedVector < wp<MixerThread::Track> > activeTracks;
3543 srcThread->getTracks(tracks, activeTracks, stream);
3544 if (tracks.size()) {
3545 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003546 }
3547 }
3548 }
3549
Eric Laurent06437712009-09-01 05:56:26 -07003550 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
3551
Eric Laurent9d91ad52009-07-17 12:17:14 -07003552 return NO_ERROR;
3553}
3554
3555// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003556AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003557{
3558 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003559 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3560 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003561 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003562 return thread;
3563}
3564
3565// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003566AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003567{
3568 PlaybackThread *thread = checkPlaybackThread_l(output);
3569 if (thread != NULL) {
3570 if (thread->type() == PlaybackThread::DIRECT) {
3571 thread = NULL;
3572 }
3573 }
3574 return (MixerThread *)thread;
3575}
3576
3577// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003578AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003579{
3580 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003581 if (mRecordThreads.indexOfKey(input) >= 0) {
3582 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003583 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003584 return thread;
3585}
3586
3587// ----------------------------------------------------------------------------
3588
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003589status_t AudioFlinger::onTransact(
3590 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3591{
3592 return BnAudioFlinger::onTransact(code, data, reply, flags);
3593}
3594
3595// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003596
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003597void AudioFlinger::instantiate() {
3598 defaultServiceManager()->addService(
3599 String16("media.audio_flinger"), new AudioFlinger());
3600}
3601
3602}; // namespace android