blob: ebd470f412e7bfa6fae80e4fb20c91ff106b2b8d [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 float MAX_GAIN = 4096.0f;
66
67// retry counts for buffer fill timeout
68// 50 * ~20msecs = 1 second
69static const int8_t kMaxTrackRetries = 50;
70static const int8_t kMaxTrackStartupRetries = 50;
71
The Android Open Source Project22f8def2009-03-09 11:52:12 -070072static const int kDumpLockRetries = 50;
73static const int kDumpLockSleep = 20000;
74
Dave Sparks8a95a452009-09-30 03:09:03 -070075static const nsecs_t kWarningThrottle = seconds(5);
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
Eric Laurent9d91ad52009-07-17 12:17:14 -0700485 mStreamTypes[stream].volume = value;
486
487 if (thread == NULL) {
Eric Laurent63da2b62009-10-21 08:14:22 -0700488 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700489 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent63da2b62009-10-21 08:14:22 -0700490 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700491 } else {
492 thread->setStreamVolume(stream, value);
493 }
Eric Laurent4dd495b2009-04-21 07:56:33 -0700494
Eric Laurent63da2b62009-10-21 08:14:22 -0700495 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700496}
497
498status_t AudioFlinger::setStreamMute(int stream, bool muted)
499{
500 // check calling permissions
501 if (!settingsAllowed()) {
502 return PERMISSION_DENIED;
503 }
504
Eric Laurent9d91ad52009-07-17 12:17:14 -0700505 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurentb1596ee2009-03-26 01:57:59 -0700506 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700507 return BAD_VALUE;
508 }
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700509
Eric Laurent9d91ad52009-07-17 12:17:14 -0700510 mStreamTypes[stream].mute = muted;
511 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700512 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700514 return NO_ERROR;
515}
516
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700517float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700518{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700519 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700520 return 0.0f;
521 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700522
523 AutoMutex lock(mLock);
524 float volume;
525 if (output) {
526 PlaybackThread *thread = checkPlaybackThread_l(output);
527 if (thread == NULL) {
528 return 0.0f;
529 }
530 volume = thread->streamVolume(stream);
531 } else {
532 volume = mStreamTypes[stream].volume;
533 }
534
Eric Laurent4dd495b2009-04-21 07:56:33 -0700535 return volume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700536}
537
538bool AudioFlinger::streamMute(int stream) const
539{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700540 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700541 return true;
542 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700543
544 return mStreamTypes[stream].mute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700545}
546
547bool AudioFlinger::isMusicActive() const
548{
Eric Laurentb025ca02009-07-09 03:20:57 -0700549 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700550 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700551 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700552 return true;
553 }
554 }
555 return false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700556}
557
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700558status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700559{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700560 status_t result;
561
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700562 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700563 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
564 // check calling permissions
565 if (!settingsAllowed()) {
566 return PERMISSION_DENIED;
The Android Open Source Project8a7a6752009-01-15 16:12:10 -0800567 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700568
569 // ioHandle == 0 means the parameters are global to the audio hardware interface
570 if (ioHandle == 0) {
571 AutoMutex lock(mHardwareLock);
572 mHardwareStatus = AUDIO_SET_PARAMETER;
573 result = mAudioHardware->setParameters(keyValuePairs);
574 mHardwareStatus = AUDIO_HW_IDLE;
575 return result;
576 }
577
Eric Laurent2d70c802009-09-29 11:12:57 -0700578 // hold a strong ref on thread in case closeOutput() or closeInput() is called
579 // and the thread is exited once the lock is released
580 sp<ThreadBase> thread;
581 {
582 Mutex::Autolock _l(mLock);
583 thread = checkPlaybackThread_l(ioHandle);
584 if (thread == NULL) {
585 thread = checkRecordThread_l(ioHandle);
586 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700587 }
Eric Laurent2d70c802009-09-29 11:12:57 -0700588 if (thread != NULL) {
589 return thread->setParameters(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700590 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700591 return BAD_VALUE;
592}
593
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700594String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700595{
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700596// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700597// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
598
599 if (ioHandle == 0) {
600 return mAudioHardware->getParameters(keys);
601 }
Eric Laurent2d70c802009-09-29 11:12:57 -0700602
603 Mutex::Autolock _l(mLock);
604
Eric Laurent9d91ad52009-07-17 12:17:14 -0700605 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
606 if (playbackThread != NULL) {
607 return playbackThread->getParameters(keys);
608 }
609 RecordThread *recordThread = checkRecordThread_l(ioHandle);
610 if (recordThread != NULL) {
611 return recordThread->getParameters(keys);
612 }
613 return String8("");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700614}
615
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800616size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
617{
618 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
619}
620
Eric Laurent63da2b62009-10-21 08:14:22 -0700621status_t AudioFlinger::setVoiceVolume(float value)
622{
623 // check calling permissions
624 if (!settingsAllowed()) {
625 return PERMISSION_DENIED;
626 }
627
628 AutoMutex lock(mHardwareLock);
629 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
630 status_t ret = mAudioHardware->setVoiceVolume(value);
631 mHardwareStatus = AUDIO_HW_IDLE;
632
633 return ret;
634}
635
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800636void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
637{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700638
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800639 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
640 Mutex::Autolock _l(mLock);
641
642 sp<IBinder> binder = client->asBinder();
643 if (mNotificationClients.indexOf(binder) < 0) {
644 LOGV("Adding notification client %p", binder.get());
645 binder->linkToDeath(this);
646 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700647 }
648
649 // the config change is always sent from playback or record threads to avoid deadlock
650 // with AudioSystem::gLock
651 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700652 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700653 }
654
655 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700656 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 }
658}
659
660void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700661
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800662 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
663 Mutex::Autolock _l(mLock);
664
665 IBinder *binder = who.unsafe_get();
666
667 if (binder != NULL) {
668 int index = mNotificationClients.indexOf(binder);
669 if (index >= 0) {
670 LOGV("Removing notification client %p", binder);
671 mNotificationClients.removeAt(index);
672 }
673 }
674}
675
Eric Laurentb3687ae2009-09-15 07:10:12 -0700676// audioConfigChanged_l() must be called with AudioFlinger::mLock held
677void AudioFlinger::audioConfigChanged_l(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700678 int ioHandle = 0;
679
680 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
681 if (mPlaybackThreads.valueAt(i) == thread) {
682 ioHandle = mPlaybackThreads.keyAt(i);
683 break;
684 }
685 }
686 if (ioHandle == 0) {
687 for (size_t i = 0; i < mRecordThreads.size(); i++) {
688 if (mRecordThreads.valueAt(i) == thread) {
689 ioHandle = mRecordThreads.keyAt(i);
690 break;
691 }
692 }
693 }
694
695 if (ioHandle != 0) {
696 size_t size = mNotificationClients.size();
697 for (size_t i = 0; i < size; i++) {
698 sp<IBinder> binder = mNotificationClients.itemAt(i);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700699 LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700700 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
701 client->ioConfigChanged(event, ioHandle, param2);
702 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700703 }
704}
705
Eric Laurent0f8ab672009-09-17 05:12:56 -0700706// removeClient_l() must be called with AudioFlinger::mLock held
707void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700708{
Eric Laurent0f8ab672009-09-17 05:12:56 -0700709 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 -0700710 mClients.removeItem(pid);
711}
712
Eric Laurent9d91ad52009-07-17 12:17:14 -0700713// ----------------------------------------------------------------------------
714
715AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
716 : Thread(false),
717 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent3464c012009-08-04 09:45:33 -0700718 mFormat(0), mFrameSize(1), mStandby(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700719{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720}
721
Eric Laurent9d91ad52009-07-17 12:17:14 -0700722AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800723{
Eric Laurent3464c012009-08-04 09:45:33 -0700724 mParamCond.broadcast();
725 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800726}
727
Eric Laurent9d91ad52009-07-17 12:17:14 -0700728void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700729{
Eric Laurent2d70c802009-09-29 11:12:57 -0700730 // keep a strong ref on ourself so that we wont get
Eric Laurent9d91ad52009-07-17 12:17:14 -0700731 // destroyed in the middle of requestExitAndWait()
732 sp <ThreadBase> strongMe = this;
733
734 LOGV("ThreadBase::exit");
735 {
736 AutoMutex lock(&mLock);
737 requestExit();
738 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700739 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700740 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700741}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700742
743uint32_t AudioFlinger::ThreadBase::sampleRate() const
744{
745 return mSampleRate;
746}
747
748int AudioFlinger::ThreadBase::channelCount() const
749{
750 return mChannelCount;
751}
752
753int AudioFlinger::ThreadBase::format() const
754{
755 return mFormat;
756}
757
758size_t AudioFlinger::ThreadBase::frameCount() const
759{
760 return mFrameCount;
761}
762
763status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
764{
Eric Laurent3464c012009-08-04 09:45:33 -0700765 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700766
Eric Laurent3464c012009-08-04 09:45:33 -0700767 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700768 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700769
Eric Laurent3464c012009-08-04 09:45:33 -0700770 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700771 mWaitWorkCV.signal();
Eric Laurent2d70c802009-09-29 11:12:57 -0700772 // wait condition with timeout in case the thread loop has exited
773 // before the request could be processed
774 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
775 status = mParamStatus;
776 mWaitWorkCV.signal();
777 } else {
778 status = TIMED_OUT;
779 }
Eric Laurent3464c012009-08-04 09:45:33 -0700780 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700781}
782
783void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
784{
785 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700786 sendConfigEvent_l(event, param);
787}
788
789// sendConfigEvent_l() must be called with ThreadBase::mLock held
790void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
791{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700792 ConfigEvent *configEvent = new ConfigEvent();
793 configEvent->mEvent = event;
794 configEvent->mParam = param;
795 mConfigEvents.add(configEvent);
796 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
797 mWaitWorkCV.signal();
798}
799
800void AudioFlinger::ThreadBase::processConfigEvents()
801{
802 mLock.lock();
803 while(!mConfigEvents.isEmpty()) {
804 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
805 ConfigEvent *configEvent = mConfigEvents[0];
806 mConfigEvents.removeAt(0);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700807 // release mLock because audioConfigChanged() will lock AudioFlinger mLock
808 // before calling Audioflinger::audioConfigChanged_l() thus creating
Eric Laurent9d91ad52009-07-17 12:17:14 -0700809 // potential cross deadlock between AudioFlinger::mLock and mLock
810 mLock.unlock();
811 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
812 delete configEvent;
813 mLock.lock();
814 }
815 mLock.unlock();
816}
817
Eric Laurentee47d432009-11-07 00:01:32 -0800818status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
819{
820 const size_t SIZE = 256;
821 char buffer[SIZE];
822 String8 result;
823
824 bool locked = tryLock(mLock);
825 if (!locked) {
826 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
827 write(fd, buffer, strlen(buffer));
828 }
829
830 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
831 result.append(buffer);
832 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
833 result.append(buffer);
834 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
835 result.append(buffer);
836 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
837 result.append(buffer);
838 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
839 result.append(buffer);
840 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
841 result.append(buffer);
842
843 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
844 result.append(buffer);
845 result.append(" Index Command");
846 for (size_t i = 0; i < mNewParameters.size(); ++i) {
847 snprintf(buffer, SIZE, "\n %02d ", i);
848 result.append(buffer);
849 result.append(mNewParameters[i]);
850 }
851
852 snprintf(buffer, SIZE, "\n\nPending config events: \n");
853 result.append(buffer);
854 snprintf(buffer, SIZE, " Index event param\n");
855 result.append(buffer);
856 for (size_t i = 0; i < mConfigEvents.size(); i++) {
857 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
858 result.append(buffer);
859 }
860 result.append("\n");
861
862 write(fd, result.string(), result.size());
863
864 if (locked) {
865 mLock.unlock();
866 }
867 return NO_ERROR;
868}
869
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800870
871// ----------------------------------------------------------------------------
872
Eric Laurent9d91ad52009-07-17 12:17:14 -0700873AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
874 : ThreadBase(audioFlinger),
Eric Laurentf9df2492009-08-06 08:49:39 -0700875 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700876 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800877{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700878 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800879
Eric Laurent9d91ad52009-07-17 12:17:14 -0700880 mMasterVolume = mAudioFlinger->masterVolume();
881 mMasterMute = mAudioFlinger->masterMute();
882
883 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
884 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
885 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800886 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700887 // notify client processes that a new input has been opened
888 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800889}
890
Eric Laurent9d91ad52009-07-17 12:17:14 -0700891AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800892{
893 delete [] mMixBuffer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800894}
895
Eric Laurent9d91ad52009-07-17 12:17:14 -0700896status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800897{
898 dumpInternals(fd, args);
899 dumpTracks(fd, args);
900 return NO_ERROR;
901}
902
Eric Laurent9d91ad52009-07-17 12:17:14 -0700903status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800904{
905 const size_t SIZE = 256;
906 char buffer[SIZE];
907 String8 result;
908
Eric Laurent9d91ad52009-07-17 12:17:14 -0700909 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800910 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -0800911 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800912 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700913 sp<Track> track = mTracks[i];
914 if (track != 0) {
915 track->dump(buffer, SIZE);
916 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800917 }
918 }
919
Eric Laurent9d91ad52009-07-17 12:17:14 -0700920 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800921 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -0800922 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800923 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700924 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800925 if (wTrack != 0) {
926 sp<Track> track = wTrack.promote();
927 if (track != 0) {
928 track->dump(buffer, SIZE);
929 result.append(buffer);
930 }
931 }
932 }
933 write(fd, result.string(), result.size());
934 return NO_ERROR;
935}
936
Eric Laurent9d91ad52009-07-17 12:17:14 -0700937status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800938{
939 const size_t SIZE = 256;
940 char buffer[SIZE];
941 String8 result;
942
Eric Laurentee47d432009-11-07 00:01:32 -0800943 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800944 result.append(buffer);
945 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
946 result.append(buffer);
947 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
948 result.append(buffer);
949 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
950 result.append(buffer);
951 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
952 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800953 write(fd, result.string(), result.size());
Eric Laurentee47d432009-11-07 00:01:32 -0800954
955 dumpBase(fd, args);
956
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800957 return NO_ERROR;
958}
959
960// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700961status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800962{
963 if (mSampleRate == 0) {
964 LOGE("No working audio driver found.");
965 return NO_INIT;
966 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700967 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800968 return NO_ERROR;
969}
970
Eric Laurent9d91ad52009-07-17 12:17:14 -0700971void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800972{
973 const size_t SIZE = 256;
974 char buffer[SIZE];
975
Eric Laurent9d91ad52009-07-17 12:17:14 -0700976 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800977
978 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
979}
980
Eric Laurent9d91ad52009-07-17 12:17:14 -0700981// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
982sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800983 const sp<AudioFlinger::Client>& client,
984 int streamType,
985 uint32_t sampleRate,
986 int format,
987 int channelCount,
988 int frameCount,
989 const sp<IMemory>& sharedBuffer,
990 status_t *status)
991{
992 sp<Track> track;
993 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700994
995 if (mType == DIRECT) {
996 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
997 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
998 sampleRate, format, channelCount, mOutput);
999 lStatus = BAD_VALUE;
1000 goto Exit;
1001 }
1002 } else {
1003 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1004 if (sampleRate > mSampleRate*2) {
1005 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1006 lStatus = BAD_VALUE;
1007 goto Exit;
1008 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001009 }
1010
Eric Laurent9d91ad52009-07-17 12:17:14 -07001011 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001012 LOGE("Audio driver not initialized.");
1013 lStatus = NO_INIT;
1014 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001015 }
1016
Eric Laurent9d91ad52009-07-17 12:17:14 -07001017 { // scope for mLock
1018 Mutex::Autolock _l(mLock);
1019 track = new Track(this, client, streamType, sampleRate, format,
1020 channelCount, frameCount, sharedBuffer);
Eric Laurent7b570852009-11-09 04:45:39 -08001021 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001022 lStatus = NO_MEMORY;
1023 goto Exit;
1024 }
1025 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001026 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001027 lStatus = NO_ERROR;
1028
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001029Exit:
1030 if(status) {
1031 *status = lStatus;
1032 }
1033 return track;
1034}
1035
Eric Laurent9d91ad52009-07-17 12:17:14 -07001036uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037{
1038 if (mOutput) {
1039 return mOutput->latency();
1040 }
1041 else {
1042 return 0;
1043 }
1044}
1045
Eric Laurent9d91ad52009-07-17 12:17:14 -07001046status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001047{
1048 mMasterVolume = value;
1049 return NO_ERROR;
1050}
1051
Eric Laurent9d91ad52009-07-17 12:17:14 -07001052status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001053{
1054 mMasterMute = muted;
1055 return NO_ERROR;
1056}
1057
Eric Laurent9d91ad52009-07-17 12:17:14 -07001058float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001059{
1060 return mMasterVolume;
1061}
1062
Eric Laurent9d91ad52009-07-17 12:17:14 -07001063bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001064{
1065 return mMasterMute;
1066}
1067
Eric Laurent9d91ad52009-07-17 12:17:14 -07001068status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001069{
1070 mStreamTypes[stream].volume = value;
1071 return NO_ERROR;
1072}
1073
Eric Laurent9d91ad52009-07-17 12:17:14 -07001074status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075{
1076 mStreamTypes[stream].mute = muted;
1077 return NO_ERROR;
1078}
1079
Eric Laurent9d91ad52009-07-17 12:17:14 -07001080float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001081{
1082 return mStreamTypes[stream].volume;
1083}
1084
Eric Laurent9d91ad52009-07-17 12:17:14 -07001085bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001086{
1087 return mStreamTypes[stream].mute;
1088}
1089
Eric Laurent9d91ad52009-07-17 12:17:14 -07001090bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001091{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001092 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001093 size_t count = mActiveTracks.size();
1094 for (size_t i = 0 ; i < count ; ++i) {
1095 sp<Track> t = mActiveTracks[i].promote();
1096 if (t == 0) continue;
1097 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001098 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001099 return true;
1100 }
1101 return false;
1102}
1103
Eric Laurent9d91ad52009-07-17 12:17:14 -07001104// addTrack_l() must be called with ThreadBase::mLock held
1105status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001106{
1107 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001108
1109 // here the track could be either new, or restarted
1110 // in both cases "unstop" the track
1111 if (track->isPaused()) {
1112 track->mState = TrackBase::RESUMING;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001113 LOGV("PAUSED => RESUMING (%d) on thread %p", track->name(), this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001114 } else {
1115 track->mState = TrackBase::ACTIVE;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001116 LOGV("? => ACTIVE (%d) on thread %p", track->name(), this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001117 }
1118 // set retry count for buffer fill
1119 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001120 if (mActiveTracks.indexOf(track) < 0) {
1121 // the track is newly added, make sure it fills up all its
1122 // buffers before playing. This is to ensure the client will
1123 // effectively get the latency it requested.
1124 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001125 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001126 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001127 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001128 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001130 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001131 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001132
1133 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001134}
1135
Eric Laurent9d91ad52009-07-17 12:17:14 -07001136// destroyTrack_l() must be called with ThreadBase::mLock held
1137void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001138{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001139 track->mState = TrackBase::TERMINATED;
1140 if (mActiveTracks.indexOf(track) < 0) {
1141 LOGV("remove track (%d) and delete from mixer", track->name());
1142 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001143 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001144 }
1145}
1146
Eric Laurent9d91ad52009-07-17 12:17:14 -07001147String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001148{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001149 return mOutput->getParameters(keys);
1150}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001151
Eric Laurent9d91ad52009-07-17 12:17:14 -07001152void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1153 AudioSystem::OutputDescriptor desc;
1154 void *param2 = 0;
1155
1156 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1157
1158 switch (event) {
1159 case AudioSystem::OUTPUT_OPENED:
1160 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1161 desc.channels = mChannelCount;
1162 desc.samplingRate = mSampleRate;
1163 desc.format = mFormat;
1164 desc.frameCount = mFrameCount;
1165 desc.latency = latency();
1166 param2 = &desc;
1167 break;
1168
1169 case AudioSystem::STREAM_CONFIG_CHANGED:
1170 param2 = &param;
1171 case AudioSystem::OUTPUT_CLOSED:
1172 default:
1173 break;
1174 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07001175 Mutex::Autolock _l(mAudioFlinger->mLock);
1176 mAudioFlinger->audioConfigChanged_l(event, this, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001177}
1178
1179void AudioFlinger::PlaybackThread::readOutputParameters()
1180{
1181 mSampleRate = mOutput->sampleRate();
1182 mChannelCount = AudioSystem::popCount(mOutput->channels());
1183
1184 mFormat = mOutput->format();
1185 mFrameSize = mOutput->frameSize();
1186 mFrameCount = mOutput->bufferSize() / mFrameSize;
1187
1188 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1189 // FIXME - Current mixer implementation only supports stereo output: Always
1190 // Allocate a stereo buffer even if HW output is mono.
1191 if (mMixBuffer != NULL) delete mMixBuffer;
1192 mMixBuffer = new int16_t[mFrameCount * 2];
1193 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1194}
1195
1196// ----------------------------------------------------------------------------
1197
1198AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1199 : PlaybackThread(audioFlinger, output),
1200 mAudioMixer(0)
1201{
1202 mType = PlaybackThread::MIXER;
1203 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1204
1205 // FIXME - Current mixer implementation only supports stereo output
1206 if (mChannelCount == 1) {
1207 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001208 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001209}
1210
Eric Laurent9d91ad52009-07-17 12:17:14 -07001211AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001212{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001213 delete mAudioMixer;
1214}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001215
Eric Laurent9d91ad52009-07-17 12:17:14 -07001216bool AudioFlinger::MixerThread::threadLoop()
1217{
Eric Laurent134aa9c2009-10-30 11:09:39 -07001218 uint32_t sleepTime = 1000;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001219 uint32_t maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001220 int16_t* curBuf = mMixBuffer;
1221 Vector< sp<Track> > tracksToRemove;
1222 size_t enabledTracks = 0;
1223 nsecs_t standbyTime = systemTime();
1224 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparks8a95a452009-09-30 03:09:03 -07001225 // FIXME: Relaxed timing because of a certain device that can't meet latency
1226 // Should be reduced to 2x after the vendor fixes the driver issue
1227 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1228 nsecs_t lastWarning = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001229
Eric Laurent9d91ad52009-07-17 12:17:14 -07001230 while (!exitPending())
1231 {
1232 processConfigEvents();
1233
1234 enabledTracks = 0;
1235 { // scope for mLock
1236
1237 Mutex::Autolock _l(mLock);
1238
1239 if (checkForNewParameters_l()) {
1240 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparks8a95a452009-09-30 03:09:03 -07001241 // FIXME: Relaxed timing because of a certain device that can't meet latency
1242 // Should be reduced to 2x after the vendor fixes the driver issue
1243 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001244 maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001245 }
1246
1247 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1248
1249 // put audio hardware into standby after short delay
1250 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1251 mSuspended) {
1252 if (!mStandby) {
1253 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1254 mOutput->standby();
1255 mStandby = true;
1256 mBytesWritten = 0;
1257 }
1258
1259 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1260 // we're about to wait, flush the binder command buffer
1261 IPCThreadState::self()->flushCommands();
1262
1263 if (exitPending()) break;
1264
1265 // wait until we have something to do...
1266 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1267 mWaitWorkCV.wait(mLock);
1268 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1269
1270 if (mMasterMute == false) {
1271 char value[PROPERTY_VALUE_MAX];
1272 property_get("ro.audio.silent", value, "0");
1273 if (atoi(value)) {
1274 LOGD("Silence is golden");
1275 setMasterMute(true);
1276 }
1277 }
1278
1279 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent134aa9c2009-10-30 11:09:39 -07001280 sleepTime = 1000;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001281 continue;
1282 }
1283 }
1284
1285 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1286 }
1287
Eric Laurentaef692f2009-09-22 00:35:48 -07001288 if (LIKELY(enabledTracks)) {
1289 // mix buffers...
1290 mAudioMixer->process(curBuf);
1291 sleepTime = 0;
1292 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001293 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001294 // If no tracks are ready, sleep once for the duration of an output
1295 // buffer size, then write 0s to the output
1296 if (sleepTime == 0) {
1297 sleepTime = maxBufferRecoveryInUsecs;
1298 } else if (mBytesWritten != 0) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001299 memset (curBuf, 0, mixBufferSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001300 sleepTime = 0;
Eric Laurent3522c802009-09-07 08:38:38 -07001301 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001302 }
1303
1304 if (mSuspended) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001305 sleepTime = maxBufferRecoveryInUsecs;
Eric Laurentaef692f2009-09-22 00:35:48 -07001306 }
1307 // sleepTime == 0 means we must write to audio hardware
1308 if (sleepTime == 0) {
1309 mLastWriteTime = systemTime();
1310 mInWrite = true;
Eric Laurentaef692f2009-09-22 00:35:48 -07001311 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1312 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1313 mNumWrites++;
1314 mInWrite = false;
1315 mStandby = false;
Dave Sparks8a95a452009-09-30 03:09:03 -07001316 nsecs_t now = systemTime();
1317 nsecs_t delta = now - mLastWriteTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07001318 if (delta > maxPeriod) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001319 mNumDelayedWrites++;
Dave Sparks8a95a452009-09-30 03:09:03 -07001320 if ((now - lastWarning) > kWarningThrottle) {
1321 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1322 ns2ms(delta), mNumDelayedWrites, this);
1323 lastWarning = now;
1324 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001325 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001326 } else {
1327 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001328 }
1329
1330 // finally let go of all our tracks, without the lock held
1331 // since we can't guarantee the destructors won't acquire that
1332 // same lock.
1333 tracksToRemove.clear();
1334 }
1335
1336 if (!mStandby) {
1337 mOutput->standby();
1338 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001339
1340 LOGV("MixerThread %p exiting", this);
1341 return false;
1342}
1343
1344// prepareTracks_l() must be called with ThreadBase::mLock held
1345size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1346{
1347
1348 size_t enabledTracks = 0;
1349 // find out which tracks need to be processed
1350 size_t count = activeTracks.size();
1351 for (size_t i=0 ; i<count ; i++) {
1352 sp<Track> t = activeTracks[i].promote();
1353 if (t == 0) continue;
1354
1355 Track* const track = t.get();
1356 audio_track_cblk_t* cblk = track->cblk();
1357
1358 // The first time a track is added we wait
1359 // for all its buffers to be filled before processing it
1360 mAudioMixer->setActiveTrack(track->name());
1361 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1362 !track->isPaused())
1363 {
1364 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1365
1366 // compute volume for this track
1367 int16_t left, right;
1368 if (track->isMuted() || mMasterMute || track->isPausing() ||
1369 mStreamTypes[track->type()].mute) {
1370 left = right = 0;
1371 if (track->isPausing()) {
1372 track->setPaused();
1373 }
1374 } else {
1375 float typeVolume = mStreamTypes[track->type()].volume;
1376 float v = mMasterVolume * typeVolume;
1377 float v_clamped = v * cblk->volume[0];
1378 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1379 left = int16_t(v_clamped);
1380 v_clamped = v * cblk->volume[1];
1381 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1382 right = int16_t(v_clamped);
1383 }
1384
1385 // XXX: these things DON'T need to be done each time
1386 mAudioMixer->setBufferProvider(track);
1387 mAudioMixer->enable(AudioMixer::MIXING);
1388
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001389 int param = AudioMixer::VOLUME;
1390 if (track->mFillingUpStatus == Track::FS_FILLED) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001391 // no ramp for the first volume setting
1392 track->mFillingUpStatus = Track::FS_ACTIVE;
1393 if (track->mState == TrackBase::RESUMING) {
1394 track->mState = TrackBase::ACTIVE;
1395 param = AudioMixer::RAMP_VOLUME;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001396 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001397 } else if (cblk->server != 0) {
1398 // If the track is stopped before the first frame was mixed,
1399 // do not apply ramp
Eric Laurent9d91ad52009-07-17 12:17:14 -07001400 param = AudioMixer::RAMP_VOLUME;
1401 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001402
Eric Laurent9d91ad52009-07-17 12:17:14 -07001403 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1404 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1405 mAudioMixer->setParameter(
1406 AudioMixer::TRACK,
1407 AudioMixer::FORMAT, track->format());
1408 mAudioMixer->setParameter(
1409 AudioMixer::TRACK,
1410 AudioMixer::CHANNEL_COUNT, track->channelCount());
1411 mAudioMixer->setParameter(
1412 AudioMixer::RESAMPLE,
1413 AudioMixer::SAMPLE_RATE,
1414 int(cblk->sampleRate));
1415
1416 // reset retry count
1417 track->mRetryCount = kMaxTrackRetries;
1418 enabledTracks++;
1419 } else {
1420 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1421 if (track->isStopped()) {
1422 track->reset();
1423 }
1424 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1425 // We have consumed all the buffers of this track.
1426 // Remove it from the list of active tracks.
1427 tracksToRemove->add(track);
1428 mAudioMixer->disable(AudioMixer::MIXING);
1429 } else {
1430 // No buffers for this track. Give it a few chances to
1431 // fill a buffer, then remove it from active list.
1432 if (--(track->mRetryCount) <= 0) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001433 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001434 tracksToRemove->add(track);
1435 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001436 // For tracks using static shared memory buffer, make sure that we have
Eric Laurent9d91ad52009-07-17 12:17:14 -07001437 // written enough data to audio hardware before disabling the track
1438 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1439 // don't care about code removing track from active list above.
1440 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1441 mAudioMixer->disable(AudioMixer::MIXING);
1442 } else {
1443 enabledTracks++;
1444 }
1445 }
1446 }
1447 }
1448
1449 // remove all the tracks that need to be...
1450 count = tracksToRemove->size();
1451 if (UNLIKELY(count)) {
1452 for (size_t i=0 ; i<count ; i++) {
1453 const sp<Track>& track = tracksToRemove->itemAt(i);
1454 mActiveTracks.remove(track);
1455 if (track->isTerminated()) {
1456 mTracks.remove(track);
1457 deleteTrackName_l(track->mName);
1458 }
1459 }
1460 }
1461
1462 return enabledTracks;
1463}
1464
1465void AudioFlinger::MixerThread::getTracks(
1466 SortedVector < sp<Track> >& tracks,
1467 SortedVector < wp<Track> >& activeTracks,
1468 int streamType)
1469{
1470 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1471 Mutex::Autolock _l(mLock);
1472 size_t size = mTracks.size();
1473 for (size_t i = 0; i < size; i++) {
1474 sp<Track> t = mTracks[i];
1475 if (t->type() == streamType) {
1476 tracks.add(t);
1477 int j = mActiveTracks.indexOf(t);
1478 if (j >= 0) {
1479 t = mActiveTracks[j].promote();
1480 if (t != NULL) {
1481 activeTracks.add(t);
1482 }
1483 }
1484 }
1485 }
1486
1487 size = activeTracks.size();
1488 for (size_t i = 0; i < size; i++) {
1489 mActiveTracks.remove(activeTracks[i]);
1490 }
1491
1492 size = tracks.size();
1493 for (size_t i = 0; i < size; i++) {
1494 sp<Track> t = tracks[i];
1495 mTracks.remove(t);
1496 deleteTrackName_l(t->name());
1497 }
1498}
1499
1500void AudioFlinger::MixerThread::putTracks(
1501 SortedVector < sp<Track> >& tracks,
1502 SortedVector < wp<Track> >& activeTracks)
1503{
1504 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1505 Mutex::Autolock _l(mLock);
1506 size_t size = tracks.size();
1507 for (size_t i = 0; i < size ; i++) {
1508 sp<Track> t = tracks[i];
1509 int name = getTrackName_l();
1510
1511 if (name < 0) return;
1512
1513 t->mName = name;
1514 t->mThread = this;
1515 mTracks.add(t);
1516
1517 int j = activeTracks.indexOf(t);
1518 if (j >= 0) {
1519 mActiveTracks.add(t);
Eric Laurent06437712009-09-01 05:56:26 -07001520 // force buffer refilling and no ramp volume when the track is mixed for the first time
1521 t->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001522 }
1523 }
1524}
1525
Eric Laurent9d91ad52009-07-17 12:17:14 -07001526// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001527int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001528{
1529 return mAudioMixer->getTrackName();
1530}
1531
Eric Laurent9d91ad52009-07-17 12:17:14 -07001532// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001533void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001534{
1535 mAudioMixer->deleteTrackName(name);
1536}
1537
Eric Laurent9d91ad52009-07-17 12:17:14 -07001538// checkForNewParameters_l() must be called with ThreadBase::mLock held
1539bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001540{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001541 bool reconfig = false;
1542
Eric Laurent3464c012009-08-04 09:45:33 -07001543 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001544 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001545 String8 keyValuePair = mNewParameters[0];
1546 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001547 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001548
Eric Laurent9d91ad52009-07-17 12:17:14 -07001549 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1550 reconfig = true;
1551 }
1552 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1553 if (value != AudioSystem::PCM_16_BIT) {
1554 status = BAD_VALUE;
1555 } else {
1556 reconfig = true;
1557 }
1558 }
1559 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1560 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1561 status = BAD_VALUE;
1562 } else {
1563 reconfig = true;
1564 }
1565 }
1566 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1567 // do not accept frame count changes if tracks are open as the track buffer
1568 // size depends on frame count and correct behavior would not be garantied
1569 // if frame count is changed after track creation
1570 if (!mTracks.isEmpty()) {
1571 status = INVALID_OPERATION;
1572 } else {
1573 reconfig = true;
1574 }
1575 }
1576 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001577 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001578 if (!mStandby && status == INVALID_OPERATION) {
1579 mOutput->standby();
1580 mStandby = true;
1581 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001582 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001583 }
1584 if (status == NO_ERROR && reconfig) {
1585 delete mAudioMixer;
1586 readOutputParameters();
1587 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1588 for (size_t i = 0; i < mTracks.size() ; i++) {
1589 int name = getTrackName_l();
1590 if (name < 0) break;
1591 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001592 // limit track sample rate to 2 x new output sample rate
1593 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1594 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1595 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001596 }
Eric Laurent3464c012009-08-04 09:45:33 -07001597 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001598 }
1599 }
Eric Laurentee47d432009-11-07 00:01:32 -08001600
1601 mNewParameters.removeAt(0);
1602
Eric Laurent9d91ad52009-07-17 12:17:14 -07001603 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001604 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001605 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001606 }
1607 return reconfig;
1608}
1609
1610status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1611{
1612 const size_t SIZE = 256;
1613 char buffer[SIZE];
1614 String8 result;
1615
1616 PlaybackThread::dumpInternals(fd, args);
1617
1618 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1619 result.append(buffer);
1620 write(fd, result.string(), result.size());
1621 return NO_ERROR;
1622}
1623
Eric Laurentf5e868b2009-10-05 20:29:18 -07001624uint32_t AudioFlinger::MixerThread::getMaxBufferRecoveryInUsecs()
1625{
1626 uint32_t time = ((mFrameCount * 1000) / mSampleRate) * 1000;
1627 // Add some margin with regard to scheduling precision
1628 if (time > 10000) {
1629 time -= 10000;
1630 }
1631 return time;
1632}
1633
Eric Laurent9d91ad52009-07-17 12:17:14 -07001634// ----------------------------------------------------------------------------
1635AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1636 : PlaybackThread(audioFlinger, output),
1637 mLeftVolume (1.0), mRightVolume(1.0)
1638{
1639 mType = PlaybackThread::DIRECT;
1640}
1641
1642AudioFlinger::DirectOutputThread::~DirectOutputThread()
1643{
1644}
1645
1646
1647bool AudioFlinger::DirectOutputThread::threadLoop()
1648{
Eric Laurent134aa9c2009-10-30 11:09:39 -07001649 uint32_t sleepTime = 1000;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001650 uint32_t maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001651 sp<Track> trackToRemove;
1652 sp<Track> activeTrack;
1653 nsecs_t standbyTime = systemTime();
1654 int8_t *curBuf;
1655 size_t mixBufferSize = mFrameCount*mFrameSize;
1656
1657 while (!exitPending())
1658 {
1659 processConfigEvents();
1660
1661 { // scope for the mLock
1662
1663 Mutex::Autolock _l(mLock);
1664
1665 if (checkForNewParameters_l()) {
1666 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001667 maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001668 }
1669
1670 // put audio hardware into standby after short delay
1671 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1672 mSuspended) {
1673 // wait until we have something to do...
1674 if (!mStandby) {
1675 LOGV("Audio hardware entering standby, mixer %p\n", this);
1676 mOutput->standby();
1677 mStandby = true;
1678 mBytesWritten = 0;
1679 }
1680
1681 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1682 // we're about to wait, flush the binder command buffer
1683 IPCThreadState::self()->flushCommands();
1684
1685 if (exitPending()) break;
1686
1687 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1688 mWaitWorkCV.wait(mLock);
1689 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1690
1691 if (mMasterMute == false) {
1692 char value[PROPERTY_VALUE_MAX];
1693 property_get("ro.audio.silent", value, "0");
1694 if (atoi(value)) {
1695 LOGD("Silence is golden");
1696 setMasterMute(true);
1697 }
1698 }
1699
1700 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent134aa9c2009-10-30 11:09:39 -07001701 sleepTime = 1000;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001702 continue;
1703 }
1704 }
1705
1706 // find out which tracks need to be processed
1707 if (mActiveTracks.size() != 0) {
1708 sp<Track> t = mActiveTracks[0].promote();
1709 if (t == 0) continue;
1710
1711 Track* const track = t.get();
1712 audio_track_cblk_t* cblk = track->cblk();
1713
1714 // The first time a track is added we wait
1715 // for all its buffers to be filled before processing it
1716 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1717 !track->isPaused())
1718 {
1719 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1720
1721 // compute volume for this track
1722 float left, right;
1723 if (track->isMuted() || mMasterMute || track->isPausing() ||
1724 mStreamTypes[track->type()].mute) {
1725 left = right = 0;
1726 if (track->isPausing()) {
1727 track->setPaused();
1728 }
1729 } else {
1730 float typeVolume = mStreamTypes[track->type()].volume;
1731 float v = mMasterVolume * typeVolume;
1732 float v_clamped = v * cblk->volume[0];
1733 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1734 left = v_clamped/MAX_GAIN;
1735 v_clamped = v * cblk->volume[1];
1736 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1737 right = v_clamped/MAX_GAIN;
1738 }
1739
1740 if (left != mLeftVolume || right != mRightVolume) {
1741 mOutput->setVolume(left, right);
1742 left = mLeftVolume;
1743 right = mRightVolume;
1744 }
1745
1746 if (track->mFillingUpStatus == Track::FS_FILLED) {
1747 track->mFillingUpStatus = Track::FS_ACTIVE;
1748 if (track->mState == TrackBase::RESUMING) {
1749 track->mState = TrackBase::ACTIVE;
1750 }
1751 }
1752
1753 // reset retry count
1754 track->mRetryCount = kMaxTrackRetries;
1755 activeTrack = t;
1756 } else {
1757 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1758 if (track->isStopped()) {
1759 track->reset();
1760 }
1761 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1762 // We have consumed all the buffers of this track.
1763 // Remove it from the list of active tracks.
1764 trackToRemove = track;
1765 } else {
1766 // No buffers for this track. Give it a few chances to
1767 // fill a buffer, then remove it from active list.
1768 if (--(track->mRetryCount) <= 0) {
1769 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1770 trackToRemove = track;
1771 }
1772
1773 // For tracks using static shared memry buffer, make sure that we have
1774 // written enough data to audio hardware before disabling the track
1775 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1776 // don't care about code removing track from active list above.
1777 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1778 activeTrack = t;
1779 }
1780 }
1781 }
1782 }
1783
1784 // remove all the tracks that need to be...
1785 if (UNLIKELY(trackToRemove != 0)) {
1786 mActiveTracks.remove(trackToRemove);
1787 if (trackToRemove->isTerminated()) {
1788 mTracks.remove(trackToRemove);
1789 deleteTrackName_l(trackToRemove->mName);
1790 }
1791 }
1792 }
1793
Eric Laurentaef692f2009-09-22 00:35:48 -07001794 if (activeTrack != 0) {
1795 AudioBufferProvider::Buffer buffer;
1796 size_t frameCount = mFrameCount;
1797 curBuf = (int8_t *)mMixBuffer;
1798 // output audio to hardware
1799 while(frameCount) {
1800 buffer.frameCount = frameCount;
1801 activeTrack->getNextBuffer(&buffer);
1802 if (UNLIKELY(buffer.raw == 0)) {
1803 memset(curBuf, 0, frameCount * mFrameSize);
1804 break;
1805 }
1806 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1807 frameCount -= buffer.frameCount;
1808 curBuf += buffer.frameCount * mFrameSize;
1809 activeTrack->releaseBuffer(&buffer);
1810 }
1811 sleepTime = 0;
1812 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001813 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001814 if (sleepTime == 0) {
1815 sleepTime = maxBufferRecoveryInUsecs;
1816 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001817 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001818 sleepTime = 0;
Eric Laurent3522c802009-09-07 08:38:38 -07001819 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001820 }
Eric Laurent3522c802009-09-07 08:38:38 -07001821
Eric Laurentaef692f2009-09-22 00:35:48 -07001822 if (mSuspended) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001823 sleepTime = maxBufferRecoveryInUsecs;
Eric Laurentaef692f2009-09-22 00:35:48 -07001824 }
1825 // sleepTime == 0 means we must write to audio hardware
1826 if (sleepTime == 0) {
1827 mLastWriteTime = systemTime();
1828 mInWrite = true;
1829 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1830 if (bytesWritten) mBytesWritten += bytesWritten;
1831 mNumWrites++;
1832 mInWrite = false;
1833 mStandby = false;
1834 } else {
1835 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001836 }
1837
1838 // finally let go of removed track, without the lock held
1839 // since we can't guarantee the destructors won't acquire that
1840 // same lock.
1841 trackToRemove.clear();
1842 activeTrack.clear();
1843 }
1844
1845 if (!mStandby) {
1846 mOutput->standby();
1847 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001848
1849 LOGV("DirectOutputThread %p exiting", this);
1850 return false;
1851}
1852
1853// getTrackName_l() must be called with ThreadBase::mLock held
1854int AudioFlinger::DirectOutputThread::getTrackName_l()
1855{
1856 return 0;
1857}
1858
1859// deleteTrackName_l() must be called with ThreadBase::mLock held
1860void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1861{
1862}
1863
1864// checkForNewParameters_l() must be called with ThreadBase::mLock held
1865bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1866{
1867 bool reconfig = false;
1868
Eric Laurent3464c012009-08-04 09:45:33 -07001869 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001870 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001871 String8 keyValuePair = mNewParameters[0];
1872 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001873 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001874
Eric Laurent9d91ad52009-07-17 12:17:14 -07001875 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1876 // do not accept frame count changes if tracks are open as the track buffer
1877 // size depends on frame count and correct behavior would not be garantied
1878 // if frame count is changed after track creation
1879 if (!mTracks.isEmpty()) {
1880 status = INVALID_OPERATION;
1881 } else {
1882 reconfig = true;
1883 }
1884 }
1885 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001886 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001887 if (!mStandby && status == INVALID_OPERATION) {
1888 mOutput->standby();
1889 mStandby = true;
1890 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001891 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001892 }
1893 if (status == NO_ERROR && reconfig) {
1894 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001895 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001896 }
1897 }
Eric Laurentee47d432009-11-07 00:01:32 -08001898
1899 mNewParameters.removeAt(0);
1900
Eric Laurent9d91ad52009-07-17 12:17:14 -07001901 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001902 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001903 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001904 }
1905 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001906}
1907
Eric Laurentf5e868b2009-10-05 20:29:18 -07001908uint32_t AudioFlinger::DirectOutputThread::getMaxBufferRecoveryInUsecs()
1909{
1910 uint32_t time;
1911 if (AudioSystem::isLinearPCM(mFormat)) {
1912 time = ((mFrameCount * 1000) / mSampleRate) * 1000;
1913 // Add some margin with regard to scheduling precision
1914 if (time > 10000) {
1915 time -= 10000;
1916 }
1917 } else {
1918 time = 10000;
1919 }
1920 return time;
1921}
1922
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001923// ----------------------------------------------------------------------------
1924
Eric Laurent9d91ad52009-07-17 12:17:14 -07001925AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1926 : MixerThread(audioFlinger, mainThread->getOutput())
1927{
1928 mType = PlaybackThread::DUPLICATING;
1929 addOutputTrack(mainThread);
1930}
1931
1932AudioFlinger::DuplicatingThread::~DuplicatingThread()
1933{
1934 mOutputTracks.clear();
1935}
1936
1937bool AudioFlinger::DuplicatingThread::threadLoop()
1938{
Eric Laurent134aa9c2009-10-30 11:09:39 -07001939 uint32_t sleepTime = 1000;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001940 uint32_t maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001941 int16_t* curBuf = mMixBuffer;
1942 Vector< sp<Track> > tracksToRemove;
1943 size_t enabledTracks = 0;
1944 nsecs_t standbyTime = systemTime();
1945 size_t mixBufferSize = mFrameCount*mFrameSize;
1946 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001947 uint32_t writeFrames = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001948
1949 while (!exitPending())
1950 {
1951 processConfigEvents();
1952
1953 enabledTracks = 0;
1954 { // scope for the mLock
1955
1956 Mutex::Autolock _l(mLock);
1957
1958 if (checkForNewParameters_l()) {
1959 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001960 maxBufferRecoveryInUsecs = getMaxBufferRecoveryInUsecs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001961 }
1962
1963 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1964
1965 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1966 outputTracks.add(mOutputTracks[i]);
1967 }
1968
1969 // put audio hardware into standby after short delay
1970 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1971 mSuspended) {
1972 if (!mStandby) {
1973 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001974 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001975 }
1976 mStandby = true;
1977 mBytesWritten = 0;
1978 }
1979
1980 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1981 // we're about to wait, flush the binder command buffer
1982 IPCThreadState::self()->flushCommands();
1983 outputTracks.clear();
1984
1985 if (exitPending()) break;
1986
1987 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1988 mWaitWorkCV.wait(mLock);
1989 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1990 if (mMasterMute == false) {
1991 char value[PROPERTY_VALUE_MAX];
1992 property_get("ro.audio.silent", value, "0");
1993 if (atoi(value)) {
1994 LOGD("Silence is golden");
1995 setMasterMute(true);
1996 }
1997 }
1998
1999 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent134aa9c2009-10-30 11:09:39 -07002000 sleepTime = 1000;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002001 continue;
2002 }
2003 }
2004
2005 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurentaef692f2009-09-22 00:35:48 -07002006 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002007
Eric Laurent9d91ad52009-07-17 12:17:14 -07002008 if (LIKELY(enabledTracks)) {
2009 // mix buffers...
2010 mAudioMixer->process(curBuf);
Eric Laurentaef692f2009-09-22 00:35:48 -07002011 sleepTime = 0;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002012 writeFrames = mFrameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002013 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002014 if (sleepTime == 0) {
2015 sleepTime = maxBufferRecoveryInUsecs;
2016 } else if (mBytesWritten != 0) {
2017 // flush remaining overflow buffers in output tracks
2018 for (size_t i = 0; i < outputTracks.size(); i++) {
2019 if (outputTracks[i]->isActive()) {
2020 sleepTime = 0;
2021 writeFrames = 0;
2022 break;
2023 }
2024 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002025 }
2026 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002027
2028 if (mSuspended) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002029 sleepTime = maxBufferRecoveryInUsecs;
Eric Laurentaef692f2009-09-22 00:35:48 -07002030 }
2031 // sleepTime == 0 means we must write to audio hardware
2032 if (sleepTime == 0) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002033 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentaef692f2009-09-22 00:35:48 -07002034 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002035 outputTracks[i]->write(curBuf, writeFrames);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002036 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002037 mStandby = false;
2038 mBytesWritten += mixBufferSize;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002039 } else {
Eric Laurentaef692f2009-09-22 00:35:48 -07002040 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002041 }
2042
2043 // finally let go of all our tracks, without the lock held
2044 // since we can't guarantee the destructors won't acquire that
2045 // same lock.
2046 tracksToRemove.clear();
2047 outputTracks.clear();
2048 }
2049
Eric Laurentf5aba822009-08-10 23:22:32 -07002050 { // scope for the mLock
2051
2052 Mutex::Autolock _l(mLock);
2053 if (!mStandby) {
2054 LOGV("DuplicatingThread() exiting out of standby");
2055 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2056 mOutputTracks[i]->destroy();
2057 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002058 }
2059 }
2060
Eric Laurent9d91ad52009-07-17 12:17:14 -07002061 return false;
2062}
2063
2064void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2065{
2066 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2067 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
2068 mSampleRate,
2069 mFormat,
2070 mChannelCount,
2071 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07002072 if (outputTrack->cblk() != NULL) {
2073 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2074 mOutputTracks.add(outputTrack);
2075 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
2076 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002077}
2078
2079void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2080{
2081 Mutex::Autolock _l(mLock);
2082 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2083 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07002084 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002085 mOutputTracks.removeAt(i);
2086 return;
2087 }
2088 }
2089 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2090}
2091
Eric Laurent9d91ad52009-07-17 12:17:14 -07002092// ----------------------------------------------------------------------------
2093
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002094// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002095AudioFlinger::ThreadBase::TrackBase::TrackBase(
2096 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002097 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002098 uint32_t sampleRate,
2099 int format,
2100 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002101 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002103 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002104 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002105 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002106 mClient(client),
Eric Laurent6ad8c642009-09-09 05:16:08 -07002107 mCblk(0),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002108 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002109 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002110 mClientTid(-1),
2111 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002112 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002113{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002114 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2115
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002116 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002117 size_t size = sizeof(audio_track_cblk_t);
2118 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2119 if (sharedBuffer == 0) {
2120 size += bufferSize;
2121 }
2122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002123 if (client != NULL) {
2124 mCblkMemory = client->heap()->allocate(size);
2125 if (mCblkMemory != 0) {
2126 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2127 if (mCblk) { // construct the shared structure in-place.
2128 new(mCblk) audio_track_cblk_t();
2129 // clear all buffers
2130 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002131 mCblk->sampleRate = sampleRate;
2132 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133 if (sharedBuffer == 0) {
2134 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2135 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2136 // Force underrun condition to avoid false underrun callback until first data is
2137 // written to buffer
2138 mCblk->flowControlFlag = 1;
2139 } else {
2140 mBuffer = sharedBuffer->pointer();
2141 }
2142 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002143 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144 } else {
2145 LOGE("not enough memory for AudioTrack size=%u", size);
2146 client->heap()->dump("AudioTrack");
2147 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002148 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149 } else {
2150 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2151 if (mCblk) { // construct the shared structure in-place.
2152 new(mCblk) audio_track_cblk_t();
2153 // clear all buffers
2154 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002155 mCblk->sampleRate = sampleRate;
2156 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002157 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2158 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2159 // Force underrun condition to avoid false underrun callback until first data is
2160 // written to buffer
2161 mCblk->flowControlFlag = 1;
2162 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2163 }
2164 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002165}
2166
Eric Laurentbdc0f842009-09-16 06:02:45 -07002167AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002168{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002170 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2171 if (mClient == NULL) {
2172 delete mCblk;
2173 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002174 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002175 mCblkMemory.clear(); // and free the shared memory
Eric Laurent0f8ab672009-09-17 05:12:56 -07002176 if (mClient != NULL) {
2177 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2178 mClient.clear();
2179 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002180}
2181
Eric Laurentbdc0f842009-09-16 06:02:45 -07002182void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002183{
2184 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002185 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002186 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002187 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002188}
2189
Eric Laurentbdc0f842009-09-16 06:02:45 -07002190bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002191 bool result;
2192 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002193
2194 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002195 if (!result) {
2196 LOGV("stepServer failed acquiring cblk mutex");
2197 mFlags |= STEPSERVER_FAILED;
2198 }
2199 return result;
2200}
2201
Eric Laurentbdc0f842009-09-16 06:02:45 -07002202void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002203 audio_track_cblk_t* cblk = this->cblk();
2204
2205 cblk->user = 0;
2206 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002207 cblk->userBase = 0;
2208 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002210 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002211}
2212
Eric Laurentbdc0f842009-09-16 06:02:45 -07002213sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002214{
2215 return mCblkMemory;
2216}
2217
Eric Laurentbdc0f842009-09-16 06:02:45 -07002218int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002219 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002220}
2221
Eric Laurentbdc0f842009-09-16 06:02:45 -07002222int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002223 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002224}
2225
Eric Laurentbdc0f842009-09-16 06:02:45 -07002226void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002227 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002228 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2229 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002230
2231 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002232 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2233 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002234 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2235 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002236 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002237 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002238 return 0;
2239 }
2240
2241 return bufferStart;
2242}
2243
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002244// ----------------------------------------------------------------------------
2245
Eric Laurent9d91ad52009-07-17 12:17:14 -07002246// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2247AudioFlinger::PlaybackThread::Track::Track(
2248 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002249 const sp<Client>& client,
2250 int streamType,
2251 uint32_t sampleRate,
2252 int format,
2253 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002254 int frameCount,
2255 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002256 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2257 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002258{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002259 if (mCblk != NULL) {
2260 sp<ThreadBase> baseThread = thread.promote();
2261 if (baseThread != 0) {
2262 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2263 mName = playbackThread->getTrackName_l();
2264 }
2265 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2266 if (mName < 0) {
2267 LOGE("no more track names available");
2268 }
2269 mVolume[0] = 1.0f;
2270 mVolume[1] = 1.0f;
2271 mStreamType = streamType;
2272 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2273 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2274 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002275 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002276}
2277
Eric Laurent9d91ad52009-07-17 12:17:14 -07002278AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002279{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002280 LOGV("PlaybackThread::Track destructor");
2281 sp<ThreadBase> thread = mThread.promote();
2282 if (thread != 0) {
2283 Mutex::Autolock _l(thread->mLock);
2284 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002285 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002286}
2287
Eric Laurent9d91ad52009-07-17 12:17:14 -07002288void AudioFlinger::PlaybackThread::Track::destroy()
2289{
2290 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2291 // by removing it from mTracks vector, so there is a risk that this Tracks's
2292 // desctructor is called. As the destructor needs to lock mLock,
2293 // we must acquire a strong reference on this Track before locking mLock
2294 // here so that the destructor is called only when exiting this function.
2295 // On the other hand, as long as Track::destroy() is only called by
2296 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2297 // this Track with its member mTrack.
2298 sp<Track> keep(this);
2299 { // scope for mLock
2300 sp<ThreadBase> thread = mThread.promote();
2301 if (thread != 0) {
2302 Mutex::Autolock _l(thread->mLock);
2303 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2304 playbackThread->destroyTrack_l(this);
2305 }
2306 }
2307}
2308
2309void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002310{
Eric Laurentee47d432009-11-07 00:01:32 -08002311 snprintf(buffer, size, " %5d %5d %3u %3u %3u %04u %1d %1d %1d %5u %5u %5u %08x %08x\n",
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002312 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002314 mStreamType,
2315 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002316 mCblk->channels,
2317 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002318 mState,
2319 mMute,
2320 mFillingUpStatus,
2321 mCblk->sampleRate,
2322 mCblk->volume[0],
2323 mCblk->volume[1],
2324 mCblk->server,
2325 mCblk->user);
2326}
2327
Eric Laurent9d91ad52009-07-17 12:17:14 -07002328status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002329{
2330 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002331 uint32_t framesReady;
2332 uint32_t framesReq = buffer->frameCount;
2333
2334 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002335 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2336 if (!step()) goto getNextBuffer_exit;
2337 LOGV("stepServer recovered");
2338 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2339 }
2340
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002341 framesReady = cblk->framesReady();
2342
2343 if (LIKELY(framesReady)) {
2344 uint32_t s = cblk->server;
2345 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2346
2347 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2348 if (framesReq > framesReady) {
2349 framesReq = framesReady;
2350 }
2351 if (s + framesReq > bufferEnd) {
2352 framesReq = bufferEnd - s;
2353 }
2354
2355 buffer->raw = getBuffer(s, framesReq);
2356 if (buffer->raw == 0) goto getNextBuffer_exit;
2357
2358 buffer->frameCount = framesReq;
2359 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002360 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002361
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002362getNextBuffer_exit:
2363 buffer->raw = 0;
2364 buffer->frameCount = 0;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002365 LOGV("getNextBuffer() no more data for track %d on thread %p", mName, mThread.unsafe_get());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002366 return NOT_ENOUGH_DATA;
2367}
2368
Eric Laurent9d91ad52009-07-17 12:17:14 -07002369bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002370 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002371
2372 if (mCblk->framesReady() >= mCblk->frameCount ||
2373 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002374 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002375 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002376 return true;
2377 }
2378 return false;
2379}
2380
Eric Laurent9d91ad52009-07-17 12:17:14 -07002381status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002382{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002383 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2384 sp<ThreadBase> thread = mThread.promote();
2385 if (thread != 0) {
2386 Mutex::Autolock _l(thread->mLock);
2387 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2388 playbackThread->addTrack_l(this);
2389 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002390 return NO_ERROR;
2391}
2392
Eric Laurent9d91ad52009-07-17 12:17:14 -07002393void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002394{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002395 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2396 sp<ThreadBase> thread = mThread.promote();
2397 if (thread != 0) {
2398 Mutex::Autolock _l(thread->mLock);
2399 if (mState > STOPPED) {
2400 mState = STOPPED;
2401 // If the track is not active (PAUSED and buffers full), flush buffers
2402 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2403 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2404 reset();
2405 }
Eric Laurentf5e868b2009-10-05 20:29:18 -07002406 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002407 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002408 }
2409}
2410
Eric Laurent9d91ad52009-07-17 12:17:14 -07002411void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002412{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002413 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002414 sp<ThreadBase> thread = mThread.promote();
2415 if (thread != 0) {
2416 Mutex::Autolock _l(thread->mLock);
2417 if (mState == ACTIVE || mState == RESUMING) {
2418 mState = PAUSING;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002419 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002420 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002421 }
2422}
2423
Eric Laurent9d91ad52009-07-17 12:17:14 -07002424void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002425{
2426 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002427 sp<ThreadBase> thread = mThread.promote();
2428 if (thread != 0) {
2429 Mutex::Autolock _l(thread->mLock);
2430 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2431 return;
2432 }
2433 // No point remaining in PAUSED state after a flush => go to
2434 // STOPPED state
2435 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002436
Eric Laurent9d91ad52009-07-17 12:17:14 -07002437 mCblk->lock.lock();
2438 // NOTE: reset() will reset cblk->user and cblk->server with
2439 // the risk that at the same time, the AudioMixer is trying to read
2440 // data. In this case, getNextBuffer() would return a NULL pointer
2441 // as audio buffer => the AudioMixer code MUST always test that pointer
2442 // returned by getNextBuffer() is not NULL!
2443 reset();
2444 mCblk->lock.unlock();
2445 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002446}
2447
Eric Laurent9d91ad52009-07-17 12:17:14 -07002448void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002449{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002450 // Do not reset twice to avoid discarding data written just after a flush and before
2451 // the audioflinger thread detects the track is stopped.
2452 if (!mResetDone) {
2453 TrackBase::reset();
2454 // Force underrun condition to avoid false underrun callback until first data is
2455 // written to buffer
2456 mCblk->flowControlFlag = 1;
2457 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002458 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002459 mResetDone = true;
2460 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002461}
2462
Eric Laurent9d91ad52009-07-17 12:17:14 -07002463void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002464{
2465 mMute = muted;
2466}
2467
Eric Laurent9d91ad52009-07-17 12:17:14 -07002468void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002469{
2470 mVolume[0] = left;
2471 mVolume[1] = right;
2472}
2473
2474// ----------------------------------------------------------------------------
2475
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002476// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002477AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2478 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 uint32_t sampleRate,
2481 int format,
2482 int channelCount,
2483 int frameCount,
2484 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002485 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002487 mOverflow(false)
2488{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002489 if (mCblk != NULL) {
2490 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2491 if (format == AudioSystem::PCM_16_BIT) {
2492 mCblk->frameSize = channelCount * sizeof(int16_t);
2493 } else if (format == AudioSystem::PCM_8_BIT) {
2494 mCblk->frameSize = channelCount * sizeof(int8_t);
2495 } else {
2496 mCblk->frameSize = sizeof(int8_t);
2497 }
2498 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002499}
2500
2501AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502{
2503}
2504
Eric Laurent9d91ad52009-07-17 12:17:14 -07002505status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506{
2507 audio_track_cblk_t* cblk = this->cblk();
2508 uint32_t framesAvail;
2509 uint32_t framesReq = buffer->frameCount;
2510
2511 // Check if last stepServer failed, try to step now
2512 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2513 if (!step()) goto getNextBuffer_exit;
2514 LOGV("stepServer recovered");
2515 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2516 }
2517
2518 framesAvail = cblk->framesAvailable_l();
2519
2520 if (LIKELY(framesAvail)) {
2521 uint32_t s = cblk->server;
2522 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2523
2524 if (framesReq > framesAvail) {
2525 framesReq = framesAvail;
2526 }
2527 if (s + framesReq > bufferEnd) {
2528 framesReq = bufferEnd - s;
2529 }
2530
2531 buffer->raw = getBuffer(s, framesReq);
2532 if (buffer->raw == 0) goto getNextBuffer_exit;
2533
2534 buffer->frameCount = framesReq;
2535 return NO_ERROR;
2536 }
2537
2538getNextBuffer_exit:
2539 buffer->raw = 0;
2540 buffer->frameCount = 0;
2541 return NOT_ENOUGH_DATA;
2542}
2543
Eric Laurent9d91ad52009-07-17 12:17:14 -07002544status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002546 sp<ThreadBase> thread = mThread.promote();
2547 if (thread != 0) {
2548 RecordThread *recordThread = (RecordThread *)thread.get();
2549 return recordThread->start(this);
2550 }
2551 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002552}
2553
Eric Laurent9d91ad52009-07-17 12:17:14 -07002554void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002556 sp<ThreadBase> thread = mThread.promote();
2557 if (thread != 0) {
2558 RecordThread *recordThread = (RecordThread *)thread.get();
2559 recordThread->stop(this);
2560 TrackBase::reset();
2561 // Force overerrun condition to avoid false overrun callback until first data is
2562 // read from buffer
2563 mCblk->flowControlFlag = 1;
2564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565}
2566
Eric Laurentee47d432009-11-07 00:01:32 -08002567void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
2568{
2569 snprintf(buffer, size, " %05d %03u %03u %04u %01d %05u %08x %08x\n",
2570 (mClient == NULL) ? getpid() : mClient->pid(),
2571 mFormat,
2572 mCblk->channels,
2573 mFrameCount,
2574 mState,
2575 mCblk->sampleRate,
2576 mCblk->server,
2577 mCblk->user);
2578}
2579
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002580
2581// ----------------------------------------------------------------------------
2582
Eric Laurent9d91ad52009-07-17 12:17:14 -07002583AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2584 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 uint32_t sampleRate,
2586 int format,
2587 int channelCount,
2588 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002589 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2590 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002592
2593 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002594 if (mCblk != NULL) {
2595 mCblk->out = 1;
2596 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2597 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2598 mOutBuffer.frameCount = 0;
2599 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2600 playbackThread->mTracks.add(this);
2601 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2602 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2603 } else {
2604 LOGW("Error creating output track on thread %p", playbackThread);
2605 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606}
2607
Eric Laurent9d91ad52009-07-17 12:17:14 -07002608AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002609{
Eric Laurentf5aba822009-08-10 23:22:32 -07002610 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611}
2612
Eric Laurent9d91ad52009-07-17 12:17:14 -07002613status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614{
2615 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002616 if (status != NO_ERROR) {
2617 return status;
2618 }
2619
2620 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 mRetryCount = 127;
2622 return status;
2623}
2624
Eric Laurent9d91ad52009-07-17 12:17:14 -07002625void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626{
2627 Track::stop();
2628 clearBufferQueue();
2629 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002630 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631}
2632
Eric Laurent9d91ad52009-07-17 12:17:14 -07002633bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634{
2635 Buffer *pInBuffer;
2636 Buffer inBuffer;
2637 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002638 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 inBuffer.frameCount = frames;
2640 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002641
2642 uint32_t waitTimeLeftMs = mWaitTimeMs;
2643
Eric Laurentf5e868b2009-10-05 20:29:18 -07002644 if (!mActive && frames != 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002645 start();
2646 sp<ThreadBase> thread = mThread.promote();
2647 if (thread != 0) {
2648 MixerThread *mixerThread = (MixerThread *)thread.get();
2649 if (mCblk->frameCount > frames){
2650 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2651 uint32_t startFrames = (mCblk->frameCount - frames);
2652 pInBuffer = new Buffer;
2653 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2654 pInBuffer->frameCount = startFrames;
2655 pInBuffer->i16 = pInBuffer->mBuffer;
2656 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2657 mBufferQueue.add(pInBuffer);
2658 } else {
2659 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2660 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 }
2664
Eric Laurent9d91ad52009-07-17 12:17:14 -07002665 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666 // First write pending buffers, then new data
2667 if (mBufferQueue.size()) {
2668 pInBuffer = mBufferQueue.itemAt(0);
2669 } else {
2670 pInBuffer = &inBuffer;
2671 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002672
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673 if (pInBuffer->frameCount == 0) {
2674 break;
2675 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002676
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 if (mOutBuffer.frameCount == 0) {
2678 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002679 nsecs_t startTime = systemTime();
2680 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2681 LOGV ("OutputTrack::write() %p no more output buffers", this);
2682 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683 break;
2684 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002685 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurentf5e868b2009-10-05 20:29:18 -07002686 LOGV("OutputTrack::write() to thread %p waitTimeMs %d waitTimeLeftMs %d", mThread.unsafe_get(), waitTimeMs, waitTimeLeftMs);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002687 if (waitTimeLeftMs >= waitTimeMs) {
2688 waitTimeLeftMs -= waitTimeMs;
2689 } else {
2690 waitTimeLeftMs = 0;
2691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002693
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2695 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2696 mCblk->stepUser(outFrames);
2697 pInBuffer->frameCount -= outFrames;
2698 pInBuffer->i16 += outFrames * channels;
2699 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002700 mOutBuffer.i16 += outFrames * channels;
2701
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 if (pInBuffer->frameCount == 0) {
2703 if (mBufferQueue.size()) {
2704 mBufferQueue.removeAt(0);
2705 delete [] pInBuffer->mBuffer;
2706 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002707 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 } else {
2709 break;
2710 }
2711 }
2712 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002714 // If we could not write all frames, allocate a buffer and queue it for next time.
2715 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002716 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 pInBuffer = new Buffer;
2718 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2719 pInBuffer->frameCount = inBuffer.frameCount;
2720 pInBuffer->i16 = pInBuffer->mBuffer;
2721 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2722 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002723 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002725 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726 }
2727 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002728
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002730 // 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 -08002731 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002732 if (frames == 0 && mBufferQueue.size() == 0) {
2733 if (mCblk->user < mCblk->frameCount) {
2734 frames = mCblk->frameCount - mCblk->user;
2735 pInBuffer = new Buffer;
2736 pInBuffer->mBuffer = new int16_t[frames * channels];
2737 pInBuffer->frameCount = frames;
2738 pInBuffer->i16 = pInBuffer->mBuffer;
2739 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2740 mBufferQueue.add(pInBuffer);
Eric Laurentf5e868b2009-10-05 20:29:18 -07002741 } else if (mActive) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002742 stop();
2743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 }
2745
Eric Laurent9d91ad52009-07-17 12:17:14 -07002746 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747}
2748
Eric Laurent9d91ad52009-07-17 12:17:14 -07002749status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750{
2751 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 status_t result;
2753 audio_track_cblk_t* cblk = mCblk;
2754 uint32_t framesReq = buffer->frameCount;
2755
Eric Laurent9d91ad52009-07-17 12:17:14 -07002756// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 uint32_t framesAvail = cblk->framesAvailable();
2760
Eric Laurent9d91ad52009-07-17 12:17:14 -07002761
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002763 Mutex::Autolock _l(cblk->lock);
2764 goto start_loop_here;
2765 while (framesAvail == 0) {
2766 active = mActive;
2767 if (UNLIKELY(!active)) {
2768 LOGV("Not active and NO_MORE_BUFFERS");
2769 return AudioTrack::NO_MORE_BUFFERS;
2770 }
2771 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2772 if (result != NO_ERROR) {
2773 return AudioTrack::NO_MORE_BUFFERS;
2774 }
2775 // read the server count again
2776 start_loop_here:
2777 framesAvail = cblk->framesAvailable_l();
2778 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 }
2780
Eric Laurent9d91ad52009-07-17 12:17:14 -07002781// if (framesAvail < framesReq) {
2782// return AudioTrack::NO_MORE_BUFFERS;
2783// }
2784
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002785 if (framesReq > framesAvail) {
2786 framesReq = framesAvail;
2787 }
2788
2789 uint32_t u = cblk->user;
2790 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2791
2792 if (u + framesReq > bufferEnd) {
2793 framesReq = bufferEnd - u;
2794 }
2795
2796 buffer->frameCount = framesReq;
2797 buffer->raw = (void *)cblk->buffer(u);
2798 return NO_ERROR;
2799}
2800
2801
Eric Laurent9d91ad52009-07-17 12:17:14 -07002802void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803{
2804 size_t size = mBufferQueue.size();
2805 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002806
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807 for (size_t i = 0; i < size; i++) {
2808 pBuffer = mBufferQueue.itemAt(i);
2809 delete [] pBuffer->mBuffer;
2810 delete pBuffer;
2811 }
2812 mBufferQueue.clear();
2813}
2814
2815// ----------------------------------------------------------------------------
2816
2817AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2818 : RefBase(),
2819 mAudioFlinger(audioFlinger),
2820 mMemoryDealer(new MemoryDealer(1024*1024)),
2821 mPid(pid)
2822{
2823 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2824}
2825
Eric Laurent0f8ab672009-09-17 05:12:56 -07002826// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827AudioFlinger::Client::~Client()
2828{
Eric Laurent0f8ab672009-09-17 05:12:56 -07002829 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830}
2831
2832const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2833{
2834 return mMemoryDealer;
2835}
2836
2837// ----------------------------------------------------------------------------
2838
Eric Laurent9d91ad52009-07-17 12:17:14 -07002839AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002840 : BnAudioTrack(),
2841 mTrack(track)
2842{
2843}
2844
2845AudioFlinger::TrackHandle::~TrackHandle() {
2846 // just stop the track on deletion, associated resources
2847 // will be freed from the main thread once all pending buffers have
2848 // been played. Unless it's not in the active track list, in which
2849 // case we free everything now...
2850 mTrack->destroy();
2851}
2852
2853status_t AudioFlinger::TrackHandle::start() {
2854 return mTrack->start();
2855}
2856
2857void AudioFlinger::TrackHandle::stop() {
2858 mTrack->stop();
2859}
2860
2861void AudioFlinger::TrackHandle::flush() {
2862 mTrack->flush();
2863}
2864
2865void AudioFlinger::TrackHandle::mute(bool e) {
2866 mTrack->mute(e);
2867}
2868
2869void AudioFlinger::TrackHandle::pause() {
2870 mTrack->pause();
2871}
2872
2873void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2874 mTrack->setVolume(left, right);
2875}
2876
2877sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2878 return mTrack->getCblk();
2879}
2880
2881status_t AudioFlinger::TrackHandle::onTransact(
2882 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2883{
2884 return BnAudioTrack::onTransact(code, data, reply, flags);
2885}
2886
2887// ----------------------------------------------------------------------------
2888
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002889sp<IAudioRecord> AudioFlinger::openRecord(
2890 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002891 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002892 uint32_t sampleRate,
2893 int format,
2894 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002895 int frameCount,
2896 uint32_t flags,
2897 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002898{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002899 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002900 sp<RecordHandle> recordHandle;
2901 sp<Client> client;
2902 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002903 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002904 RecordThread *thread;
2905 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002906
2907 // check calling permissions
2908 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002909 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002910 goto Exit;
2911 }
2912
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002913 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002914 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002915 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002916 thread = checkRecordThread_l(input);
2917 if (thread == NULL) {
2918 lStatus = BAD_VALUE;
2919 goto Exit;
2920 }
2921
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002922 wclient = mClients.valueFor(pid);
2923 if (wclient != NULL) {
2924 client = wclient.promote();
2925 } else {
2926 client = new Client(this, pid);
2927 mClients.add(pid, client);
2928 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002929
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002930 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002931 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002932 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002933 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934 if (recordTrack->getCblk() == NULL) {
Eric Laurent0f8ab672009-09-17 05:12:56 -07002935 // remove local strong reference to Client before deleting the RecordTrack so that the Client
2936 // destructor is called by the TrackBase destructor with mLock held
2937 client.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938 recordTrack.clear();
2939 lStatus = NO_MEMORY;
2940 goto Exit;
2941 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002942
2943 // return to handle to client
2944 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002945 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002946
2947Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002948 if (status) {
2949 *status = lStatus;
2950 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002951 return recordHandle;
2952}
2953
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002954// ----------------------------------------------------------------------------
2955
Eric Laurent9d91ad52009-07-17 12:17:14 -07002956AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002957 : BnAudioRecord(),
2958 mRecordTrack(recordTrack)
2959{
2960}
2961
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002962AudioFlinger::RecordHandle::~RecordHandle() {
2963 stop();
2964}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002965
2966status_t AudioFlinger::RecordHandle::start() {
2967 LOGV("RecordHandle::start()");
2968 return mRecordTrack->start();
2969}
2970
2971void AudioFlinger::RecordHandle::stop() {
2972 LOGV("RecordHandle::stop()");
2973 mRecordTrack->stop();
2974}
2975
2976sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2977 return mRecordTrack->getCblk();
2978}
2979
2980status_t AudioFlinger::RecordHandle::onTransact(
2981 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2982{
2983 return BnAudioRecord::onTransact(code, data, reply, flags);
2984}
2985
2986// ----------------------------------------------------------------------------
2987
Eric Laurent9d91ad52009-07-17 12:17:14 -07002988AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2989 ThreadBase(audioFlinger),
2990 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002991{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002992 mReqChannelCount = AudioSystem::popCount(channels);
2993 mReqSampleRate = sampleRate;
2994 readInputParameters();
2995 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002996}
2997
Eric Laurent9d91ad52009-07-17 12:17:14 -07002998
2999AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003000{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003001 delete[] mRsmpInBuffer;
3002 if (mResampler != 0) {
3003 delete mResampler;
3004 delete[] mRsmpOutBuffer;
3005 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003006}
3007
Eric Laurent9d91ad52009-07-17 12:17:14 -07003008void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003009{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003010 const size_t SIZE = 256;
3011 char buffer[SIZE];
3012
3013 snprintf(buffer, SIZE, "Record Thread %p", this);
3014
3015 run(buffer, PRIORITY_URGENT_AUDIO);
3016}
3017bool AudioFlinger::RecordThread::threadLoop()
3018{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003019 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003020 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003021
3022 // start recording
3023 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003024
Eric Laurent9d91ad52009-07-17 12:17:14 -07003025 processConfigEvents();
3026
3027 { // scope for mLock
3028 Mutex::Autolock _l(mLock);
3029 checkForNewParameters_l();
3030 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3031 if (!mStandby) {
3032 mInput->standby();
3033 mStandby = true;
3034 }
3035
3036 if (exitPending()) break;
3037
3038 LOGV("RecordThread: loop stopping");
3039 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003040 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003041 LOGV("RecordThread: loop starting");
3042 continue;
3043 }
3044 if (mActiveTrack != 0) {
3045 if (mActiveTrack->mState == TrackBase::PAUSING) {
3046 mActiveTrack.clear();
3047 mStartStopCond.broadcast();
3048 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
3049 mRsmpInIndex = mFrameCount;
3050 if (mReqChannelCount != mActiveTrack->channelCount()) {
3051 mActiveTrack.clear();
3052 } else {
Eric Laurent9e7b8192009-08-10 02:41:54 -07003053 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003054 }
3055 mStartStopCond.broadcast();
3056 }
3057 mStandby = false;
3058 }
3059 }
3060
3061 if (mActiveTrack != 0) {
3062 buffer.frameCount = mFrameCount;
3063 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3064 size_t framesOut = buffer.frameCount;
3065 if (mResampler == 0) {
3066 // no resampling
3067 while (framesOut) {
3068 size_t framesIn = mFrameCount - mRsmpInIndex;
3069 if (framesIn) {
3070 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3071 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3072 if (framesIn > framesOut)
3073 framesIn = framesOut;
3074 mRsmpInIndex += framesIn;
3075 framesOut -= framesIn;
3076 if (mChannelCount == mReqChannelCount ||
3077 mFormat != AudioSystem::PCM_16_BIT) {
3078 memcpy(dst, src, framesIn * mFrameSize);
3079 } else {
3080 int16_t *src16 = (int16_t *)src;
3081 int16_t *dst16 = (int16_t *)dst;
3082 if (mChannelCount == 1) {
3083 while (framesIn--) {
3084 *dst16++ = *src16;
3085 *dst16++ = *src16++;
3086 }
3087 } else {
3088 while (framesIn--) {
3089 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3090 src16 += 2;
3091 }
3092 }
3093 }
3094 }
3095 if (framesOut && mFrameCount == mRsmpInIndex) {
3096 ssize_t bytesRead;
3097 if (framesOut == mFrameCount &&
3098 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
3099 bytesRead = mInput->read(buffer.raw, mInputBytes);
3100 framesOut = 0;
3101 } else {
3102 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3103 mRsmpInIndex = 0;
3104 }
3105 if (bytesRead < 0) {
3106 LOGE("Error reading audio input");
3107 sleep(1);
3108 mRsmpInIndex = mFrameCount;
3109 framesOut = 0;
3110 buffer.frameCount = 0;
3111 }
3112 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003113 }
3114 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003115 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003116
Eric Laurent9d91ad52009-07-17 12:17:14 -07003117 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3118 // alter output frame count as if we were expecting stereo samples
3119 if (mChannelCount == 1 && mReqChannelCount == 1) {
3120 framesOut >>= 1;
3121 }
3122 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3123 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3124 // are 32 bit aligned which should be always true.
3125 if (mChannelCount == 2 && mReqChannelCount == 1) {
3126 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3127 // the resampler always outputs stereo samples: do post stereo to mono conversion
3128 int16_t *src = (int16_t *)mRsmpOutBuffer;
3129 int16_t *dst = buffer.i16;
3130 while (framesOut--) {
3131 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3132 src += 2;
3133 }
3134 } else {
3135 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3136 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003137
Eric Laurent9d91ad52009-07-17 12:17:14 -07003138 }
3139 mActiveTrack->releaseBuffer(&buffer);
3140 mActiveTrack->overflow();
3141 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003142 // client isn't retrieving buffers fast enough
3143 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003144 if (!mActiveTrack->setOverflow())
3145 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003146 // Release the processor for a while before asking for a new buffer.
3147 // This will give the application more chance to read from the buffer and
3148 // clear the overflow.
3149 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003150 }
3151 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003152 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003153
Eric Laurent9d91ad52009-07-17 12:17:14 -07003154 if (!mStandby) {
3155 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003156 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003157 mActiveTrack.clear();
3158
Eric Laurent9d91ad52009-07-17 12:17:14 -07003159 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003160 return false;
3161}
3162
Eric Laurent9d91ad52009-07-17 12:17:14 -07003163status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003164{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003165 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003166 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003167
Eric Laurent9d91ad52009-07-17 12:17:14 -07003168 if (mActiveTrack != 0) {
3169 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003170
Eric Laurent9d91ad52009-07-17 12:17:14 -07003171 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003172
Eric Laurent9d91ad52009-07-17 12:17:14 -07003173 return NO_ERROR;
3174 }
3175
3176 mActiveTrack = recordTrack;
3177 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003178 // signal thread to start
3179 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003180 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003181 mStartStopCond.wait(mLock);
3182 if (mActiveTrack != 0) {
3183 LOGV("Record started OK");
3184 return NO_ERROR;
3185 } else {
3186 LOGV("Record failed to start");
3187 return BAD_VALUE;
3188 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003189}
3190
Eric Laurent9d91ad52009-07-17 12:17:14 -07003191void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3192 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003193 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003194 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3195 mActiveTrack->mState = TrackBase::PAUSING;
3196 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003197 }
3198}
3199
Eric Laurent9d91ad52009-07-17 12:17:14 -07003200status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201{
3202 const size_t SIZE = 256;
3203 char buffer[SIZE];
3204 String8 result;
3205 pid_t pid = 0;
3206
Eric Laurentee47d432009-11-07 00:01:32 -08003207 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3208 result.append(buffer);
3209
3210 if (mActiveTrack != 0) {
3211 result.append("Active Track:\n");
3212 result.append(" Clien Fmt Chn Buf S SRate Serv User\n");
3213 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -08003215
3216 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3217 result.append(buffer);
3218 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3219 result.append(buffer);
3220 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3221 result.append(buffer);
3222 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3223 result.append(buffer);
3224 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3225 result.append(buffer);
3226
3227
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 } else {
3229 result.append("No record client\n");
3230 }
3231 write(fd, result.string(), result.size());
Eric Laurentee47d432009-11-07 00:01:32 -08003232
3233 dumpBase(fd, args);
3234
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 return NO_ERROR;
3236}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003237
Eric Laurent9d91ad52009-07-17 12:17:14 -07003238status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3239{
3240 size_t framesReq = buffer->frameCount;
3241 size_t framesReady = mFrameCount - mRsmpInIndex;
3242 int channelCount;
3243
3244 if (framesReady == 0) {
3245 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3246 if (bytesRead < 0) {
3247 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3248 sleep(1);
3249 buffer->raw = 0;
3250 buffer->frameCount = 0;
3251 return NOT_ENOUGH_DATA;
3252 }
3253 mRsmpInIndex = 0;
3254 framesReady = mFrameCount;
3255 }
3256
3257 if (framesReq > framesReady) {
3258 framesReq = framesReady;
3259 }
3260
3261 if (mChannelCount == 1 && mReqChannelCount == 2) {
3262 channelCount = 1;
3263 } else {
3264 channelCount = 2;
3265 }
3266 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3267 buffer->frameCount = framesReq;
3268 return NO_ERROR;
3269}
3270
3271void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3272{
3273 mRsmpInIndex += buffer->frameCount;
3274 buffer->frameCount = 0;
3275}
3276
3277bool AudioFlinger::RecordThread::checkForNewParameters_l()
3278{
3279 bool reconfig = false;
3280
Eric Laurent3464c012009-08-04 09:45:33 -07003281 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003282 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003283 String8 keyValuePair = mNewParameters[0];
3284 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003285 int value;
3286 int reqFormat = mFormat;
3287 int reqSamplingRate = mReqSampleRate;
3288 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003289
Eric Laurent9d91ad52009-07-17 12:17:14 -07003290 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3291 reqSamplingRate = value;
3292 reconfig = true;
3293 }
3294 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3295 reqFormat = value;
3296 reconfig = true;
3297 }
3298 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3299 reqChannelCount = AudioSystem::popCount(value);
3300 reconfig = true;
3301 }
3302 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3303 // do not accept frame count changes if tracks are open as the track buffer
3304 // size depends on frame count and correct behavior would not be garantied
3305 // if frame count is changed after track creation
3306 if (mActiveTrack != 0) {
3307 status = INVALID_OPERATION;
3308 } else {
3309 reconfig = true;
3310 }
3311 }
3312 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003313 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003314 if (status == INVALID_OPERATION) {
3315 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003316 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003317 }
3318 if (reconfig) {
3319 if (status == BAD_VALUE &&
3320 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3321 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3322 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3323 status = NO_ERROR;
3324 }
3325 if (status == NO_ERROR) {
3326 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003327 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003328 }
3329 }
3330 }
Eric Laurentee47d432009-11-07 00:01:32 -08003331
3332 mNewParameters.removeAt(0);
3333
Eric Laurent9d91ad52009-07-17 12:17:14 -07003334 mParamStatus = status;
3335 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003336 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003337 }
3338 return reconfig;
3339}
3340
3341String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3342{
3343 return mInput->getParameters(keys);
3344}
3345
3346void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3347 AudioSystem::OutputDescriptor desc;
3348 void *param2 = 0;
3349
3350 switch (event) {
3351 case AudioSystem::INPUT_OPENED:
3352 case AudioSystem::INPUT_CONFIG_CHANGED:
3353 desc.channels = mChannelCount;
3354 desc.samplingRate = mSampleRate;
3355 desc.format = mFormat;
3356 desc.frameCount = mFrameCount;
3357 desc.latency = 0;
3358 param2 = &desc;
3359 break;
3360
3361 case AudioSystem::INPUT_CLOSED:
3362 default:
3363 break;
3364 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003365 Mutex::Autolock _l(mAudioFlinger->mLock);
3366 mAudioFlinger->audioConfigChanged_l(event, this, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003367}
3368
3369void AudioFlinger::RecordThread::readInputParameters()
3370{
3371 if (mRsmpInBuffer) delete mRsmpInBuffer;
3372 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3373 if (mResampler) delete mResampler;
3374 mResampler = 0;
3375
3376 mSampleRate = mInput->sampleRate();
3377 mChannelCount = AudioSystem::popCount(mInput->channels());
3378 mFormat = mInput->format();
3379 mFrameSize = mInput->frameSize();
3380 mInputBytes = mInput->bufferSize();
3381 mFrameCount = mInputBytes / mFrameSize;
3382 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3383
3384 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3385 {
3386 int channelCount;
3387 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3388 // stereo to mono post process as the resampler always outputs stereo.
3389 if (mChannelCount == 1 && mReqChannelCount == 2) {
3390 channelCount = 1;
3391 } else {
3392 channelCount = 2;
3393 }
3394 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3395 mResampler->setSampleRate(mSampleRate);
3396 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3397 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3398
3399 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3400 if (mChannelCount == 1 && mReqChannelCount == 1) {
3401 mFrameCount >>= 1;
3402 }
3403
3404 }
3405 mRsmpInIndex = mFrameCount;
3406}
3407
3408// ----------------------------------------------------------------------------
3409
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003410int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003411 uint32_t *pSamplingRate,
3412 uint32_t *pFormat,
3413 uint32_t *pChannels,
3414 uint32_t *pLatencyMs,
3415 uint32_t flags)
3416{
3417 status_t status;
3418 PlaybackThread *thread = NULL;
3419 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3420 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3421 uint32_t format = pFormat ? *pFormat : 0;
3422 uint32_t channels = pChannels ? *pChannels : 0;
3423 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3424
3425 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3426 pDevices ? *pDevices : 0,
3427 samplingRate,
3428 format,
3429 channels,
3430 flags);
3431
3432 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003433 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003434 }
3435 Mutex::Autolock _l(mLock);
3436
3437 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3438 (int *)&format,
3439 &channels,
3440 &samplingRate,
3441 &status);
3442 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3443 output,
3444 samplingRate,
3445 format,
3446 channels,
3447 status);
3448
3449 mHardwareStatus = AUDIO_HW_IDLE;
3450 if (output != 0) {
3451 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3452 (format != AudioSystem::PCM_16_BIT) ||
3453 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3454 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003455 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003456 } else {
3457 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003458 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003459 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003460 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003461
3462 if (pSamplingRate) *pSamplingRate = samplingRate;
3463 if (pFormat) *pFormat = format;
3464 if (pChannels) *pChannels = channels;
3465 if (pLatencyMs) *pLatencyMs = thread->latency();
3466 }
3467
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003468 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003469}
3470
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003471int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003472{
3473 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003474 MixerThread *thread1 = checkMixerThread_l(output1);
3475 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003476
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003477 if (thread1 == NULL || thread2 == NULL) {
3478 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3479 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003480 }
3481
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003482
3483 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3484 thread->addOutputTrack(thread2);
3485 mPlaybackThreads.add(++mNextThreadId, thread);
3486 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003487}
3488
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003489status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003490{
Eric Laurentdae20d92009-08-04 08:37:05 -07003491 // keep strong reference on the playback thread so that
3492 // it is not destroyed while exit() is executed
3493 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003494 {
3495 Mutex::Autolock _l(mLock);
3496 thread = checkPlaybackThread_l(output);
3497 if (thread == NULL) {
3498 return BAD_VALUE;
3499 }
3500
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003501 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003502
3503 if (thread->type() == PlaybackThread::MIXER) {
3504 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003505 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3506 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003507 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003508 }
3509 }
3510 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003511 void *param2 = 0;
3512 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, thread, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003513 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003514 }
3515 thread->exit();
3516
Eric Laurentdae20d92009-08-04 08:37:05 -07003517 if (thread->type() != PlaybackThread::DUPLICATING) {
3518 mAudioHardware->closeOutputStream(thread->getOutput());
3519 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003520 return NO_ERROR;
3521}
3522
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003523status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003524{
3525 Mutex::Autolock _l(mLock);
3526 PlaybackThread *thread = checkPlaybackThread_l(output);
3527
3528 if (thread == NULL) {
3529 return BAD_VALUE;
3530 }
3531
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003532 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003533 thread->suspend();
3534
3535 return NO_ERROR;
3536}
3537
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003538status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003539{
3540 Mutex::Autolock _l(mLock);
3541 PlaybackThread *thread = checkPlaybackThread_l(output);
3542
3543 if (thread == NULL) {
3544 return BAD_VALUE;
3545 }
3546
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003547 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003548
3549 thread->restore();
3550
3551 return NO_ERROR;
3552}
3553
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003554int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003555 uint32_t *pSamplingRate,
3556 uint32_t *pFormat,
3557 uint32_t *pChannels,
3558 uint32_t acoustics)
3559{
3560 status_t status;
3561 RecordThread *thread = NULL;
3562 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3563 uint32_t format = pFormat ? *pFormat : 0;
3564 uint32_t channels = pChannels ? *pChannels : 0;
3565 uint32_t reqSamplingRate = samplingRate;
3566 uint32_t reqFormat = format;
3567 uint32_t reqChannels = channels;
3568
3569 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003570 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003571 }
3572 Mutex::Autolock _l(mLock);
3573
3574 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3575 (int *)&format,
3576 &channels,
3577 &samplingRate,
3578 &status,
3579 (AudioSystem::audio_in_acoustics)acoustics);
3580 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3581 input,
3582 samplingRate,
3583 format,
3584 channels,
3585 acoustics,
3586 status);
3587
3588 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3589 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3590 // or stereo to mono conversions on 16 bit PCM inputs.
3591 if (input == 0 && status == BAD_VALUE &&
3592 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3593 (samplingRate <= 2 * reqSamplingRate) &&
3594 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3595 LOGV("openInput() reopening with proposed sampling rate and channels");
3596 input = mAudioHardware->openInputStream(*pDevices,
3597 (int *)&format,
3598 &channels,
3599 &samplingRate,
3600 &status,
3601 (AudioSystem::audio_in_acoustics)acoustics);
3602 }
3603
3604 if (input != 0) {
3605 // Start record thread
3606 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003607 mRecordThreads.add(++mNextThreadId, thread);
3608 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003609 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3610 if (pFormat) *pFormat = format;
3611 if (pChannels) *pChannels = reqChannels;
3612
3613 input->standby();
3614 }
3615
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003616 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003617}
3618
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003619status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003620{
Eric Laurentdae20d92009-08-04 08:37:05 -07003621 // keep strong reference on the record thread so that
3622 // it is not destroyed while exit() is executed
3623 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003624 {
3625 Mutex::Autolock _l(mLock);
3626 thread = checkRecordThread_l(input);
3627 if (thread == NULL) {
3628 return BAD_VALUE;
3629 }
3630
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003631 LOGV("closeInput() %d", input);
Eric Laurentb3687ae2009-09-15 07:10:12 -07003632 void *param2 = 0;
3633 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, thread, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003634 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003635 }
3636 thread->exit();
3637
Eric Laurentdae20d92009-08-04 08:37:05 -07003638 mAudioHardware->closeInputStream(thread->getInput());
3639
Eric Laurent9d91ad52009-07-17 12:17:14 -07003640 return NO_ERROR;
3641}
3642
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003643status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003644{
3645 Mutex::Autolock _l(mLock);
3646 MixerThread *dstThread = checkMixerThread_l(output);
3647 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003648 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003649 return BAD_VALUE;
3650 }
3651
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003652 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003653
3654 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003655 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003656 if (thread != dstThread &&
3657 thread->type() != PlaybackThread::DIRECT) {
3658 MixerThread *srcThread = (MixerThread *)thread;
3659 SortedVector < sp<MixerThread::Track> > tracks;
3660 SortedVector < wp<MixerThread::Track> > activeTracks;
3661 srcThread->getTracks(tracks, activeTracks, stream);
3662 if (tracks.size()) {
3663 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003664 }
3665 }
3666 }
3667
Eric Laurent06437712009-09-01 05:56:26 -07003668 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
3669
Eric Laurent9d91ad52009-07-17 12:17:14 -07003670 return NO_ERROR;
3671}
3672
3673// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003674AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003675{
3676 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003677 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3678 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003679 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003680 return thread;
3681}
3682
3683// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003684AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003685{
3686 PlaybackThread *thread = checkPlaybackThread_l(output);
3687 if (thread != NULL) {
3688 if (thread->type() == PlaybackThread::DIRECT) {
3689 thread = NULL;
3690 }
3691 }
3692 return (MixerThread *)thread;
3693}
3694
3695// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003696AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003697{
3698 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003699 if (mRecordThreads.indexOfKey(input) >= 0) {
3700 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003701 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003702 return thread;
3703}
3704
3705// ----------------------------------------------------------------------------
3706
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003707status_t AudioFlinger::onTransact(
3708 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3709{
3710 return BnAudioFlinger::onTransact(code, data, reply, flags);
3711}
3712
3713// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003714
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003715void AudioFlinger::instantiate() {
3716 defaultServiceManager()->addService(
3717 String16("media.audio_flinger"), new AudioFlinger());
3718}
3719
3720}; // namespace android