blob: cad420a9b15361afb9c36072e59720a47afc7f94 [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
Eric Laurent43c0b0a2010-01-25 08:49:09 -0800547bool AudioFlinger::isStreamActive(int stream) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700548{
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 Laurent43c0b0a2010-01-25 08:49:09 -0800551 if (mPlaybackThreads.valueAt(i)->isStreamActive(stream)) {
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
Eric Laurente9ed2722010-01-19 17:37:09 -0800636status_t AudioFlinger::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output)
637{
638 status_t status;
639
640 Mutex::Autolock _l(mLock);
641
642 PlaybackThread *playbackThread = checkPlaybackThread_l(output);
643 if (playbackThread != NULL) {
644 return playbackThread->getRenderPosition(halFrames, dspFrames);
645 }
646
647 return BAD_VALUE;
648}
649
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800650void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
651{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700652
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800653 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
654 Mutex::Autolock _l(mLock);
655
656 sp<IBinder> binder = client->asBinder();
657 if (mNotificationClients.indexOf(binder) < 0) {
658 LOGV("Adding notification client %p", binder.get());
659 binder->linkToDeath(this);
660 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700661 }
662
663 // the config change is always sent from playback or record threads to avoid deadlock
664 // with AudioSystem::gLock
665 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700666 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700667 }
668
669 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700670 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800671 }
672}
673
674void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700675
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800676 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
677 Mutex::Autolock _l(mLock);
678
679 IBinder *binder = who.unsafe_get();
680
681 if (binder != NULL) {
682 int index = mNotificationClients.indexOf(binder);
683 if (index >= 0) {
684 LOGV("Removing notification client %p", binder);
685 mNotificationClients.removeAt(index);
686 }
687 }
688}
689
Eric Laurentb3687ae2009-09-15 07:10:12 -0700690// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent09b4ba82009-11-19 09:00:56 -0800691void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2) {
692 size_t size = mNotificationClients.size();
693 for (size_t i = 0; i < size; i++) {
694 sp<IBinder> binder = mNotificationClients.itemAt(i);
695 LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
696 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
697 client->ioConfigChanged(event, ioHandle, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700698 }
699}
700
Eric Laurent0f8ab672009-09-17 05:12:56 -0700701// removeClient_l() must be called with AudioFlinger::mLock held
702void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700703{
Eric Laurent0f8ab672009-09-17 05:12:56 -0700704 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 -0700705 mClients.removeItem(pid);
706}
707
Eric Laurent9d91ad52009-07-17 12:17:14 -0700708// ----------------------------------------------------------------------------
709
Eric Laurent09b4ba82009-11-19 09:00:56 -0800710AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700711 : Thread(false),
712 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent09b4ba82009-11-19 09:00:56 -0800713 mFormat(0), mFrameSize(1), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700714{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715}
716
Eric Laurent9d91ad52009-07-17 12:17:14 -0700717AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800718{
Eric Laurent3464c012009-08-04 09:45:33 -0700719 mParamCond.broadcast();
720 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721}
722
Eric Laurent9d91ad52009-07-17 12:17:14 -0700723void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700724{
Eric Laurent2d70c802009-09-29 11:12:57 -0700725 // keep a strong ref on ourself so that we wont get
Eric Laurent9d91ad52009-07-17 12:17:14 -0700726 // destroyed in the middle of requestExitAndWait()
727 sp <ThreadBase> strongMe = this;
728
729 LOGV("ThreadBase::exit");
730 {
731 AutoMutex lock(&mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -0800732 mExiting = true;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700733 requestExit();
734 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700735 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700736 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700737}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700738
739uint32_t AudioFlinger::ThreadBase::sampleRate() const
740{
741 return mSampleRate;
742}
743
744int AudioFlinger::ThreadBase::channelCount() const
745{
746 return mChannelCount;
747}
748
749int AudioFlinger::ThreadBase::format() const
750{
751 return mFormat;
752}
753
754size_t AudioFlinger::ThreadBase::frameCount() const
755{
756 return mFrameCount;
757}
758
759status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
760{
Eric Laurent3464c012009-08-04 09:45:33 -0700761 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700762
Eric Laurent3464c012009-08-04 09:45:33 -0700763 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700764 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700765
Eric Laurent3464c012009-08-04 09:45:33 -0700766 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700767 mWaitWorkCV.signal();
Eric Laurent2d70c802009-09-29 11:12:57 -0700768 // wait condition with timeout in case the thread loop has exited
769 // before the request could be processed
770 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
771 status = mParamStatus;
772 mWaitWorkCV.signal();
773 } else {
774 status = TIMED_OUT;
775 }
Eric Laurent3464c012009-08-04 09:45:33 -0700776 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700777}
778
779void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
780{
781 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700782 sendConfigEvent_l(event, param);
783}
784
785// sendConfigEvent_l() must be called with ThreadBase::mLock held
786void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
787{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700788 ConfigEvent *configEvent = new ConfigEvent();
789 configEvent->mEvent = event;
790 configEvent->mParam = param;
791 mConfigEvents.add(configEvent);
792 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
793 mWaitWorkCV.signal();
794}
795
796void AudioFlinger::ThreadBase::processConfigEvents()
797{
798 mLock.lock();
799 while(!mConfigEvents.isEmpty()) {
800 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
801 ConfigEvent *configEvent = mConfigEvents[0];
802 mConfigEvents.removeAt(0);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700803 // release mLock because audioConfigChanged() will lock AudioFlinger mLock
804 // before calling Audioflinger::audioConfigChanged_l() thus creating
Eric Laurent9d91ad52009-07-17 12:17:14 -0700805 // potential cross deadlock between AudioFlinger::mLock and mLock
806 mLock.unlock();
807 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
808 delete configEvent;
809 mLock.lock();
810 }
811 mLock.unlock();
812}
813
Eric Laurentee47d432009-11-07 00:01:32 -0800814status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
815{
816 const size_t SIZE = 256;
817 char buffer[SIZE];
818 String8 result;
819
820 bool locked = tryLock(mLock);
821 if (!locked) {
822 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
823 write(fd, buffer, strlen(buffer));
824 }
825
826 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
827 result.append(buffer);
828 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
829 result.append(buffer);
830 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
831 result.append(buffer);
832 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
833 result.append(buffer);
834 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
835 result.append(buffer);
836 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
837 result.append(buffer);
838
839 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
840 result.append(buffer);
841 result.append(" Index Command");
842 for (size_t i = 0; i < mNewParameters.size(); ++i) {
843 snprintf(buffer, SIZE, "\n %02d ", i);
844 result.append(buffer);
845 result.append(mNewParameters[i]);
846 }
847
848 snprintf(buffer, SIZE, "\n\nPending config events: \n");
849 result.append(buffer);
850 snprintf(buffer, SIZE, " Index event param\n");
851 result.append(buffer);
852 for (size_t i = 0; i < mConfigEvents.size(); i++) {
853 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
854 result.append(buffer);
855 }
856 result.append("\n");
857
858 write(fd, result.string(), result.size());
859
860 if (locked) {
861 mLock.unlock();
862 }
863 return NO_ERROR;
864}
865
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800866
867// ----------------------------------------------------------------------------
868
Eric Laurent09b4ba82009-11-19 09:00:56 -0800869AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
870 : ThreadBase(audioFlinger, id),
Eric Laurentf9df2492009-08-06 08:49:39 -0700871 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700872 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800873{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700874 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800875
Eric Laurent9d91ad52009-07-17 12:17:14 -0700876 mMasterVolume = mAudioFlinger->masterVolume();
877 mMasterMute = mAudioFlinger->masterMute();
878
879 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
880 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
881 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800882 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700883 // notify client processes that a new input has been opened
884 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885}
886
Eric Laurent9d91ad52009-07-17 12:17:14 -0700887AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800888{
889 delete [] mMixBuffer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800890}
891
Eric Laurent9d91ad52009-07-17 12:17:14 -0700892status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800893{
894 dumpInternals(fd, args);
895 dumpTracks(fd, args);
896 return NO_ERROR;
897}
898
Eric Laurent9d91ad52009-07-17 12:17:14 -0700899status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800900{
901 const size_t SIZE = 256;
902 char buffer[SIZE];
903 String8 result;
904
Eric Laurent9d91ad52009-07-17 12:17:14 -0700905 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800906 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -0800907 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 -0800908 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700909 sp<Track> track = mTracks[i];
910 if (track != 0) {
911 track->dump(buffer, SIZE);
912 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800913 }
914 }
915
Eric Laurent9d91ad52009-07-17 12:17:14 -0700916 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800917 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -0800918 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 -0800919 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700920 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800921 if (wTrack != 0) {
922 sp<Track> track = wTrack.promote();
923 if (track != 0) {
924 track->dump(buffer, SIZE);
925 result.append(buffer);
926 }
927 }
928 }
929 write(fd, result.string(), result.size());
930 return NO_ERROR;
931}
932
Eric Laurent9d91ad52009-07-17 12:17:14 -0700933status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800934{
935 const size_t SIZE = 256;
936 char buffer[SIZE];
937 String8 result;
938
Eric Laurentee47d432009-11-07 00:01:32 -0800939 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800940 result.append(buffer);
941 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
942 result.append(buffer);
943 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
944 result.append(buffer);
945 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
946 result.append(buffer);
947 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
948 result.append(buffer);
Eric Laurent7e2aad12009-12-18 05:47:48 -0800949 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
950 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800951 write(fd, result.string(), result.size());
Eric Laurentee47d432009-11-07 00:01:32 -0800952
953 dumpBase(fd, args);
954
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800955 return NO_ERROR;
956}
957
958// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700959status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800960{
961 if (mSampleRate == 0) {
962 LOGE("No working audio driver found.");
963 return NO_INIT;
964 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700965 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800966 return NO_ERROR;
967}
968
Eric Laurent9d91ad52009-07-17 12:17:14 -0700969void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800970{
971 const size_t SIZE = 256;
972 char buffer[SIZE];
973
Eric Laurent9d91ad52009-07-17 12:17:14 -0700974 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800975
976 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
977}
978
Eric Laurent9d91ad52009-07-17 12:17:14 -0700979// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
980sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800981 const sp<AudioFlinger::Client>& client,
982 int streamType,
983 uint32_t sampleRate,
984 int format,
985 int channelCount,
986 int frameCount,
987 const sp<IMemory>& sharedBuffer,
988 status_t *status)
989{
990 sp<Track> track;
991 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700992
993 if (mType == DIRECT) {
994 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
995 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
996 sampleRate, format, channelCount, mOutput);
997 lStatus = BAD_VALUE;
998 goto Exit;
999 }
1000 } else {
1001 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
1002 if (sampleRate > mSampleRate*2) {
1003 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
1004 lStatus = BAD_VALUE;
1005 goto Exit;
1006 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001007 }
1008
Eric Laurent9d91ad52009-07-17 12:17:14 -07001009 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001010 LOGE("Audio driver not initialized.");
1011 lStatus = NO_INIT;
1012 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013 }
1014
Eric Laurent9d91ad52009-07-17 12:17:14 -07001015 { // scope for mLock
1016 Mutex::Autolock _l(mLock);
1017 track = new Track(this, client, streamType, sampleRate, format,
1018 channelCount, frameCount, sharedBuffer);
Eric Laurent7b570852009-11-09 04:45:39 -08001019 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001020 lStatus = NO_MEMORY;
1021 goto Exit;
1022 }
1023 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001024 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001025 lStatus = NO_ERROR;
1026
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027Exit:
1028 if(status) {
1029 *status = lStatus;
1030 }
1031 return track;
1032}
1033
Eric Laurent9d91ad52009-07-17 12:17:14 -07001034uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001035{
1036 if (mOutput) {
1037 return mOutput->latency();
1038 }
1039 else {
1040 return 0;
1041 }
1042}
1043
Eric Laurent9d91ad52009-07-17 12:17:14 -07001044status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001045{
1046 mMasterVolume = value;
1047 return NO_ERROR;
1048}
1049
Eric Laurent9d91ad52009-07-17 12:17:14 -07001050status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001051{
1052 mMasterMute = muted;
1053 return NO_ERROR;
1054}
1055
Eric Laurent9d91ad52009-07-17 12:17:14 -07001056float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001057{
1058 return mMasterVolume;
1059}
1060
Eric Laurent9d91ad52009-07-17 12:17:14 -07001061bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062{
1063 return mMasterMute;
1064}
1065
Eric Laurent9d91ad52009-07-17 12:17:14 -07001066status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067{
1068 mStreamTypes[stream].volume = value;
1069 return NO_ERROR;
1070}
1071
Eric Laurent9d91ad52009-07-17 12:17:14 -07001072status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001073{
1074 mStreamTypes[stream].mute = muted;
1075 return NO_ERROR;
1076}
1077
Eric Laurent9d91ad52009-07-17 12:17:14 -07001078float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001079{
1080 return mStreamTypes[stream].volume;
1081}
1082
Eric Laurent9d91ad52009-07-17 12:17:14 -07001083bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001084{
1085 return mStreamTypes[stream].mute;
1086}
1087
Eric Laurent43c0b0a2010-01-25 08:49:09 -08001088bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001089{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001090 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001091 size_t count = mActiveTracks.size();
1092 for (size_t i = 0 ; i < count ; ++i) {
1093 sp<Track> t = mActiveTracks[i].promote();
1094 if (t == 0) continue;
1095 Track* const track = t.get();
Eric Laurent43c0b0a2010-01-25 08:49:09 -08001096 if (t->type() == stream)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001097 return true;
1098 }
1099 return false;
1100}
1101
Eric Laurent9d91ad52009-07-17 12:17:14 -07001102// addTrack_l() must be called with ThreadBase::mLock held
1103status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001104{
1105 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001106
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001107 // set retry count for buffer fill
1108 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001109 if (mActiveTracks.indexOf(track) < 0) {
1110 // the track is newly added, make sure it fills up all its
1111 // buffers before playing. This is to ensure the client will
1112 // effectively get the latency it requested.
1113 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001114 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001115 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001116 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001117 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001118
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001119 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001120 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001121
1122 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001123}
1124
Eric Laurent9d91ad52009-07-17 12:17:14 -07001125// destroyTrack_l() must be called with ThreadBase::mLock held
1126void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001127{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001128 track->mState = TrackBase::TERMINATED;
1129 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001130 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001131 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001132 }
1133}
1134
Eric Laurent9d91ad52009-07-17 12:17:14 -07001135String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001136{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001137 return mOutput->getParameters(keys);
1138}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001139
Eric Laurent9d91ad52009-07-17 12:17:14 -07001140void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1141 AudioSystem::OutputDescriptor desc;
1142 void *param2 = 0;
1143
1144 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1145
1146 switch (event) {
1147 case AudioSystem::OUTPUT_OPENED:
1148 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1149 desc.channels = mChannelCount;
1150 desc.samplingRate = mSampleRate;
1151 desc.format = mFormat;
1152 desc.frameCount = mFrameCount;
1153 desc.latency = latency();
1154 param2 = &desc;
1155 break;
1156
1157 case AudioSystem::STREAM_CONFIG_CHANGED:
1158 param2 = &param;
1159 case AudioSystem::OUTPUT_CLOSED:
1160 default:
1161 break;
1162 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07001163 Mutex::Autolock _l(mAudioFlinger->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08001164 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001165}
1166
1167void AudioFlinger::PlaybackThread::readOutputParameters()
1168{
1169 mSampleRate = mOutput->sampleRate();
1170 mChannelCount = AudioSystem::popCount(mOutput->channels());
1171
1172 mFormat = mOutput->format();
1173 mFrameSize = mOutput->frameSize();
1174 mFrameCount = mOutput->bufferSize() / mFrameSize;
1175
Eric Laurent9d91ad52009-07-17 12:17:14 -07001176 // FIXME - Current mixer implementation only supports stereo output: Always
1177 // Allocate a stereo buffer even if HW output is mono.
1178 if (mMixBuffer != NULL) delete mMixBuffer;
1179 mMixBuffer = new int16_t[mFrameCount * 2];
1180 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1181}
1182
Eric Laurente9ed2722010-01-19 17:37:09 -08001183status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
1184{
1185 if (halFrames == 0 || dspFrames == 0) {
1186 return BAD_VALUE;
1187 }
1188 if (mOutput == 0) {
1189 return INVALID_OPERATION;
1190 }
1191 *halFrames = mBytesWritten/mOutput->frameSize();
1192
1193 return mOutput->getRenderPosition(dspFrames);
1194}
1195
Eric Laurent9d91ad52009-07-17 12:17:14 -07001196// ----------------------------------------------------------------------------
1197
Eric Laurent09b4ba82009-11-19 09:00:56 -08001198AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
1199 : PlaybackThread(audioFlinger, output, id),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001200 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 Laurent9d91ad52009-07-17 12:17:14 -07001218 int16_t* curBuf = mMixBuffer;
1219 Vector< sp<Track> > tracksToRemove;
Eric Laurent0e49d352009-11-09 23:32:22 -08001220 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001221 nsecs_t standbyTime = systemTime();
1222 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparks8a95a452009-09-30 03:09:03 -07001223 // FIXME: Relaxed timing because of a certain device that can't meet latency
1224 // Should be reduced to 2x after the vendor fixes the driver issue
1225 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1226 nsecs_t lastWarning = 0;
Eric Laurent0e49d352009-11-09 23:32:22 -08001227 bool longStandbyExit = false;
1228 uint32_t activeSleepTime = activeSleepTimeUs();
1229 uint32_t idleSleepTime = idleSleepTimeUs();
1230 uint32_t sleepTime = idleSleepTime;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001231
Eric Laurent9d91ad52009-07-17 12:17:14 -07001232 while (!exitPending())
1233 {
1234 processConfigEvents();
1235
Eric Laurent0e49d352009-11-09 23:32:22 -08001236 mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001237 { // scope for mLock
1238
1239 Mutex::Autolock _l(mLock);
1240
1241 if (checkForNewParameters_l()) {
1242 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparks8a95a452009-09-30 03:09:03 -07001243 // FIXME: Relaxed timing because of a certain device that can't meet latency
1244 // Should be reduced to 2x after the vendor fixes the driver issue
1245 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent0e49d352009-11-09 23:32:22 -08001246 activeSleepTime = activeSleepTimeUs();
1247 idleSleepTime = idleSleepTimeUs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001248 }
1249
1250 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1251
1252 // put audio hardware into standby after short delay
1253 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1254 mSuspended) {
1255 if (!mStandby) {
1256 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1257 mOutput->standby();
1258 mStandby = true;
1259 mBytesWritten = 0;
1260 }
1261
1262 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1263 // we're about to wait, flush the binder command buffer
1264 IPCThreadState::self()->flushCommands();
1265
1266 if (exitPending()) break;
1267
1268 // wait until we have something to do...
1269 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1270 mWaitWorkCV.wait(mLock);
1271 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1272
1273 if (mMasterMute == false) {
1274 char value[PROPERTY_VALUE_MAX];
1275 property_get("ro.audio.silent", value, "0");
1276 if (atoi(value)) {
1277 LOGD("Silence is golden");
1278 setMasterMute(true);
1279 }
1280 }
1281
1282 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent0e49d352009-11-09 23:32:22 -08001283 sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001284 continue;
1285 }
1286 }
1287
Eric Laurent0e49d352009-11-09 23:32:22 -08001288 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001289 }
1290
Eric Laurent0e49d352009-11-09 23:32:22 -08001291 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001292 // mix buffers...
1293 mAudioMixer->process(curBuf);
1294 sleepTime = 0;
1295 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001296 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001297 // If no tracks are ready, sleep once for the duration of an output
1298 // buffer size, then write 0s to the output
1299 if (sleepTime == 0) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001300 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1301 sleepTime = activeSleepTime;
1302 } else {
1303 sleepTime = idleSleepTime;
1304 }
1305 } else if (mBytesWritten != 0 ||
1306 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001307 memset (curBuf, 0, mixBufferSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001308 sleepTime = 0;
Eric Laurent0e49d352009-11-09 23:32:22 -08001309 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent3522c802009-09-07 08:38:38 -07001310 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001311 }
1312
1313 if (mSuspended) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001314 sleepTime = idleSleepTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07001315 }
1316 // sleepTime == 0 means we must write to audio hardware
1317 if (sleepTime == 0) {
1318 mLastWriteTime = systemTime();
1319 mInWrite = true;
Eric Laurente9ed2722010-01-19 17:37:09 -08001320 mBytesWritten += mixBufferSize;
Eric Laurentaef692f2009-09-22 00:35:48 -07001321 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
Eric Laurente9ed2722010-01-19 17:37:09 -08001322 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentaef692f2009-09-22 00:35:48 -07001323 mNumWrites++;
1324 mInWrite = false;
Dave Sparks8a95a452009-09-30 03:09:03 -07001325 nsecs_t now = systemTime();
1326 nsecs_t delta = now - mLastWriteTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07001327 if (delta > maxPeriod) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001328 mNumDelayedWrites++;
Dave Sparks8a95a452009-09-30 03:09:03 -07001329 if ((now - lastWarning) > kWarningThrottle) {
1330 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1331 ns2ms(delta), mNumDelayedWrites, this);
1332 lastWarning = now;
1333 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001334 if (mStandby) {
1335 longStandbyExit = true;
1336 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001337 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001338 mStandby = false;
Eric Laurentaef692f2009-09-22 00:35:48 -07001339 } else {
1340 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001341 }
1342
1343 // finally let go of all our tracks, without the lock held
1344 // since we can't guarantee the destructors won't acquire that
1345 // same lock.
1346 tracksToRemove.clear();
1347 }
1348
1349 if (!mStandby) {
1350 mOutput->standby();
1351 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001352
1353 LOGV("MixerThread %p exiting", this);
1354 return false;
1355}
1356
1357// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent0e49d352009-11-09 23:32:22 -08001358uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurent9d91ad52009-07-17 12:17:14 -07001359{
1360
Eric Laurent0e49d352009-11-09 23:32:22 -08001361 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001362 // find out which tracks need to be processed
1363 size_t count = activeTracks.size();
1364 for (size_t i=0 ; i<count ; i++) {
1365 sp<Track> t = activeTracks[i].promote();
1366 if (t == 0) continue;
1367
1368 Track* const track = t.get();
1369 audio_track_cblk_t* cblk = track->cblk();
1370
1371 // The first time a track is added we wait
1372 // for all its buffers to be filled before processing it
1373 mAudioMixer->setActiveTrack(track->name());
1374 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1375 !track->isPaused())
1376 {
Eric Laurent7e2aad12009-12-18 05:47:48 -08001377 //LOGV("track %d u=%08x, s=%08x [OK] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001378
1379 // compute volume for this track
1380 int16_t left, right;
1381 if (track->isMuted() || mMasterMute || track->isPausing() ||
1382 mStreamTypes[track->type()].mute) {
1383 left = right = 0;
1384 if (track->isPausing()) {
1385 track->setPaused();
1386 }
1387 } else {
1388 float typeVolume = mStreamTypes[track->type()].volume;
1389 float v = mMasterVolume * typeVolume;
1390 float v_clamped = v * cblk->volume[0];
1391 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1392 left = int16_t(v_clamped);
1393 v_clamped = v * cblk->volume[1];
1394 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1395 right = int16_t(v_clamped);
1396 }
1397
1398 // XXX: these things DON'T need to be done each time
1399 mAudioMixer->setBufferProvider(track);
1400 mAudioMixer->enable(AudioMixer::MIXING);
1401
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001402 int param = AudioMixer::VOLUME;
1403 if (track->mFillingUpStatus == Track::FS_FILLED) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001404 // no ramp for the first volume setting
1405 track->mFillingUpStatus = Track::FS_ACTIVE;
1406 if (track->mState == TrackBase::RESUMING) {
1407 track->mState = TrackBase::ACTIVE;
1408 param = AudioMixer::RAMP_VOLUME;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001409 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001410 } else if (cblk->server != 0) {
1411 // If the track is stopped before the first frame was mixed,
1412 // do not apply ramp
Eric Laurent9d91ad52009-07-17 12:17:14 -07001413 param = AudioMixer::RAMP_VOLUME;
1414 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001415
Eric Laurent9d91ad52009-07-17 12:17:14 -07001416 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1417 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1418 mAudioMixer->setParameter(
1419 AudioMixer::TRACK,
1420 AudioMixer::FORMAT, track->format());
1421 mAudioMixer->setParameter(
1422 AudioMixer::TRACK,
1423 AudioMixer::CHANNEL_COUNT, track->channelCount());
1424 mAudioMixer->setParameter(
1425 AudioMixer::RESAMPLE,
1426 AudioMixer::SAMPLE_RATE,
1427 int(cblk->sampleRate));
1428
1429 // reset retry count
1430 track->mRetryCount = kMaxTrackRetries;
Eric Laurent0e49d352009-11-09 23:32:22 -08001431 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001432 } else {
Eric Laurent7e2aad12009-12-18 05:47:48 -08001433 //LOGV("track %d u=%08x, s=%08x [NOT READY] on thread %p", track->name(), cblk->user, cblk->server, this);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001434 if (track->isStopped()) {
1435 track->reset();
1436 }
1437 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1438 // We have consumed all the buffers of this track.
1439 // Remove it from the list of active tracks.
1440 tracksToRemove->add(track);
1441 mAudioMixer->disable(AudioMixer::MIXING);
1442 } else {
1443 // No buffers for this track. Give it a few chances to
1444 // fill a buffer, then remove it from active list.
1445 if (--(track->mRetryCount) <= 0) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001446 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001447 tracksToRemove->add(track);
Eric Laurent0e49d352009-11-09 23:32:22 -08001448 } else if (mixerStatus != MIXER_TRACKS_READY) {
1449 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001450 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001451
1452 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001453 }
1454 }
1455 }
1456
1457 // remove all the tracks that need to be...
1458 count = tracksToRemove->size();
1459 if (UNLIKELY(count)) {
1460 for (size_t i=0 ; i<count ; i++) {
1461 const sp<Track>& track = tracksToRemove->itemAt(i);
1462 mActiveTracks.remove(track);
1463 if (track->isTerminated()) {
1464 mTracks.remove(track);
1465 deleteTrackName_l(track->mName);
1466 }
1467 }
1468 }
1469
Eric Laurent0e49d352009-11-09 23:32:22 -08001470 return mixerStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001471}
1472
1473void AudioFlinger::MixerThread::getTracks(
1474 SortedVector < sp<Track> >& tracks,
1475 SortedVector < wp<Track> >& activeTracks,
1476 int streamType)
1477{
1478 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1479 Mutex::Autolock _l(mLock);
1480 size_t size = mTracks.size();
1481 for (size_t i = 0; i < size; i++) {
1482 sp<Track> t = mTracks[i];
1483 if (t->type() == streamType) {
1484 tracks.add(t);
1485 int j = mActiveTracks.indexOf(t);
1486 if (j >= 0) {
1487 t = mActiveTracks[j].promote();
1488 if (t != NULL) {
1489 activeTracks.add(t);
1490 }
1491 }
1492 }
1493 }
1494
1495 size = activeTracks.size();
1496 for (size_t i = 0; i < size; i++) {
1497 mActiveTracks.remove(activeTracks[i]);
1498 }
1499
1500 size = tracks.size();
1501 for (size_t i = 0; i < size; i++) {
1502 sp<Track> t = tracks[i];
1503 mTracks.remove(t);
1504 deleteTrackName_l(t->name());
1505 }
1506}
1507
1508void AudioFlinger::MixerThread::putTracks(
1509 SortedVector < sp<Track> >& tracks,
1510 SortedVector < wp<Track> >& activeTracks)
1511{
1512 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1513 Mutex::Autolock _l(mLock);
1514 size_t size = tracks.size();
1515 for (size_t i = 0; i < size ; i++) {
1516 sp<Track> t = tracks[i];
1517 int name = getTrackName_l();
1518
1519 if (name < 0) return;
1520
1521 t->mName = name;
1522 t->mThread = this;
1523 mTracks.add(t);
1524
1525 int j = activeTracks.indexOf(t);
1526 if (j >= 0) {
1527 mActiveTracks.add(t);
Eric Laurent06437712009-09-01 05:56:26 -07001528 // force buffer refilling and no ramp volume when the track is mixed for the first time
1529 t->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001530 }
1531 }
1532}
1533
Eric Laurent9d91ad52009-07-17 12:17:14 -07001534// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001535int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001536{
1537 return mAudioMixer->getTrackName();
1538}
1539
Eric Laurent9d91ad52009-07-17 12:17:14 -07001540// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001541void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001542{
Eric Laurentfed93822009-12-07 10:53:10 -08001543 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001544 mAudioMixer->deleteTrackName(name);
1545}
1546
Eric Laurent9d91ad52009-07-17 12:17:14 -07001547// checkForNewParameters_l() must be called with ThreadBase::mLock held
1548bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001549{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001550 bool reconfig = false;
1551
Eric Laurent3464c012009-08-04 09:45:33 -07001552 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001553 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001554 String8 keyValuePair = mNewParameters[0];
1555 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001556 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001557
Eric Laurent9d91ad52009-07-17 12:17:14 -07001558 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1559 reconfig = true;
1560 }
1561 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1562 if (value != AudioSystem::PCM_16_BIT) {
1563 status = BAD_VALUE;
1564 } else {
1565 reconfig = true;
1566 }
1567 }
1568 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1569 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1570 status = BAD_VALUE;
1571 } else {
1572 reconfig = true;
1573 }
1574 }
1575 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1576 // do not accept frame count changes if tracks are open as the track buffer
1577 // size depends on frame count and correct behavior would not be garantied
1578 // if frame count is changed after track creation
1579 if (!mTracks.isEmpty()) {
1580 status = INVALID_OPERATION;
1581 } else {
1582 reconfig = true;
1583 }
1584 }
1585 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001586 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001587 if (!mStandby && status == INVALID_OPERATION) {
1588 mOutput->standby();
1589 mStandby = true;
1590 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001591 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001592 }
1593 if (status == NO_ERROR && reconfig) {
1594 delete mAudioMixer;
1595 readOutputParameters();
1596 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1597 for (size_t i = 0; i < mTracks.size() ; i++) {
1598 int name = getTrackName_l();
1599 if (name < 0) break;
1600 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001601 // limit track sample rate to 2 x new output sample rate
1602 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1603 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1604 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001605 }
Eric Laurent3464c012009-08-04 09:45:33 -07001606 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001607 }
1608 }
Eric Laurentee47d432009-11-07 00:01:32 -08001609
1610 mNewParameters.removeAt(0);
1611
Eric Laurent9d91ad52009-07-17 12:17:14 -07001612 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001613 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001614 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001615 }
1616 return reconfig;
1617}
1618
1619status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1620{
1621 const size_t SIZE = 256;
1622 char buffer[SIZE];
1623 String8 result;
1624
1625 PlaybackThread::dumpInternals(fd, args);
1626
1627 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1628 result.append(buffer);
1629 write(fd, result.string(), result.size());
1630 return NO_ERROR;
1631}
1632
Eric Laurent0e49d352009-11-09 23:32:22 -08001633uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurentf5e868b2009-10-05 20:29:18 -07001634{
Eric Laurent0e49d352009-11-09 23:32:22 -08001635 return (uint32_t)(mOutput->latency() * 1000) / 2;
1636}
1637
1638uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1639{
1640 return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001641}
1642
Eric Laurent9d91ad52009-07-17 12:17:14 -07001643// ----------------------------------------------------------------------------
Eric Laurent09b4ba82009-11-19 09:00:56 -08001644AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
1645 : PlaybackThread(audioFlinger, output, id),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001646 mLeftVolume (1.0), mRightVolume(1.0)
1647{
1648 mType = PlaybackThread::DIRECT;
1649}
1650
1651AudioFlinger::DirectOutputThread::~DirectOutputThread()
1652{
1653}
1654
1655
1656bool AudioFlinger::DirectOutputThread::threadLoop()
1657{
Eric Laurent0e49d352009-11-09 23:32:22 -08001658 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001659 sp<Track> trackToRemove;
1660 sp<Track> activeTrack;
1661 nsecs_t standbyTime = systemTime();
1662 int8_t *curBuf;
1663 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent0e49d352009-11-09 23:32:22 -08001664 uint32_t activeSleepTime = activeSleepTimeUs();
1665 uint32_t idleSleepTime = idleSleepTimeUs();
1666 uint32_t sleepTime = idleSleepTime;
1667
Eric Laurent9d91ad52009-07-17 12:17:14 -07001668
1669 while (!exitPending())
1670 {
1671 processConfigEvents();
1672
Eric Laurent0e49d352009-11-09 23:32:22 -08001673 mixerStatus = MIXER_IDLE;
1674
Eric Laurent9d91ad52009-07-17 12:17:14 -07001675 { // scope for the mLock
1676
1677 Mutex::Autolock _l(mLock);
1678
1679 if (checkForNewParameters_l()) {
1680 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent0e49d352009-11-09 23:32:22 -08001681 activeSleepTime = activeSleepTimeUs();
1682 idleSleepTime = idleSleepTimeUs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001683 }
1684
1685 // put audio hardware into standby after short delay
1686 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1687 mSuspended) {
1688 // wait until we have something to do...
1689 if (!mStandby) {
1690 LOGV("Audio hardware entering standby, mixer %p\n", this);
1691 mOutput->standby();
1692 mStandby = true;
1693 mBytesWritten = 0;
1694 }
1695
1696 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1697 // we're about to wait, flush the binder command buffer
1698 IPCThreadState::self()->flushCommands();
1699
1700 if (exitPending()) break;
1701
1702 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1703 mWaitWorkCV.wait(mLock);
1704 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1705
1706 if (mMasterMute == false) {
1707 char value[PROPERTY_VALUE_MAX];
1708 property_get("ro.audio.silent", value, "0");
1709 if (atoi(value)) {
1710 LOGD("Silence is golden");
1711 setMasterMute(true);
1712 }
1713 }
1714
1715 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent0e49d352009-11-09 23:32:22 -08001716 sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001717 continue;
1718 }
1719 }
1720
1721 // find out which tracks need to be processed
1722 if (mActiveTracks.size() != 0) {
1723 sp<Track> t = mActiveTracks[0].promote();
1724 if (t == 0) continue;
1725
1726 Track* const track = t.get();
1727 audio_track_cblk_t* cblk = track->cblk();
1728
1729 // The first time a track is added we wait
1730 // for all its buffers to be filled before processing it
1731 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1732 !track->isPaused())
1733 {
1734 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1735
1736 // compute volume for this track
1737 float left, right;
1738 if (track->isMuted() || mMasterMute || track->isPausing() ||
1739 mStreamTypes[track->type()].mute) {
1740 left = right = 0;
1741 if (track->isPausing()) {
1742 track->setPaused();
1743 }
1744 } else {
1745 float typeVolume = mStreamTypes[track->type()].volume;
1746 float v = mMasterVolume * typeVolume;
1747 float v_clamped = v * cblk->volume[0];
1748 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1749 left = v_clamped/MAX_GAIN;
1750 v_clamped = v * cblk->volume[1];
1751 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1752 right = v_clamped/MAX_GAIN;
1753 }
1754
1755 if (left != mLeftVolume || right != mRightVolume) {
1756 mOutput->setVolume(left, right);
1757 left = mLeftVolume;
1758 right = mRightVolume;
1759 }
1760
1761 if (track->mFillingUpStatus == Track::FS_FILLED) {
1762 track->mFillingUpStatus = Track::FS_ACTIVE;
1763 if (track->mState == TrackBase::RESUMING) {
1764 track->mState = TrackBase::ACTIVE;
1765 }
1766 }
1767
1768 // reset retry count
1769 track->mRetryCount = kMaxTrackRetries;
1770 activeTrack = t;
Eric Laurent0e49d352009-11-09 23:32:22 -08001771 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001772 } else {
1773 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1774 if (track->isStopped()) {
1775 track->reset();
1776 }
1777 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1778 // We have consumed all the buffers of this track.
1779 // Remove it from the list of active tracks.
1780 trackToRemove = track;
1781 } else {
1782 // No buffers for this track. Give it a few chances to
1783 // fill a buffer, then remove it from active list.
1784 if (--(track->mRetryCount) <= 0) {
1785 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1786 trackToRemove = track;
Eric Laurent0e49d352009-11-09 23:32:22 -08001787 } else {
1788 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001789 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001790 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001791 }
1792 }
1793
1794 // remove all the tracks that need to be...
1795 if (UNLIKELY(trackToRemove != 0)) {
1796 mActiveTracks.remove(trackToRemove);
1797 if (trackToRemove->isTerminated()) {
1798 mTracks.remove(trackToRemove);
1799 deleteTrackName_l(trackToRemove->mName);
1800 }
1801 }
1802 }
1803
Eric Laurent0e49d352009-11-09 23:32:22 -08001804 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001805 AudioBufferProvider::Buffer buffer;
1806 size_t frameCount = mFrameCount;
1807 curBuf = (int8_t *)mMixBuffer;
1808 // output audio to hardware
1809 while(frameCount) {
1810 buffer.frameCount = frameCount;
1811 activeTrack->getNextBuffer(&buffer);
1812 if (UNLIKELY(buffer.raw == 0)) {
1813 memset(curBuf, 0, frameCount * mFrameSize);
1814 break;
1815 }
1816 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1817 frameCount -= buffer.frameCount;
1818 curBuf += buffer.frameCount * mFrameSize;
1819 activeTrack->releaseBuffer(&buffer);
1820 }
1821 sleepTime = 0;
1822 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001823 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001824 if (sleepTime == 0) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001825 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1826 sleepTime = activeSleepTime;
1827 } else {
1828 sleepTime = idleSleepTime;
1829 }
Eric Laurentf5e868b2009-10-05 20:29:18 -07001830 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001831 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001832 sleepTime = 0;
Eric Laurent3522c802009-09-07 08:38:38 -07001833 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001834 }
Eric Laurent3522c802009-09-07 08:38:38 -07001835
Eric Laurentaef692f2009-09-22 00:35:48 -07001836 if (mSuspended) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001837 sleepTime = idleSleepTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07001838 }
1839 // sleepTime == 0 means we must write to audio hardware
1840 if (sleepTime == 0) {
1841 mLastWriteTime = systemTime();
1842 mInWrite = true;
Eric Laurente9ed2722010-01-19 17:37:09 -08001843 mBytesWritten += mixBufferSize;
Eric Laurentaef692f2009-09-22 00:35:48 -07001844 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
Eric Laurente9ed2722010-01-19 17:37:09 -08001845 if (bytesWritten < 0) mBytesWritten -= mixBufferSize;
Eric Laurentaef692f2009-09-22 00:35:48 -07001846 mNumWrites++;
1847 mInWrite = false;
1848 mStandby = false;
1849 } else {
1850 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001851 }
1852
1853 // finally let go of removed track, without the lock held
1854 // since we can't guarantee the destructors won't acquire that
1855 // same lock.
1856 trackToRemove.clear();
1857 activeTrack.clear();
1858 }
1859
1860 if (!mStandby) {
1861 mOutput->standby();
1862 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001863
1864 LOGV("DirectOutputThread %p exiting", this);
1865 return false;
1866}
1867
1868// getTrackName_l() must be called with ThreadBase::mLock held
1869int AudioFlinger::DirectOutputThread::getTrackName_l()
1870{
1871 return 0;
1872}
1873
1874// deleteTrackName_l() must be called with ThreadBase::mLock held
1875void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1876{
1877}
1878
1879// checkForNewParameters_l() must be called with ThreadBase::mLock held
1880bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1881{
1882 bool reconfig = false;
1883
Eric Laurent3464c012009-08-04 09:45:33 -07001884 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001885 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001886 String8 keyValuePair = mNewParameters[0];
1887 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001888 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001889
Eric Laurent9d91ad52009-07-17 12:17:14 -07001890 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1891 // do not accept frame count changes if tracks are open as the track buffer
1892 // size depends on frame count and correct behavior would not be garantied
1893 // if frame count is changed after track creation
1894 if (!mTracks.isEmpty()) {
1895 status = INVALID_OPERATION;
1896 } else {
1897 reconfig = true;
1898 }
1899 }
1900 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001901 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001902 if (!mStandby && status == INVALID_OPERATION) {
1903 mOutput->standby();
1904 mStandby = true;
1905 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001906 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001907 }
1908 if (status == NO_ERROR && reconfig) {
1909 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001910 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001911 }
1912 }
Eric Laurentee47d432009-11-07 00:01:32 -08001913
1914 mNewParameters.removeAt(0);
1915
Eric Laurent9d91ad52009-07-17 12:17:14 -07001916 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001917 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001918 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001919 }
1920 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001921}
1922
Eric Laurent0e49d352009-11-09 23:32:22 -08001923uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurentf5e868b2009-10-05 20:29:18 -07001924{
1925 uint32_t time;
1926 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001927 time = (uint32_t)(mOutput->latency() * 1000) / 2;
1928 } else {
1929 time = 10000;
1930 }
1931 return time;
1932}
1933
1934uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
1935{
1936 uint32_t time;
1937 if (AudioSystem::isLinearPCM(mFormat)) {
1938 time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001939 } else {
1940 time = 10000;
1941 }
1942 return time;
1943}
1944
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001945// ----------------------------------------------------------------------------
1946
Eric Laurent09b4ba82009-11-19 09:00:56 -08001947AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent7e2aad12009-12-18 05:47:48 -08001948 : MixerThread(audioFlinger, mainThread->getOutput(), id), mWaitTimeMs(UINT_MAX)
Eric Laurent9d91ad52009-07-17 12:17:14 -07001949{
1950 mType = PlaybackThread::DUPLICATING;
1951 addOutputTrack(mainThread);
1952}
1953
1954AudioFlinger::DuplicatingThread::~DuplicatingThread()
1955{
Eric Laurentfed93822009-12-07 10:53:10 -08001956 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1957 mOutputTracks[i]->destroy();
1958 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001959 mOutputTracks.clear();
1960}
1961
1962bool AudioFlinger::DuplicatingThread::threadLoop()
1963{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001964 int16_t* curBuf = mMixBuffer;
1965 Vector< sp<Track> > tracksToRemove;
Eric Laurent0e49d352009-11-09 23:32:22 -08001966 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001967 nsecs_t standbyTime = systemTime();
1968 size_t mixBufferSize = mFrameCount*mFrameSize;
1969 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001970 uint32_t writeFrames = 0;
Eric Laurent0e49d352009-11-09 23:32:22 -08001971 uint32_t activeSleepTime = activeSleepTimeUs();
1972 uint32_t idleSleepTime = idleSleepTimeUs();
1973 uint32_t sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001974
1975 while (!exitPending())
1976 {
1977 processConfigEvents();
1978
Eric Laurent0e49d352009-11-09 23:32:22 -08001979 mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001980 { // scope for the mLock
1981
1982 Mutex::Autolock _l(mLock);
1983
1984 if (checkForNewParameters_l()) {
1985 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent7e2aad12009-12-18 05:47:48 -08001986 updateWaitTime();
Eric Laurent0e49d352009-11-09 23:32:22 -08001987 activeSleepTime = activeSleepTimeUs();
1988 idleSleepTime = idleSleepTimeUs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001989 }
1990
1991 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1992
1993 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1994 outputTracks.add(mOutputTracks[i]);
1995 }
1996
1997 // put audio hardware into standby after short delay
1998 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1999 mSuspended) {
2000 if (!mStandby) {
2001 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002002 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002003 }
2004 mStandby = true;
2005 mBytesWritten = 0;
2006 }
2007
2008 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
2009 // we're about to wait, flush the binder command buffer
2010 IPCThreadState::self()->flushCommands();
2011 outputTracks.clear();
2012
2013 if (exitPending()) break;
2014
2015 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
2016 mWaitWorkCV.wait(mLock);
2017 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
2018 if (mMasterMute == false) {
2019 char value[PROPERTY_VALUE_MAX];
2020 property_get("ro.audio.silent", value, "0");
2021 if (atoi(value)) {
2022 LOGD("Silence is golden");
2023 setMasterMute(true);
2024 }
2025 }
2026
2027 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent0e49d352009-11-09 23:32:22 -08002028 sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002029 continue;
2030 }
2031 }
2032
Eric Laurent0e49d352009-11-09 23:32:22 -08002033 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurentaef692f2009-09-22 00:35:48 -07002034 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002035
Eric Laurent0e49d352009-11-09 23:32:22 -08002036 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002037 // mix buffers...
Eric Laurent7e2aad12009-12-18 05:47:48 -08002038 if (outputsReady(outputTracks)) {
2039 mAudioMixer->process(curBuf);
2040 } else {
2041 memset(curBuf, 0, mixBufferSize);
2042 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002043 sleepTime = 0;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002044 writeFrames = mFrameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002045 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002046 if (sleepTime == 0) {
Eric Laurent0e49d352009-11-09 23:32:22 -08002047 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2048 sleepTime = activeSleepTime;
2049 } else {
2050 sleepTime = idleSleepTime;
2051 }
Eric Laurentf5e868b2009-10-05 20:29:18 -07002052 } else if (mBytesWritten != 0) {
2053 // flush remaining overflow buffers in output tracks
2054 for (size_t i = 0; i < outputTracks.size(); i++) {
2055 if (outputTracks[i]->isActive()) {
2056 sleepTime = 0;
2057 writeFrames = 0;
2058 break;
2059 }
2060 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002061 }
2062 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002063
2064 if (mSuspended) {
Eric Laurent0e49d352009-11-09 23:32:22 -08002065 sleepTime = idleSleepTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07002066 }
2067 // sleepTime == 0 means we must write to audio hardware
2068 if (sleepTime == 0) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002069 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentaef692f2009-09-22 00:35:48 -07002070 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002071 outputTracks[i]->write(curBuf, writeFrames);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002072 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002073 mStandby = false;
2074 mBytesWritten += mixBufferSize;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002075 } else {
Eric Laurentaef692f2009-09-22 00:35:48 -07002076 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002077 }
2078
2079 // finally let go of all our tracks, without the lock held
2080 // since we can't guarantee the destructors won't acquire that
2081 // same lock.
2082 tracksToRemove.clear();
2083 outputTracks.clear();
2084 }
2085
Eric Laurent9d91ad52009-07-17 12:17:14 -07002086 return false;
2087}
2088
2089void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2090{
2091 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2092 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent7e2aad12009-12-18 05:47:48 -08002093 this,
Eric Laurent9d91ad52009-07-17 12:17:14 -07002094 mSampleRate,
2095 mFormat,
2096 mChannelCount,
2097 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07002098 if (outputTrack->cblk() != NULL) {
2099 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2100 mOutputTracks.add(outputTrack);
2101 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent7e2aad12009-12-18 05:47:48 -08002102 updateWaitTime();
Eric Laurentf5aba822009-08-10 23:22:32 -07002103 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002104}
2105
2106void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2107{
2108 Mutex::Autolock _l(mLock);
2109 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2110 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07002111 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002112 mOutputTracks.removeAt(i);
Eric Laurent7e2aad12009-12-18 05:47:48 -08002113 updateWaitTime();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002114 return;
2115 }
2116 }
2117 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2118}
2119
Eric Laurent7e2aad12009-12-18 05:47:48 -08002120void AudioFlinger::DuplicatingThread::updateWaitTime()
2121{
2122 mWaitTimeMs = UINT_MAX;
2123 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2124 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2125 if (strong != NULL) {
2126 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2127 if (waitTimeMs < mWaitTimeMs) {
2128 mWaitTimeMs = waitTimeMs;
2129 }
2130 }
2131 }
2132}
2133
2134
2135bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2136{
2137 for (size_t i = 0; i < outputTracks.size(); i++) {
2138 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2139 if (thread == 0) {
2140 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2141 return false;
2142 }
2143 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2144 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2145 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2146 return false;
2147 }
2148 }
2149 return true;
2150}
2151
2152uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2153{
2154 return (mWaitTimeMs * 1000) / 2;
2155}
2156
Eric Laurent9d91ad52009-07-17 12:17:14 -07002157// ----------------------------------------------------------------------------
2158
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002159// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002160AudioFlinger::ThreadBase::TrackBase::TrackBase(
2161 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002162 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002163 uint32_t sampleRate,
2164 int format,
2165 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002166 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002168 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002169 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002170 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002171 mClient(client),
Eric Laurent6ad8c642009-09-09 05:16:08 -07002172 mCblk(0),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002173 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002174 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002175 mClientTid(-1),
2176 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002177 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002178{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002179 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2180
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002181 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002182 size_t size = sizeof(audio_track_cblk_t);
2183 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2184 if (sharedBuffer == 0) {
2185 size += bufferSize;
2186 }
2187
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002188 if (client != NULL) {
2189 mCblkMemory = client->heap()->allocate(size);
2190 if (mCblkMemory != 0) {
2191 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2192 if (mCblk) { // construct the shared structure in-place.
2193 new(mCblk) audio_track_cblk_t();
2194 // clear all buffers
2195 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002196 mCblk->sampleRate = sampleRate;
2197 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002198 if (sharedBuffer == 0) {
2199 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2200 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2201 // Force underrun condition to avoid false underrun callback until first data is
2202 // written to buffer
2203 mCblk->flowControlFlag = 1;
2204 } else {
2205 mBuffer = sharedBuffer->pointer();
2206 }
2207 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002208 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209 } else {
2210 LOGE("not enough memory for AudioTrack size=%u", size);
2211 client->heap()->dump("AudioTrack");
2212 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002213 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214 } else {
2215 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2216 if (mCblk) { // construct the shared structure in-place.
2217 new(mCblk) audio_track_cblk_t();
2218 // clear all buffers
2219 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002220 mCblk->sampleRate = sampleRate;
2221 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002222 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2223 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2224 // Force underrun condition to avoid false underrun callback until first data is
2225 // written to buffer
2226 mCblk->flowControlFlag = 1;
2227 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2228 }
2229 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002230}
2231
Eric Laurentbdc0f842009-09-16 06:02:45 -07002232AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002233{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002235 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2236 if (mClient == NULL) {
2237 delete mCblk;
2238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002240 mCblkMemory.clear(); // and free the shared memory
Eric Laurent0f8ab672009-09-17 05:12:56 -07002241 if (mClient != NULL) {
2242 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2243 mClient.clear();
2244 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002245}
2246
Eric Laurentbdc0f842009-09-16 06:02:45 -07002247void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002248{
2249 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002250 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002251 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002252 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002253}
2254
Eric Laurentbdc0f842009-09-16 06:02:45 -07002255bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002256 bool result;
2257 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002258
2259 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002260 if (!result) {
2261 LOGV("stepServer failed acquiring cblk mutex");
2262 mFlags |= STEPSERVER_FAILED;
2263 }
2264 return result;
2265}
2266
Eric Laurentbdc0f842009-09-16 06:02:45 -07002267void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002268 audio_track_cblk_t* cblk = this->cblk();
2269
2270 cblk->user = 0;
2271 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002272 cblk->userBase = 0;
2273 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002274 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002275 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002276}
2277
Eric Laurentbdc0f842009-09-16 06:02:45 -07002278sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002279{
2280 return mCblkMemory;
2281}
2282
Eric Laurentbdc0f842009-09-16 06:02:45 -07002283int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002284 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002285}
2286
Eric Laurentbdc0f842009-09-16 06:02:45 -07002287int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002288 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002289}
2290
Eric Laurentbdc0f842009-09-16 06:02:45 -07002291void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002292 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002293 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2294 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002295
2296 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002297 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2298 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002299 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2300 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002301 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002302 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002303 return 0;
2304 }
2305
2306 return bufferStart;
2307}
2308
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002309// ----------------------------------------------------------------------------
2310
Eric Laurent9d91ad52009-07-17 12:17:14 -07002311// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2312AudioFlinger::PlaybackThread::Track::Track(
2313 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002314 const sp<Client>& client,
2315 int streamType,
2316 uint32_t sampleRate,
2317 int format,
2318 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002319 int frameCount,
2320 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002321 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2322 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002323{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002324 if (mCblk != NULL) {
2325 sp<ThreadBase> baseThread = thread.promote();
2326 if (baseThread != 0) {
2327 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2328 mName = playbackThread->getTrackName_l();
2329 }
2330 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2331 if (mName < 0) {
2332 LOGE("no more track names available");
2333 }
2334 mVolume[0] = 1.0f;
2335 mVolume[1] = 1.0f;
2336 mStreamType = streamType;
2337 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2338 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2339 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002340 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002341}
2342
Eric Laurent9d91ad52009-07-17 12:17:14 -07002343AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002344{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002345 LOGV("PlaybackThread::Track destructor");
2346 sp<ThreadBase> thread = mThread.promote();
2347 if (thread != 0) {
Eric Laurentd3fc8ac2009-12-01 02:17:41 -08002348 Mutex::Autolock _l(thread->mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002349 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002350 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002351}
2352
Eric Laurent9d91ad52009-07-17 12:17:14 -07002353void AudioFlinger::PlaybackThread::Track::destroy()
2354{
2355 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2356 // by removing it from mTracks vector, so there is a risk that this Tracks's
2357 // desctructor is called. As the destructor needs to lock mLock,
2358 // we must acquire a strong reference on this Track before locking mLock
2359 // here so that the destructor is called only when exiting this function.
2360 // On the other hand, as long as Track::destroy() is only called by
2361 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2362 // this Track with its member mTrack.
2363 sp<Track> keep(this);
2364 { // scope for mLock
2365 sp<ThreadBase> thread = mThread.promote();
2366 if (thread != 0) {
Eric Laurentd3fc8ac2009-12-01 02:17:41 -08002367 if (!isOutputTrack()) {
2368 if (mState == ACTIVE || mState == RESUMING) {
2369 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2370 }
2371 AudioSystem::releaseOutput(thread->id());
Eric Laurent09b4ba82009-11-19 09:00:56 -08002372 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002373 Mutex::Autolock _l(thread->mLock);
2374 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2375 playbackThread->destroyTrack_l(this);
2376 }
2377 }
2378}
2379
2380void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002381{
Eric Laurentee47d432009-11-07 00:01:32 -08002382 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 -07002383 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002385 mStreamType,
2386 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002387 mCblk->channels,
2388 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002389 mState,
2390 mMute,
2391 mFillingUpStatus,
2392 mCblk->sampleRate,
2393 mCblk->volume[0],
2394 mCblk->volume[1],
2395 mCblk->server,
2396 mCblk->user);
2397}
2398
Eric Laurent9d91ad52009-07-17 12:17:14 -07002399status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002400{
2401 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002402 uint32_t framesReady;
2403 uint32_t framesReq = buffer->frameCount;
2404
2405 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002406 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2407 if (!step()) goto getNextBuffer_exit;
2408 LOGV("stepServer recovered");
2409 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2410 }
2411
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002412 framesReady = cblk->framesReady();
2413
2414 if (LIKELY(framesReady)) {
2415 uint32_t s = cblk->server;
2416 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2417
2418 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2419 if (framesReq > framesReady) {
2420 framesReq = framesReady;
2421 }
2422 if (s + framesReq > bufferEnd) {
2423 framesReq = bufferEnd - s;
2424 }
2425
2426 buffer->raw = getBuffer(s, framesReq);
2427 if (buffer->raw == 0) goto getNextBuffer_exit;
2428
2429 buffer->frameCount = framesReq;
2430 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002431 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002432
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002433getNextBuffer_exit:
2434 buffer->raw = 0;
2435 buffer->frameCount = 0;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002436 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 -07002437 return NOT_ENOUGH_DATA;
2438}
2439
Eric Laurent9d91ad52009-07-17 12:17:14 -07002440bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002441 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002442
2443 if (mCblk->framesReady() >= mCblk->frameCount ||
2444 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002445 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002446 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002447 return true;
2448 }
2449 return false;
2450}
2451
Eric Laurent9d91ad52009-07-17 12:17:14 -07002452status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002453{
Eric Laurent09b4ba82009-11-19 09:00:56 -08002454 status_t status = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002455 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2456 sp<ThreadBase> thread = mThread.promote();
2457 if (thread != 0) {
2458 Mutex::Autolock _l(thread->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08002459 int state = mState;
2460 // here the track could be either new, or restarted
2461 // in both cases "unstop" the track
2462 if (mState == PAUSED) {
2463 mState = TrackBase::RESUMING;
2464 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2465 } else {
2466 mState = TrackBase::ACTIVE;
2467 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2468 }
2469
2470 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2471 thread->mLock.unlock();
2472 status = AudioSystem::startOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2473 thread->mLock.lock();
2474 }
2475 if (status == NO_ERROR) {
2476 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2477 playbackThread->addTrack_l(this);
2478 } else {
2479 mState = state;
2480 }
2481 } else {
2482 status = BAD_VALUE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002483 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08002484 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002485}
2486
Eric Laurent9d91ad52009-07-17 12:17:14 -07002487void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002488{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002489 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2490 sp<ThreadBase> thread = mThread.promote();
2491 if (thread != 0) {
2492 Mutex::Autolock _l(thread->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08002493 int state = mState;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002494 if (mState > STOPPED) {
2495 mState = STOPPED;
2496 // If the track is not active (PAUSED and buffers full), flush buffers
2497 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2498 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2499 reset();
2500 }
Eric Laurentf5e868b2009-10-05 20:29:18 -07002501 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002502 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08002503 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
2504 thread->mLock.unlock();
2505 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2506 thread->mLock.lock();
2507 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002508 }
2509}
2510
Eric Laurent9d91ad52009-07-17 12:17:14 -07002511void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002512{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002513 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002514 sp<ThreadBase> thread = mThread.promote();
2515 if (thread != 0) {
2516 Mutex::Autolock _l(thread->mLock);
2517 if (mState == ACTIVE || mState == RESUMING) {
2518 mState = PAUSING;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002519 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent09b4ba82009-11-19 09:00:56 -08002520 if (!isOutputTrack()) {
2521 thread->mLock.unlock();
2522 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2523 thread->mLock.lock();
2524 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002525 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002526 }
2527}
2528
Eric Laurent9d91ad52009-07-17 12:17:14 -07002529void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002530{
2531 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002532 sp<ThreadBase> thread = mThread.promote();
2533 if (thread != 0) {
2534 Mutex::Autolock _l(thread->mLock);
2535 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2536 return;
2537 }
2538 // No point remaining in PAUSED state after a flush => go to
2539 // STOPPED state
2540 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002541
Eric Laurent9d91ad52009-07-17 12:17:14 -07002542 mCblk->lock.lock();
2543 // NOTE: reset() will reset cblk->user and cblk->server with
2544 // the risk that at the same time, the AudioMixer is trying to read
2545 // data. In this case, getNextBuffer() would return a NULL pointer
2546 // as audio buffer => the AudioMixer code MUST always test that pointer
2547 // returned by getNextBuffer() is not NULL!
2548 reset();
2549 mCblk->lock.unlock();
2550 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002551}
2552
Eric Laurent9d91ad52009-07-17 12:17:14 -07002553void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002554{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002555 // Do not reset twice to avoid discarding data written just after a flush and before
2556 // the audioflinger thread detects the track is stopped.
2557 if (!mResetDone) {
2558 TrackBase::reset();
2559 // Force underrun condition to avoid false underrun callback until first data is
2560 // written to buffer
2561 mCblk->flowControlFlag = 1;
2562 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002563 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002564 mResetDone = true;
2565 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002566}
2567
Eric Laurent9d91ad52009-07-17 12:17:14 -07002568void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002569{
2570 mMute = muted;
2571}
2572
Eric Laurent9d91ad52009-07-17 12:17:14 -07002573void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002574{
2575 mVolume[0] = left;
2576 mVolume[1] = right;
2577}
2578
2579// ----------------------------------------------------------------------------
2580
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002581// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002582AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2583 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 uint32_t sampleRate,
2586 int format,
2587 int channelCount,
2588 int frameCount,
2589 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002590 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002592 mOverflow(false)
2593{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002594 if (mCblk != NULL) {
2595 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2596 if (format == AudioSystem::PCM_16_BIT) {
2597 mCblk->frameSize = channelCount * sizeof(int16_t);
2598 } else if (format == AudioSystem::PCM_8_BIT) {
2599 mCblk->frameSize = channelCount * sizeof(int8_t);
2600 } else {
2601 mCblk->frameSize = sizeof(int8_t);
2602 }
2603 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002604}
2605
2606AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607{
Eric Laurent09b4ba82009-11-19 09:00:56 -08002608 sp<ThreadBase> thread = mThread.promote();
2609 if (thread != 0) {
2610 AudioSystem::releaseInput(thread->id());
2611 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002612}
2613
Eric Laurent9d91ad52009-07-17 12:17:14 -07002614status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615{
2616 audio_track_cblk_t* cblk = this->cblk();
2617 uint32_t framesAvail;
2618 uint32_t framesReq = buffer->frameCount;
2619
2620 // Check if last stepServer failed, try to step now
2621 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2622 if (!step()) goto getNextBuffer_exit;
2623 LOGV("stepServer recovered");
2624 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2625 }
2626
2627 framesAvail = cblk->framesAvailable_l();
2628
2629 if (LIKELY(framesAvail)) {
2630 uint32_t s = cblk->server;
2631 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2632
2633 if (framesReq > framesAvail) {
2634 framesReq = framesAvail;
2635 }
2636 if (s + framesReq > bufferEnd) {
2637 framesReq = bufferEnd - s;
2638 }
2639
2640 buffer->raw = getBuffer(s, framesReq);
2641 if (buffer->raw == 0) goto getNextBuffer_exit;
2642
2643 buffer->frameCount = framesReq;
2644 return NO_ERROR;
2645 }
2646
2647getNextBuffer_exit:
2648 buffer->raw = 0;
2649 buffer->frameCount = 0;
2650 return NOT_ENOUGH_DATA;
2651}
2652
Eric Laurent9d91ad52009-07-17 12:17:14 -07002653status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002655 sp<ThreadBase> thread = mThread.promote();
2656 if (thread != 0) {
2657 RecordThread *recordThread = (RecordThread *)thread.get();
2658 return recordThread->start(this);
Eric Laurent09b4ba82009-11-19 09:00:56 -08002659 } else {
2660 return BAD_VALUE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662}
2663
Eric Laurent9d91ad52009-07-17 12:17:14 -07002664void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002666 sp<ThreadBase> thread = mThread.promote();
2667 if (thread != 0) {
2668 RecordThread *recordThread = (RecordThread *)thread.get();
2669 recordThread->stop(this);
2670 TrackBase::reset();
2671 // Force overerrun condition to avoid false overrun callback until first data is
2672 // read from buffer
2673 mCblk->flowControlFlag = 1;
2674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675}
2676
Eric Laurentee47d432009-11-07 00:01:32 -08002677void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
2678{
2679 snprintf(buffer, size, " %05d %03u %03u %04u %01d %05u %08x %08x\n",
2680 (mClient == NULL) ? getpid() : mClient->pid(),
2681 mFormat,
2682 mCblk->channels,
2683 mFrameCount,
2684 mState,
2685 mCblk->sampleRate,
2686 mCblk->server,
2687 mCblk->user);
2688}
2689
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690
2691// ----------------------------------------------------------------------------
2692
Eric Laurent9d91ad52009-07-17 12:17:14 -07002693AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2694 const wp<ThreadBase>& thread,
Eric Laurent7e2aad12009-12-18 05:47:48 -08002695 DuplicatingThread *sourceThread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 uint32_t sampleRate,
2697 int format,
2698 int channelCount,
2699 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002700 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
Eric Laurent7e2aad12009-12-18 05:47:48 -08002701 mActive(false), mSourceThread(sourceThread)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002703
2704 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002705 if (mCblk != NULL) {
2706 mCblk->out = 1;
2707 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2708 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2709 mOutBuffer.frameCount = 0;
Eric Laurentf5aba822009-08-10 23:22:32 -07002710 playbackThread->mTracks.add(this);
Eric Laurent7e2aad12009-12-18 05:47:48 -08002711 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p",
2712 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd);
Eric Laurentf5aba822009-08-10 23:22:32 -07002713 } else {
2714 LOGW("Error creating output track on thread %p", playbackThread);
2715 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716}
2717
Eric Laurent9d91ad52009-07-17 12:17:14 -07002718AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719{
Eric Laurentf5aba822009-08-10 23:22:32 -07002720 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002721}
2722
Eric Laurent9d91ad52009-07-17 12:17:14 -07002723status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002724{
2725 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002726 if (status != NO_ERROR) {
2727 return status;
2728 }
2729
2730 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002731 mRetryCount = 127;
2732 return status;
2733}
2734
Eric Laurent9d91ad52009-07-17 12:17:14 -07002735void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736{
2737 Track::stop();
2738 clearBufferQueue();
2739 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002740 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741}
2742
Eric Laurent9d91ad52009-07-17 12:17:14 -07002743bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744{
2745 Buffer *pInBuffer;
2746 Buffer inBuffer;
2747 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002748 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749 inBuffer.frameCount = frames;
2750 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002751
Eric Laurent7e2aad12009-12-18 05:47:48 -08002752 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002753
Eric Laurentf5e868b2009-10-05 20:29:18 -07002754 if (!mActive && frames != 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002755 start();
2756 sp<ThreadBase> thread = mThread.promote();
2757 if (thread != 0) {
2758 MixerThread *mixerThread = (MixerThread *)thread.get();
2759 if (mCblk->frameCount > frames){
2760 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2761 uint32_t startFrames = (mCblk->frameCount - frames);
2762 pInBuffer = new Buffer;
2763 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2764 pInBuffer->frameCount = startFrames;
2765 pInBuffer->i16 = pInBuffer->mBuffer;
2766 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2767 mBufferQueue.add(pInBuffer);
2768 } else {
2769 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2770 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002772 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 }
2774
Eric Laurent9d91ad52009-07-17 12:17:14 -07002775 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 // First write pending buffers, then new data
2777 if (mBufferQueue.size()) {
2778 pInBuffer = mBufferQueue.itemAt(0);
2779 } else {
2780 pInBuffer = &inBuffer;
2781 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002782
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 if (pInBuffer->frameCount == 0) {
2784 break;
2785 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002786
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002787 if (mOutBuffer.frameCount == 0) {
2788 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002789 nsecs_t startTime = systemTime();
2790 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent7e2aad12009-12-18 05:47:48 -08002791 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002792 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 break;
2794 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002795 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002796 if (waitTimeLeftMs >= waitTimeMs) {
2797 waitTimeLeftMs -= waitTimeMs;
2798 } else {
2799 waitTimeLeftMs = 0;
2800 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002802
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2804 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2805 mCblk->stepUser(outFrames);
2806 pInBuffer->frameCount -= outFrames;
2807 pInBuffer->i16 += outFrames * channels;
2808 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002809 mOutBuffer.i16 += outFrames * channels;
2810
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 if (pInBuffer->frameCount == 0) {
2812 if (mBufferQueue.size()) {
2813 mBufferQueue.removeAt(0);
2814 delete [] pInBuffer->mBuffer;
2815 delete pInBuffer;
Eric Laurent7e2aad12009-12-18 05:47:48 -08002816 LOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 } else {
2818 break;
2819 }
2820 }
2821 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002822
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823 // If we could not write all frames, allocate a buffer and queue it for next time.
2824 if (inBuffer.frameCount) {
Eric Laurent7e2aad12009-12-18 05:47:48 -08002825 sp<ThreadBase> thread = mThread.promote();
2826 if (thread != 0 && !thread->standby()) {
2827 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2828 pInBuffer = new Buffer;
2829 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2830 pInBuffer->frameCount = inBuffer.frameCount;
2831 pInBuffer->i16 = pInBuffer->mBuffer;
2832 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2833 mBufferQueue.add(pInBuffer);
2834 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
2835 } else {
2836 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
2837 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 }
2839 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002840
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002842 // 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 -08002843 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002844 if (frames == 0 && mBufferQueue.size() == 0) {
2845 if (mCblk->user < mCblk->frameCount) {
2846 frames = mCblk->frameCount - mCblk->user;
2847 pInBuffer = new Buffer;
2848 pInBuffer->mBuffer = new int16_t[frames * channels];
2849 pInBuffer->frameCount = frames;
2850 pInBuffer->i16 = pInBuffer->mBuffer;
2851 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2852 mBufferQueue.add(pInBuffer);
Eric Laurentf5e868b2009-10-05 20:29:18 -07002853 } else if (mActive) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002854 stop();
2855 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 }
2857
Eric Laurent9d91ad52009-07-17 12:17:14 -07002858 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859}
2860
Eric Laurent9d91ad52009-07-17 12:17:14 -07002861status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862{
2863 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 status_t result;
2865 audio_track_cblk_t* cblk = mCblk;
2866 uint32_t framesReq = buffer->frameCount;
2867
Eric Laurent9d91ad52009-07-17 12:17:14 -07002868// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002870
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 uint32_t framesAvail = cblk->framesAvailable();
2872
Eric Laurent9d91ad52009-07-17 12:17:14 -07002873
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002875 Mutex::Autolock _l(cblk->lock);
2876 goto start_loop_here;
2877 while (framesAvail == 0) {
2878 active = mActive;
2879 if (UNLIKELY(!active)) {
2880 LOGV("Not active and NO_MORE_BUFFERS");
2881 return AudioTrack::NO_MORE_BUFFERS;
2882 }
2883 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2884 if (result != NO_ERROR) {
2885 return AudioTrack::NO_MORE_BUFFERS;
2886 }
2887 // read the server count again
2888 start_loop_here:
2889 framesAvail = cblk->framesAvailable_l();
2890 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 }
2892
Eric Laurent9d91ad52009-07-17 12:17:14 -07002893// if (framesAvail < framesReq) {
2894// return AudioTrack::NO_MORE_BUFFERS;
2895// }
2896
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897 if (framesReq > framesAvail) {
2898 framesReq = framesAvail;
2899 }
2900
2901 uint32_t u = cblk->user;
2902 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2903
2904 if (u + framesReq > bufferEnd) {
2905 framesReq = bufferEnd - u;
2906 }
2907
2908 buffer->frameCount = framesReq;
2909 buffer->raw = (void *)cblk->buffer(u);
2910 return NO_ERROR;
2911}
2912
2913
Eric Laurent9d91ad52009-07-17 12:17:14 -07002914void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915{
2916 size_t size = mBufferQueue.size();
2917 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002918
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002919 for (size_t i = 0; i < size; i++) {
2920 pBuffer = mBufferQueue.itemAt(i);
2921 delete [] pBuffer->mBuffer;
2922 delete pBuffer;
2923 }
2924 mBufferQueue.clear();
2925}
2926
2927// ----------------------------------------------------------------------------
2928
2929AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2930 : RefBase(),
2931 mAudioFlinger(audioFlinger),
2932 mMemoryDealer(new MemoryDealer(1024*1024)),
2933 mPid(pid)
2934{
2935 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2936}
2937
Eric Laurent0f8ab672009-09-17 05:12:56 -07002938// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002939AudioFlinger::Client::~Client()
2940{
Eric Laurent0f8ab672009-09-17 05:12:56 -07002941 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942}
2943
2944const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2945{
2946 return mMemoryDealer;
2947}
2948
2949// ----------------------------------------------------------------------------
2950
Eric Laurent9d91ad52009-07-17 12:17:14 -07002951AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002952 : BnAudioTrack(),
2953 mTrack(track)
2954{
2955}
2956
2957AudioFlinger::TrackHandle::~TrackHandle() {
2958 // just stop the track on deletion, associated resources
2959 // will be freed from the main thread once all pending buffers have
2960 // been played. Unless it's not in the active track list, in which
2961 // case we free everything now...
2962 mTrack->destroy();
2963}
2964
2965status_t AudioFlinger::TrackHandle::start() {
2966 return mTrack->start();
2967}
2968
2969void AudioFlinger::TrackHandle::stop() {
2970 mTrack->stop();
2971}
2972
2973void AudioFlinger::TrackHandle::flush() {
2974 mTrack->flush();
2975}
2976
2977void AudioFlinger::TrackHandle::mute(bool e) {
2978 mTrack->mute(e);
2979}
2980
2981void AudioFlinger::TrackHandle::pause() {
2982 mTrack->pause();
2983}
2984
2985void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2986 mTrack->setVolume(left, right);
2987}
2988
2989sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2990 return mTrack->getCblk();
2991}
2992
2993status_t AudioFlinger::TrackHandle::onTransact(
2994 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2995{
2996 return BnAudioTrack::onTransact(code, data, reply, flags);
2997}
2998
2999// ----------------------------------------------------------------------------
3000
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003001sp<IAudioRecord> AudioFlinger::openRecord(
3002 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003003 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003004 uint32_t sampleRate,
3005 int format,
3006 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003007 int frameCount,
3008 uint32_t flags,
3009 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003010{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003011 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003012 sp<RecordHandle> recordHandle;
3013 sp<Client> client;
3014 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003015 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003016 RecordThread *thread;
3017 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003018
3019 // check calling permissions
3020 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003021 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003022 goto Exit;
3023 }
3024
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003025 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07003026 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003027 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003028 thread = checkRecordThread_l(input);
3029 if (thread == NULL) {
3030 lStatus = BAD_VALUE;
3031 goto Exit;
3032 }
3033
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003034 wclient = mClients.valueFor(pid);
3035 if (wclient != NULL) {
3036 client = wclient.promote();
3037 } else {
3038 client = new Client(this, pid);
3039 mClients.add(pid, client);
3040 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07003041
The Android Open Source Project22f8def2009-03-09 11:52:12 -07003042 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07003043 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07003044 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003045 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046 if (recordTrack->getCblk() == NULL) {
Eric Laurent0f8ab672009-09-17 05:12:56 -07003047 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3048 // destructor is called by the TrackBase destructor with mLock held
3049 client.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 recordTrack.clear();
3051 lStatus = NO_MEMORY;
3052 goto Exit;
3053 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003054
3055 // return to handle to client
3056 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003057 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003058
3059Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003060 if (status) {
3061 *status = lStatus;
3062 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003063 return recordHandle;
3064}
3065
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003066// ----------------------------------------------------------------------------
3067
Eric Laurent9d91ad52009-07-17 12:17:14 -07003068AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003069 : BnAudioRecord(),
3070 mRecordTrack(recordTrack)
3071{
3072}
3073
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003074AudioFlinger::RecordHandle::~RecordHandle() {
3075 stop();
3076}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003077
3078status_t AudioFlinger::RecordHandle::start() {
3079 LOGV("RecordHandle::start()");
3080 return mRecordTrack->start();
3081}
3082
3083void AudioFlinger::RecordHandle::stop() {
3084 LOGV("RecordHandle::stop()");
3085 mRecordTrack->stop();
3086}
3087
3088sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3089 return mRecordTrack->getCblk();
3090}
3091
3092status_t AudioFlinger::RecordHandle::onTransact(
3093 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3094{
3095 return BnAudioRecord::onTransact(code, data, reply, flags);
3096}
3097
3098// ----------------------------------------------------------------------------
3099
Eric Laurent09b4ba82009-11-19 09:00:56 -08003100AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3101 ThreadBase(audioFlinger, id),
Eric Laurent9d91ad52009-07-17 12:17:14 -07003102 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003103{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003104 mReqChannelCount = AudioSystem::popCount(channels);
3105 mReqSampleRate = sampleRate;
3106 readInputParameters();
3107 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003108}
3109
Eric Laurent9d91ad52009-07-17 12:17:14 -07003110
3111AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003112{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003113 delete[] mRsmpInBuffer;
3114 if (mResampler != 0) {
3115 delete mResampler;
3116 delete[] mRsmpOutBuffer;
3117 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003118}
3119
Eric Laurent9d91ad52009-07-17 12:17:14 -07003120void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003121{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003122 const size_t SIZE = 256;
3123 char buffer[SIZE];
3124
3125 snprintf(buffer, SIZE, "Record Thread %p", this);
3126
3127 run(buffer, PRIORITY_URGENT_AUDIO);
3128}
Eric Laurent09b4ba82009-11-19 09:00:56 -08003129
Eric Laurent9d91ad52009-07-17 12:17:14 -07003130bool AudioFlinger::RecordThread::threadLoop()
3131{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003132 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003133 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003134
3135 // start recording
3136 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003137
Eric Laurent9d91ad52009-07-17 12:17:14 -07003138 processConfigEvents();
3139
3140 { // scope for mLock
3141 Mutex::Autolock _l(mLock);
3142 checkForNewParameters_l();
3143 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3144 if (!mStandby) {
3145 mInput->standby();
3146 mStandby = true;
3147 }
3148
3149 if (exitPending()) break;
3150
3151 LOGV("RecordThread: loop stopping");
3152 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003153 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003154 LOGV("RecordThread: loop starting");
3155 continue;
3156 }
3157 if (mActiveTrack != 0) {
3158 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent52910952009-12-05 05:20:01 -08003159 if (!mStandby) {
3160 mInput->standby();
3161 mStandby = true;
3162 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003163 mActiveTrack.clear();
3164 mStartStopCond.broadcast();
3165 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003166 if (mReqChannelCount != mActiveTrack->channelCount()) {
3167 mActiveTrack.clear();
Eric Laurent52910952009-12-05 05:20:01 -08003168 mStartStopCond.broadcast();
3169 } else if (mBytesRead != 0) {
3170 // record start succeeds only if first read from audio input
3171 // succeeds
3172 if (mBytesRead > 0) {
3173 mActiveTrack->mState = TrackBase::ACTIVE;
3174 } else {
3175 mActiveTrack.clear();
3176 }
3177 mStartStopCond.broadcast();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003178 }
Eric Laurent52910952009-12-05 05:20:01 -08003179 mStandby = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003180 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003181 }
3182 }
3183
3184 if (mActiveTrack != 0) {
Eric Laurent52910952009-12-05 05:20:01 -08003185 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3186 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent09b4ba82009-11-19 09:00:56 -08003187 usleep(5000);
3188 continue;
3189 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003190 buffer.frameCount = mFrameCount;
3191 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3192 size_t framesOut = buffer.frameCount;
3193 if (mResampler == 0) {
3194 // no resampling
3195 while (framesOut) {
3196 size_t framesIn = mFrameCount - mRsmpInIndex;
3197 if (framesIn) {
3198 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3199 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3200 if (framesIn > framesOut)
3201 framesIn = framesOut;
3202 mRsmpInIndex += framesIn;
3203 framesOut -= framesIn;
3204 if (mChannelCount == mReqChannelCount ||
3205 mFormat != AudioSystem::PCM_16_BIT) {
3206 memcpy(dst, src, framesIn * mFrameSize);
3207 } else {
3208 int16_t *src16 = (int16_t *)src;
3209 int16_t *dst16 = (int16_t *)dst;
3210 if (mChannelCount == 1) {
3211 while (framesIn--) {
3212 *dst16++ = *src16;
3213 *dst16++ = *src16++;
3214 }
3215 } else {
3216 while (framesIn--) {
3217 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3218 src16 += 2;
3219 }
3220 }
3221 }
3222 }
3223 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003224 if (framesOut == mFrameCount &&
3225 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent52910952009-12-05 05:20:01 -08003226 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003227 framesOut = 0;
3228 } else {
Eric Laurent52910952009-12-05 05:20:01 -08003229 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003230 mRsmpInIndex = 0;
3231 }
Eric Laurent52910952009-12-05 05:20:01 -08003232 if (mBytesRead < 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003233 LOGE("Error reading audio input");
Eric Laurent52910952009-12-05 05:20:01 -08003234 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3235 sleep(1);
3236 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003237 mRsmpInIndex = mFrameCount;
3238 framesOut = 0;
3239 buffer.frameCount = 0;
3240 }
3241 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003242 }
3243 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003244 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003245
Eric Laurent9d91ad52009-07-17 12:17:14 -07003246 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3247 // alter output frame count as if we were expecting stereo samples
3248 if (mChannelCount == 1 && mReqChannelCount == 1) {
3249 framesOut >>= 1;
3250 }
3251 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3252 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3253 // are 32 bit aligned which should be always true.
3254 if (mChannelCount == 2 && mReqChannelCount == 1) {
3255 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3256 // the resampler always outputs stereo samples: do post stereo to mono conversion
3257 int16_t *src = (int16_t *)mRsmpOutBuffer;
3258 int16_t *dst = buffer.i16;
3259 while (framesOut--) {
3260 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3261 src += 2;
3262 }
3263 } else {
3264 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3265 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003266
Eric Laurent9d91ad52009-07-17 12:17:14 -07003267 }
3268 mActiveTrack->releaseBuffer(&buffer);
3269 mActiveTrack->overflow();
3270 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003271 // client isn't retrieving buffers fast enough
3272 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003273 if (!mActiveTrack->setOverflow())
3274 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003275 // Release the processor for a while before asking for a new buffer.
3276 // This will give the application more chance to read from the buffer and
3277 // clear the overflow.
3278 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003279 }
3280 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003281 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003282
Eric Laurent9d91ad52009-07-17 12:17:14 -07003283 if (!mStandby) {
3284 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003285 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003286 mActiveTrack.clear();
3287
Eric Laurent09b4ba82009-11-19 09:00:56 -08003288 mStartStopCond.broadcast();
3289
Eric Laurent9d91ad52009-07-17 12:17:14 -07003290 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003291 return false;
3292}
3293
Eric Laurent9d91ad52009-07-17 12:17:14 -07003294status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003295{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003296 LOGV("RecordThread::start");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003297 sp <ThreadBase> strongMe = this;
3298 status_t status = NO_ERROR;
3299 {
3300 AutoMutex lock(&mLock);
3301 if (mActiveTrack != 0) {
3302 if (recordTrack != mActiveTrack.get()) {
3303 status = -EBUSY;
3304 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent52910952009-12-05 05:20:01 -08003305 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003306 }
3307 return status;
3308 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003309
Eric Laurent09b4ba82009-11-19 09:00:56 -08003310 recordTrack->mState = TrackBase::IDLE;
3311 mActiveTrack = recordTrack;
3312 mLock.unlock();
3313 status_t status = AudioSystem::startInput(mId);
3314 mLock.lock();
3315 if (status != NO_ERROR) {
3316 mActiveTrack.clear();
3317 return status;
3318 }
3319 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent52910952009-12-05 05:20:01 -08003320 mRsmpInIndex = mFrameCount;
3321 mBytesRead = 0;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003322 // signal thread to start
3323 LOGV("Signal record thread");
3324 mWaitWorkCV.signal();
3325 // do not wait for mStartStopCond if exiting
3326 if (mExiting) {
3327 mActiveTrack.clear();
3328 status = INVALID_OPERATION;
3329 goto startError;
3330 }
3331 mStartStopCond.wait(mLock);
3332 if (mActiveTrack == 0) {
3333 LOGV("Record failed to start");
3334 status = BAD_VALUE;
3335 goto startError;
3336 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003337 LOGV("Record started OK");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003338 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003339 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08003340startError:
3341 AudioSystem::stopInput(mId);
3342 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003343}
3344
Eric Laurent9d91ad52009-07-17 12:17:14 -07003345void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3346 LOGV("RecordThread::stop");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003347 sp <ThreadBase> strongMe = this;
3348 {
3349 AutoMutex lock(&mLock);
3350 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3351 mActiveTrack->mState = TrackBase::PAUSING;
3352 // do not wait for mStartStopCond if exiting
3353 if (mExiting) {
3354 return;
3355 }
3356 mStartStopCond.wait(mLock);
3357 // if we have been restarted, recordTrack == mActiveTrack.get() here
3358 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3359 mLock.unlock();
3360 AudioSystem::stopInput(mId);
3361 mLock.lock();
Eric Laurent52910952009-12-05 05:20:01 -08003362 LOGV("Record stopped OK");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003363 }
3364 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003365 }
3366}
3367
Eric Laurent9d91ad52009-07-17 12:17:14 -07003368status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369{
3370 const size_t SIZE = 256;
3371 char buffer[SIZE];
3372 String8 result;
3373 pid_t pid = 0;
3374
Eric Laurentee47d432009-11-07 00:01:32 -08003375 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3376 result.append(buffer);
3377
3378 if (mActiveTrack != 0) {
3379 result.append("Active Track:\n");
3380 result.append(" Clien Fmt Chn Buf S SRate Serv User\n");
3381 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -08003383
3384 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3385 result.append(buffer);
3386 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3387 result.append(buffer);
3388 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3389 result.append(buffer);
3390 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3391 result.append(buffer);
3392 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3393 result.append(buffer);
3394
3395
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003396 } else {
3397 result.append("No record client\n");
3398 }
3399 write(fd, result.string(), result.size());
Eric Laurentee47d432009-11-07 00:01:32 -08003400
3401 dumpBase(fd, args);
3402
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003403 return NO_ERROR;
3404}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003405
Eric Laurent9d91ad52009-07-17 12:17:14 -07003406status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3407{
3408 size_t framesReq = buffer->frameCount;
3409 size_t framesReady = mFrameCount - mRsmpInIndex;
3410 int channelCount;
3411
3412 if (framesReady == 0) {
Eric Laurent52910952009-12-05 05:20:01 -08003413 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3414 if (mBytesRead < 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003415 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent52910952009-12-05 05:20:01 -08003416 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3417 sleep(1);
3418 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003419 buffer->raw = 0;
3420 buffer->frameCount = 0;
3421 return NOT_ENOUGH_DATA;
3422 }
3423 mRsmpInIndex = 0;
3424 framesReady = mFrameCount;
3425 }
3426
3427 if (framesReq > framesReady) {
3428 framesReq = framesReady;
3429 }
3430
3431 if (mChannelCount == 1 && mReqChannelCount == 2) {
3432 channelCount = 1;
3433 } else {
3434 channelCount = 2;
3435 }
3436 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3437 buffer->frameCount = framesReq;
3438 return NO_ERROR;
3439}
3440
3441void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3442{
3443 mRsmpInIndex += buffer->frameCount;
3444 buffer->frameCount = 0;
3445}
3446
3447bool AudioFlinger::RecordThread::checkForNewParameters_l()
3448{
3449 bool reconfig = false;
3450
Eric Laurent3464c012009-08-04 09:45:33 -07003451 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003452 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003453 String8 keyValuePair = mNewParameters[0];
3454 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003455 int value;
3456 int reqFormat = mFormat;
3457 int reqSamplingRate = mReqSampleRate;
3458 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003459
Eric Laurent9d91ad52009-07-17 12:17:14 -07003460 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3461 reqSamplingRate = value;
3462 reconfig = true;
3463 }
3464 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3465 reqFormat = value;
3466 reconfig = true;
3467 }
3468 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3469 reqChannelCount = AudioSystem::popCount(value);
3470 reconfig = true;
3471 }
3472 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3473 // do not accept frame count changes if tracks are open as the track buffer
3474 // size depends on frame count and correct behavior would not be garantied
3475 // if frame count is changed after track creation
3476 if (mActiveTrack != 0) {
3477 status = INVALID_OPERATION;
3478 } else {
3479 reconfig = true;
3480 }
3481 }
3482 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003483 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003484 if (status == INVALID_OPERATION) {
3485 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003486 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003487 }
3488 if (reconfig) {
3489 if (status == BAD_VALUE &&
3490 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3491 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3492 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3493 status = NO_ERROR;
3494 }
3495 if (status == NO_ERROR) {
3496 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003497 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003498 }
3499 }
3500 }
Eric Laurentee47d432009-11-07 00:01:32 -08003501
3502 mNewParameters.removeAt(0);
3503
Eric Laurent9d91ad52009-07-17 12:17:14 -07003504 mParamStatus = status;
3505 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003506 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003507 }
3508 return reconfig;
3509}
3510
3511String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3512{
3513 return mInput->getParameters(keys);
3514}
3515
3516void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3517 AudioSystem::OutputDescriptor desc;
3518 void *param2 = 0;
3519
3520 switch (event) {
3521 case AudioSystem::INPUT_OPENED:
3522 case AudioSystem::INPUT_CONFIG_CHANGED:
3523 desc.channels = mChannelCount;
3524 desc.samplingRate = mSampleRate;
3525 desc.format = mFormat;
3526 desc.frameCount = mFrameCount;
3527 desc.latency = 0;
3528 param2 = &desc;
3529 break;
3530
3531 case AudioSystem::INPUT_CLOSED:
3532 default:
3533 break;
3534 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003535 Mutex::Autolock _l(mAudioFlinger->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08003536 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003537}
3538
3539void AudioFlinger::RecordThread::readInputParameters()
3540{
3541 if (mRsmpInBuffer) delete mRsmpInBuffer;
3542 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3543 if (mResampler) delete mResampler;
3544 mResampler = 0;
3545
3546 mSampleRate = mInput->sampleRate();
3547 mChannelCount = AudioSystem::popCount(mInput->channels());
3548 mFormat = mInput->format();
3549 mFrameSize = mInput->frameSize();
3550 mInputBytes = mInput->bufferSize();
3551 mFrameCount = mInputBytes / mFrameSize;
3552 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3553
3554 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3555 {
3556 int channelCount;
3557 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3558 // stereo to mono post process as the resampler always outputs stereo.
3559 if (mChannelCount == 1 && mReqChannelCount == 2) {
3560 channelCount = 1;
3561 } else {
3562 channelCount = 2;
3563 }
3564 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3565 mResampler->setSampleRate(mSampleRate);
3566 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3567 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3568
3569 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3570 if (mChannelCount == 1 && mReqChannelCount == 1) {
3571 mFrameCount >>= 1;
3572 }
3573
3574 }
3575 mRsmpInIndex = mFrameCount;
3576}
3577
3578// ----------------------------------------------------------------------------
3579
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003580int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003581 uint32_t *pSamplingRate,
3582 uint32_t *pFormat,
3583 uint32_t *pChannels,
3584 uint32_t *pLatencyMs,
3585 uint32_t flags)
3586{
3587 status_t status;
3588 PlaybackThread *thread = NULL;
3589 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3590 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3591 uint32_t format = pFormat ? *pFormat : 0;
3592 uint32_t channels = pChannels ? *pChannels : 0;
3593 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3594
3595 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3596 pDevices ? *pDevices : 0,
3597 samplingRate,
3598 format,
3599 channels,
3600 flags);
3601
3602 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003603 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003604 }
3605 Mutex::Autolock _l(mLock);
3606
3607 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3608 (int *)&format,
3609 &channels,
3610 &samplingRate,
3611 &status);
3612 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3613 output,
3614 samplingRate,
3615 format,
3616 channels,
3617 status);
3618
3619 mHardwareStatus = AUDIO_HW_IDLE;
3620 if (output != 0) {
3621 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3622 (format != AudioSystem::PCM_16_BIT) ||
3623 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent09b4ba82009-11-19 09:00:56 -08003624 thread = new DirectOutputThread(this, output, ++mNextThreadId);
3625 LOGV("openOutput() created direct output: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003626 } else {
Eric Laurent09b4ba82009-11-19 09:00:56 -08003627 thread = new MixerThread(this, output, ++mNextThreadId);
3628 LOGV("openOutput() created mixer output: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003629 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08003630 mPlaybackThreads.add(mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003631
3632 if (pSamplingRate) *pSamplingRate = samplingRate;
3633 if (pFormat) *pFormat = format;
3634 if (pChannels) *pChannels = channels;
3635 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent52910952009-12-05 05:20:01 -08003636
3637 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003638 }
3639
Eric Laurent52910952009-12-05 05:20:01 -08003640 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003641}
3642
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003643int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003644{
3645 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003646 MixerThread *thread1 = checkMixerThread_l(output1);
3647 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003648
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003649 if (thread1 == NULL || thread2 == NULL) {
3650 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3651 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003652 }
3653
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003654
Eric Laurent09b4ba82009-11-19 09:00:56 -08003655 DuplicatingThread *thread = new DuplicatingThread(this, thread1, ++mNextThreadId);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003656 thread->addOutputTrack(thread2);
Eric Laurent09b4ba82009-11-19 09:00:56 -08003657 mPlaybackThreads.add(mNextThreadId, thread);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003658 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003659}
3660
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003661status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003662{
Eric Laurentdae20d92009-08-04 08:37:05 -07003663 // keep strong reference on the playback thread so that
3664 // it is not destroyed while exit() is executed
3665 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003666 {
3667 Mutex::Autolock _l(mLock);
3668 thread = checkPlaybackThread_l(output);
3669 if (thread == NULL) {
3670 return BAD_VALUE;
3671 }
3672
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003673 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003674
3675 if (thread->type() == PlaybackThread::MIXER) {
3676 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003677 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3678 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003679 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003680 }
3681 }
3682 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003683 void *param2 = 0;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003684 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003685 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003686 }
3687 thread->exit();
3688
Eric Laurentdae20d92009-08-04 08:37:05 -07003689 if (thread->type() != PlaybackThread::DUPLICATING) {
3690 mAudioHardware->closeOutputStream(thread->getOutput());
3691 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003692 return NO_ERROR;
3693}
3694
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003695status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003696{
3697 Mutex::Autolock _l(mLock);
3698 PlaybackThread *thread = checkPlaybackThread_l(output);
3699
3700 if (thread == NULL) {
3701 return BAD_VALUE;
3702 }
3703
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003704 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003705 thread->suspend();
3706
3707 return NO_ERROR;
3708}
3709
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003710status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003711{
3712 Mutex::Autolock _l(mLock);
3713 PlaybackThread *thread = checkPlaybackThread_l(output);
3714
3715 if (thread == NULL) {
3716 return BAD_VALUE;
3717 }
3718
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003719 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003720
3721 thread->restore();
3722
3723 return NO_ERROR;
3724}
3725
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003726int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003727 uint32_t *pSamplingRate,
3728 uint32_t *pFormat,
3729 uint32_t *pChannels,
3730 uint32_t acoustics)
3731{
3732 status_t status;
3733 RecordThread *thread = NULL;
3734 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3735 uint32_t format = pFormat ? *pFormat : 0;
3736 uint32_t channels = pChannels ? *pChannels : 0;
3737 uint32_t reqSamplingRate = samplingRate;
3738 uint32_t reqFormat = format;
3739 uint32_t reqChannels = channels;
3740
3741 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003742 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003743 }
3744 Mutex::Autolock _l(mLock);
3745
3746 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3747 (int *)&format,
3748 &channels,
3749 &samplingRate,
3750 &status,
3751 (AudioSystem::audio_in_acoustics)acoustics);
3752 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3753 input,
3754 samplingRate,
3755 format,
3756 channels,
3757 acoustics,
3758 status);
3759
3760 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3761 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3762 // or stereo to mono conversions on 16 bit PCM inputs.
3763 if (input == 0 && status == BAD_VALUE &&
3764 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3765 (samplingRate <= 2 * reqSamplingRate) &&
3766 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3767 LOGV("openInput() reopening with proposed sampling rate and channels");
3768 input = mAudioHardware->openInputStream(*pDevices,
3769 (int *)&format,
3770 &channels,
3771 &samplingRate,
3772 &status,
3773 (AudioSystem::audio_in_acoustics)acoustics);
3774 }
3775
3776 if (input != 0) {
3777 // Start record thread
Eric Laurent09b4ba82009-11-19 09:00:56 -08003778 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, ++mNextThreadId);
3779 mRecordThreads.add(mNextThreadId, thread);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003780 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003781 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3782 if (pFormat) *pFormat = format;
3783 if (pChannels) *pChannels = reqChannels;
3784
3785 input->standby();
Eric Laurent52910952009-12-05 05:20:01 -08003786
3787 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003788 }
3789
Eric Laurent52910952009-12-05 05:20:01 -08003790 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003791}
3792
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003793status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003794{
Eric Laurentdae20d92009-08-04 08:37:05 -07003795 // keep strong reference on the record thread so that
3796 // it is not destroyed while exit() is executed
3797 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003798 {
3799 Mutex::Autolock _l(mLock);
3800 thread = checkRecordThread_l(input);
3801 if (thread == NULL) {
3802 return BAD_VALUE;
3803 }
3804
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003805 LOGV("closeInput() %d", input);
Eric Laurentb3687ae2009-09-15 07:10:12 -07003806 void *param2 = 0;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003807 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003808 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003809 }
3810 thread->exit();
3811
Eric Laurentdae20d92009-08-04 08:37:05 -07003812 mAudioHardware->closeInputStream(thread->getInput());
3813
Eric Laurent9d91ad52009-07-17 12:17:14 -07003814 return NO_ERROR;
3815}
3816
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003817status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003818{
3819 Mutex::Autolock _l(mLock);
3820 MixerThread *dstThread = checkMixerThread_l(output);
3821 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003822 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003823 return BAD_VALUE;
3824 }
3825
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003826 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003827
3828 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003829 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003830 if (thread != dstThread &&
3831 thread->type() != PlaybackThread::DIRECT) {
3832 MixerThread *srcThread = (MixerThread *)thread;
3833 SortedVector < sp<MixerThread::Track> > tracks;
3834 SortedVector < wp<MixerThread::Track> > activeTracks;
3835 srcThread->getTracks(tracks, activeTracks, stream);
3836 if (tracks.size()) {
3837 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003838 }
3839 }
3840 }
3841
Eric Laurent06437712009-09-01 05:56:26 -07003842 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
3843
Eric Laurent9d91ad52009-07-17 12:17:14 -07003844 return NO_ERROR;
3845}
3846
3847// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003848AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003849{
3850 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003851 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3852 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003853 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003854 return thread;
3855}
3856
3857// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003858AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003859{
3860 PlaybackThread *thread = checkPlaybackThread_l(output);
3861 if (thread != NULL) {
3862 if (thread->type() == PlaybackThread::DIRECT) {
3863 thread = NULL;
3864 }
3865 }
3866 return (MixerThread *)thread;
3867}
3868
3869// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003870AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003871{
3872 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003873 if (mRecordThreads.indexOfKey(input) >= 0) {
3874 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003875 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003876 return thread;
3877}
3878
3879// ----------------------------------------------------------------------------
3880
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003881status_t AudioFlinger::onTransact(
3882 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3883{
3884 return BnAudioFlinger::onTransact(code, data, reply, flags);
3885}
3886
3887// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003888
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003889void AudioFlinger::instantiate() {
3890 defaultServiceManager()->addService(
3891 String16("media.audio_flinger"), new AudioFlinger());
3892}
3893
3894}; // namespace android