blob: 5c58603fae1239bd919b38dfd27cc145faf706f5 [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800636void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
637{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700638
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800639 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
640 Mutex::Autolock _l(mLock);
641
642 sp<IBinder> binder = client->asBinder();
643 if (mNotificationClients.indexOf(binder) < 0) {
644 LOGV("Adding notification client %p", binder.get());
645 binder->linkToDeath(this);
646 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700647 }
648
649 // the config change is always sent from playback or record threads to avoid deadlock
650 // with AudioSystem::gLock
651 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700652 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700653 }
654
655 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700656 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 }
658}
659
660void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700661
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800662 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
663 Mutex::Autolock _l(mLock);
664
665 IBinder *binder = who.unsafe_get();
666
667 if (binder != NULL) {
668 int index = mNotificationClients.indexOf(binder);
669 if (index >= 0) {
670 LOGV("Removing notification client %p", binder);
671 mNotificationClients.removeAt(index);
672 }
673 }
674}
675
Eric Laurentb3687ae2009-09-15 07:10:12 -0700676// audioConfigChanged_l() must be called with AudioFlinger::mLock held
Eric Laurent09b4ba82009-11-19 09:00:56 -0800677void AudioFlinger::audioConfigChanged_l(int event, int ioHandle, void *param2) {
678 size_t size = mNotificationClients.size();
679 for (size_t i = 0; i < size; i++) {
680 sp<IBinder> binder = mNotificationClients.itemAt(i);
681 LOGV("audioConfigChanged_l() Notifying change to client %p", binder.get());
682 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
683 client->ioConfigChanged(event, ioHandle, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700684 }
685}
686
Eric Laurent0f8ab672009-09-17 05:12:56 -0700687// removeClient_l() must be called with AudioFlinger::mLock held
688void AudioFlinger::removeClient_l(pid_t pid)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700689{
Eric Laurent0f8ab672009-09-17 05:12:56 -0700690 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 -0700691 mClients.removeItem(pid);
692}
693
Eric Laurent9d91ad52009-07-17 12:17:14 -0700694// ----------------------------------------------------------------------------
695
Eric Laurent09b4ba82009-11-19 09:00:56 -0800696AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, int id)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700697 : Thread(false),
698 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
Eric Laurent09b4ba82009-11-19 09:00:56 -0800699 mFormat(0), mFrameSize(1), mStandby(false), mId(id), mExiting(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700700{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800701}
702
Eric Laurent9d91ad52009-07-17 12:17:14 -0700703AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800704{
Eric Laurent3464c012009-08-04 09:45:33 -0700705 mParamCond.broadcast();
706 mNewParameters.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707}
708
Eric Laurent9d91ad52009-07-17 12:17:14 -0700709void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700710{
Eric Laurent2d70c802009-09-29 11:12:57 -0700711 // keep a strong ref on ourself so that we wont get
Eric Laurent9d91ad52009-07-17 12:17:14 -0700712 // destroyed in the middle of requestExitAndWait()
713 sp <ThreadBase> strongMe = this;
714
715 LOGV("ThreadBase::exit");
716 {
717 AutoMutex lock(&mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -0800718 mExiting = true;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700719 requestExit();
720 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700721 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700722 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700723}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700724
725uint32_t AudioFlinger::ThreadBase::sampleRate() const
726{
727 return mSampleRate;
728}
729
730int AudioFlinger::ThreadBase::channelCount() const
731{
732 return mChannelCount;
733}
734
735int AudioFlinger::ThreadBase::format() const
736{
737 return mFormat;
738}
739
740size_t AudioFlinger::ThreadBase::frameCount() const
741{
742 return mFrameCount;
743}
744
745status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
746{
Eric Laurent3464c012009-08-04 09:45:33 -0700747 status_t status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700748
Eric Laurent3464c012009-08-04 09:45:33 -0700749 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurent9d91ad52009-07-17 12:17:14 -0700750 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700751
Eric Laurent3464c012009-08-04 09:45:33 -0700752 mNewParameters.add(keyValuePairs);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700753 mWaitWorkCV.signal();
Eric Laurent2d70c802009-09-29 11:12:57 -0700754 // wait condition with timeout in case the thread loop has exited
755 // before the request could be processed
756 if (mParamCond.waitRelative(mLock, seconds(2)) == NO_ERROR) {
757 status = mParamStatus;
758 mWaitWorkCV.signal();
759 } else {
760 status = TIMED_OUT;
761 }
Eric Laurent3464c012009-08-04 09:45:33 -0700762 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700763}
764
765void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
766{
767 Mutex::Autolock _l(mLock);
Eric Laurent3464c012009-08-04 09:45:33 -0700768 sendConfigEvent_l(event, param);
769}
770
771// sendConfigEvent_l() must be called with ThreadBase::mLock held
772void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
773{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700774 ConfigEvent *configEvent = new ConfigEvent();
775 configEvent->mEvent = event;
776 configEvent->mParam = param;
777 mConfigEvents.add(configEvent);
778 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
779 mWaitWorkCV.signal();
780}
781
782void AudioFlinger::ThreadBase::processConfigEvents()
783{
784 mLock.lock();
785 while(!mConfigEvents.isEmpty()) {
786 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
787 ConfigEvent *configEvent = mConfigEvents[0];
788 mConfigEvents.removeAt(0);
Eric Laurentb3687ae2009-09-15 07:10:12 -0700789 // release mLock because audioConfigChanged() will lock AudioFlinger mLock
790 // before calling Audioflinger::audioConfigChanged_l() thus creating
Eric Laurent9d91ad52009-07-17 12:17:14 -0700791 // potential cross deadlock between AudioFlinger::mLock and mLock
792 mLock.unlock();
793 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
794 delete configEvent;
795 mLock.lock();
796 }
797 mLock.unlock();
798}
799
Eric Laurentee47d432009-11-07 00:01:32 -0800800status_t AudioFlinger::ThreadBase::dumpBase(int fd, const Vector<String16>& args)
801{
802 const size_t SIZE = 256;
803 char buffer[SIZE];
804 String8 result;
805
806 bool locked = tryLock(mLock);
807 if (!locked) {
808 snprintf(buffer, SIZE, "thread %p maybe dead locked\n", this);
809 write(fd, buffer, strlen(buffer));
810 }
811
812 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
813 result.append(buffer);
814 snprintf(buffer, SIZE, "Sample rate: %d\n", mSampleRate);
815 result.append(buffer);
816 snprintf(buffer, SIZE, "Frame count: %d\n", mFrameCount);
817 result.append(buffer);
818 snprintf(buffer, SIZE, "Channel Count: %d\n", mChannelCount);
819 result.append(buffer);
820 snprintf(buffer, SIZE, "Format: %d\n", mFormat);
821 result.append(buffer);
822 snprintf(buffer, SIZE, "Frame size: %d\n", mFrameSize);
823 result.append(buffer);
824
825 snprintf(buffer, SIZE, "\nPending setParameters commands: \n");
826 result.append(buffer);
827 result.append(" Index Command");
828 for (size_t i = 0; i < mNewParameters.size(); ++i) {
829 snprintf(buffer, SIZE, "\n %02d ", i);
830 result.append(buffer);
831 result.append(mNewParameters[i]);
832 }
833
834 snprintf(buffer, SIZE, "\n\nPending config events: \n");
835 result.append(buffer);
836 snprintf(buffer, SIZE, " Index event param\n");
837 result.append(buffer);
838 for (size_t i = 0; i < mConfigEvents.size(); i++) {
839 snprintf(buffer, SIZE, " %02d %02d %d\n", i, mConfigEvents[i]->mEvent, mConfigEvents[i]->mParam);
840 result.append(buffer);
841 }
842 result.append("\n");
843
844 write(fd, result.string(), result.size());
845
846 if (locked) {
847 mLock.unlock();
848 }
849 return NO_ERROR;
850}
851
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800852
853// ----------------------------------------------------------------------------
854
Eric Laurent09b4ba82009-11-19 09:00:56 -0800855AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
856 : ThreadBase(audioFlinger, id),
Eric Laurentf9df2492009-08-06 08:49:39 -0700857 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700858 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800859{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700860 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800861
Eric Laurent9d91ad52009-07-17 12:17:14 -0700862 mMasterVolume = mAudioFlinger->masterVolume();
863 mMasterMute = mAudioFlinger->masterMute();
864
865 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
866 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
867 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800868 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700869 // notify client processes that a new input has been opened
870 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800871}
872
Eric Laurent9d91ad52009-07-17 12:17:14 -0700873AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800874{
875 delete [] mMixBuffer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800876}
877
Eric Laurent9d91ad52009-07-17 12:17:14 -0700878status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800879{
880 dumpInternals(fd, args);
881 dumpTracks(fd, args);
882 return NO_ERROR;
883}
884
Eric Laurent9d91ad52009-07-17 12:17:14 -0700885status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800886{
887 const size_t SIZE = 256;
888 char buffer[SIZE];
889 String8 result;
890
Eric Laurent9d91ad52009-07-17 12:17:14 -0700891 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800892 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -0800893 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 -0800894 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700895 sp<Track> track = mTracks[i];
896 if (track != 0) {
897 track->dump(buffer, SIZE);
898 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800899 }
900 }
901
Eric Laurent9d91ad52009-07-17 12:17:14 -0700902 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800903 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -0800904 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 -0800905 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700906 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800907 if (wTrack != 0) {
908 sp<Track> track = wTrack.promote();
909 if (track != 0) {
910 track->dump(buffer, SIZE);
911 result.append(buffer);
912 }
913 }
914 }
915 write(fd, result.string(), result.size());
916 return NO_ERROR;
917}
918
Eric Laurent9d91ad52009-07-17 12:17:14 -0700919status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800920{
921 const size_t SIZE = 256;
922 char buffer[SIZE];
923 String8 result;
924
Eric Laurentee47d432009-11-07 00:01:32 -0800925 snprintf(buffer, SIZE, "\nOutput thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800926 result.append(buffer);
927 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
928 result.append(buffer);
929 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
930 result.append(buffer);
931 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
932 result.append(buffer);
933 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
934 result.append(buffer);
Eric Laurent7e2aad12009-12-18 05:47:48 -0800935 snprintf(buffer, SIZE, "suspend count: %d\n", mSuspended);
936 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800937 write(fd, result.string(), result.size());
Eric Laurentee47d432009-11-07 00:01:32 -0800938
939 dumpBase(fd, args);
940
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800941 return NO_ERROR;
942}
943
944// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700945status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800946{
947 if (mSampleRate == 0) {
948 LOGE("No working audio driver found.");
949 return NO_INIT;
950 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700951 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800952 return NO_ERROR;
953}
954
Eric Laurent9d91ad52009-07-17 12:17:14 -0700955void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800956{
957 const size_t SIZE = 256;
958 char buffer[SIZE];
959
Eric Laurent9d91ad52009-07-17 12:17:14 -0700960 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800961
962 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
963}
964
Eric Laurent9d91ad52009-07-17 12:17:14 -0700965// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
966sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800967 const sp<AudioFlinger::Client>& client,
968 int streamType,
969 uint32_t sampleRate,
970 int format,
971 int channelCount,
972 int frameCount,
973 const sp<IMemory>& sharedBuffer,
974 status_t *status)
975{
976 sp<Track> track;
977 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700978
979 if (mType == DIRECT) {
980 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
981 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
982 sampleRate, format, channelCount, mOutput);
983 lStatus = BAD_VALUE;
984 goto Exit;
985 }
986 } else {
987 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
988 if (sampleRate > mSampleRate*2) {
989 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
990 lStatus = BAD_VALUE;
991 goto Exit;
992 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800993 }
994
Eric Laurent9d91ad52009-07-17 12:17:14 -0700995 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700996 LOGE("Audio driver not initialized.");
997 lStatus = NO_INIT;
998 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800999 }
1000
Eric Laurent9d91ad52009-07-17 12:17:14 -07001001 { // scope for mLock
1002 Mutex::Autolock _l(mLock);
1003 track = new Track(this, client, streamType, sampleRate, format,
1004 channelCount, frameCount, sharedBuffer);
Eric Laurent7b570852009-11-09 04:45:39 -08001005 if (track->getCblk() == NULL || track->name() < 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001006 lStatus = NO_MEMORY;
1007 goto Exit;
1008 }
1009 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001010 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001011 lStatus = NO_ERROR;
1012
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001013Exit:
1014 if(status) {
1015 *status = lStatus;
1016 }
1017 return track;
1018}
1019
Eric Laurent9d91ad52009-07-17 12:17:14 -07001020uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021{
1022 if (mOutput) {
1023 return mOutput->latency();
1024 }
1025 else {
1026 return 0;
1027 }
1028}
1029
Eric Laurent9d91ad52009-07-17 12:17:14 -07001030status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031{
1032 mMasterVolume = value;
1033 return NO_ERROR;
1034}
1035
Eric Laurent9d91ad52009-07-17 12:17:14 -07001036status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001037{
1038 mMasterMute = muted;
1039 return NO_ERROR;
1040}
1041
Eric Laurent9d91ad52009-07-17 12:17:14 -07001042float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043{
1044 return mMasterVolume;
1045}
1046
Eric Laurent9d91ad52009-07-17 12:17:14 -07001047bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048{
1049 return mMasterMute;
1050}
1051
Eric Laurent9d91ad52009-07-17 12:17:14 -07001052status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001053{
1054 mStreamTypes[stream].volume = value;
1055 return NO_ERROR;
1056}
1057
Eric Laurent9d91ad52009-07-17 12:17:14 -07001058status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001059{
1060 mStreamTypes[stream].mute = muted;
1061 return NO_ERROR;
1062}
1063
Eric Laurent9d91ad52009-07-17 12:17:14 -07001064float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001065{
1066 return mStreamTypes[stream].volume;
1067}
1068
Eric Laurent9d91ad52009-07-17 12:17:14 -07001069bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001070{
1071 return mStreamTypes[stream].mute;
1072}
1073
Eric Laurent43c0b0a2010-01-25 08:49:09 -08001074bool AudioFlinger::PlaybackThread::isStreamActive(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001076 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001077 size_t count = mActiveTracks.size();
1078 for (size_t i = 0 ; i < count ; ++i) {
1079 sp<Track> t = mActiveTracks[i].promote();
1080 if (t == 0) continue;
1081 Track* const track = t.get();
Eric Laurent43c0b0a2010-01-25 08:49:09 -08001082 if (t->type() == stream)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001083 return true;
1084 }
1085 return false;
1086}
1087
Eric Laurent9d91ad52009-07-17 12:17:14 -07001088// addTrack_l() must be called with ThreadBase::mLock held
1089status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001090{
1091 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001092
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001093 // set retry count for buffer fill
1094 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001095 if (mActiveTracks.indexOf(track) < 0) {
1096 // the track is newly added, make sure it fills up all its
1097 // buffers before playing. This is to ensure the client will
1098 // effectively get the latency it requested.
1099 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001100 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001101 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001102 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001103 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001105 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001106 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001107
1108 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001109}
1110
Eric Laurent9d91ad52009-07-17 12:17:14 -07001111// destroyTrack_l() must be called with ThreadBase::mLock held
1112void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001113{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001114 track->mState = TrackBase::TERMINATED;
1115 if (mActiveTracks.indexOf(track) < 0) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001116 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001117 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001118 }
1119}
1120
Eric Laurent9d91ad52009-07-17 12:17:14 -07001121String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001122{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001123 return mOutput->getParameters(keys);
1124}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001125
Eric Laurent9d91ad52009-07-17 12:17:14 -07001126void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1127 AudioSystem::OutputDescriptor desc;
1128 void *param2 = 0;
1129
1130 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1131
1132 switch (event) {
1133 case AudioSystem::OUTPUT_OPENED:
1134 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1135 desc.channels = mChannelCount;
1136 desc.samplingRate = mSampleRate;
1137 desc.format = mFormat;
1138 desc.frameCount = mFrameCount;
1139 desc.latency = latency();
1140 param2 = &desc;
1141 break;
1142
1143 case AudioSystem::STREAM_CONFIG_CHANGED:
1144 param2 = &param;
1145 case AudioSystem::OUTPUT_CLOSED:
1146 default:
1147 break;
1148 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07001149 Mutex::Autolock _l(mAudioFlinger->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08001150 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001151}
1152
1153void AudioFlinger::PlaybackThread::readOutputParameters()
1154{
1155 mSampleRate = mOutput->sampleRate();
1156 mChannelCount = AudioSystem::popCount(mOutput->channels());
1157
1158 mFormat = mOutput->format();
1159 mFrameSize = mOutput->frameSize();
1160 mFrameCount = mOutput->bufferSize() / mFrameSize;
1161
Eric Laurent9d91ad52009-07-17 12:17:14 -07001162 // FIXME - Current mixer implementation only supports stereo output: Always
1163 // Allocate a stereo buffer even if HW output is mono.
1164 if (mMixBuffer != NULL) delete mMixBuffer;
1165 mMixBuffer = new int16_t[mFrameCount * 2];
1166 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1167}
1168
1169// ----------------------------------------------------------------------------
1170
Eric Laurent09b4ba82009-11-19 09:00:56 -08001171AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
1172 : PlaybackThread(audioFlinger, output, id),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001173 mAudioMixer(0)
1174{
1175 mType = PlaybackThread::MIXER;
1176 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1177
1178 // FIXME - Current mixer implementation only supports stereo output
1179 if (mChannelCount == 1) {
1180 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001181 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001182}
1183
Eric Laurent9d91ad52009-07-17 12:17:14 -07001184AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001185{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001186 delete mAudioMixer;
1187}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001188
Eric Laurent9d91ad52009-07-17 12:17:14 -07001189bool AudioFlinger::MixerThread::threadLoop()
1190{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001191 int16_t* curBuf = mMixBuffer;
1192 Vector< sp<Track> > tracksToRemove;
Eric Laurent0e49d352009-11-09 23:32:22 -08001193 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001194 nsecs_t standbyTime = systemTime();
1195 size_t mixBufferSize = mFrameCount * mFrameSize;
Dave Sparks8a95a452009-09-30 03:09:03 -07001196 // FIXME: Relaxed timing because of a certain device that can't meet latency
1197 // Should be reduced to 2x after the vendor fixes the driver issue
1198 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
1199 nsecs_t lastWarning = 0;
Eric Laurent0e49d352009-11-09 23:32:22 -08001200 bool longStandbyExit = false;
1201 uint32_t activeSleepTime = activeSleepTimeUs();
1202 uint32_t idleSleepTime = idleSleepTimeUs();
1203 uint32_t sleepTime = idleSleepTime;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001204
Eric Laurent9d91ad52009-07-17 12:17:14 -07001205 while (!exitPending())
1206 {
1207 processConfigEvents();
1208
Eric Laurent0e49d352009-11-09 23:32:22 -08001209 mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001210 { // scope for mLock
1211
1212 Mutex::Autolock _l(mLock);
1213
1214 if (checkForNewParameters_l()) {
1215 mixBufferSize = mFrameCount * mFrameSize;
Dave Sparks8a95a452009-09-30 03:09:03 -07001216 // FIXME: Relaxed timing because of a certain device that can't meet latency
1217 // Should be reduced to 2x after the vendor fixes the driver issue
1218 maxPeriod = seconds(mFrameCount) / mSampleRate * 3;
Eric Laurent0e49d352009-11-09 23:32:22 -08001219 activeSleepTime = activeSleepTimeUs();
1220 idleSleepTime = idleSleepTimeUs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001221 }
1222
1223 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1224
1225 // put audio hardware into standby after short delay
1226 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1227 mSuspended) {
1228 if (!mStandby) {
1229 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1230 mOutput->standby();
1231 mStandby = true;
1232 mBytesWritten = 0;
1233 }
1234
1235 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1236 // we're about to wait, flush the binder command buffer
1237 IPCThreadState::self()->flushCommands();
1238
1239 if (exitPending()) break;
1240
1241 // wait until we have something to do...
1242 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1243 mWaitWorkCV.wait(mLock);
1244 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1245
1246 if (mMasterMute == false) {
1247 char value[PROPERTY_VALUE_MAX];
1248 property_get("ro.audio.silent", value, "0");
1249 if (atoi(value)) {
1250 LOGD("Silence is golden");
1251 setMasterMute(true);
1252 }
1253 }
1254
1255 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent0e49d352009-11-09 23:32:22 -08001256 sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001257 continue;
1258 }
1259 }
1260
Eric Laurent0e49d352009-11-09 23:32:22 -08001261 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001262 }
1263
Eric Laurent0e49d352009-11-09 23:32:22 -08001264 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001265 // mix buffers...
1266 mAudioMixer->process(curBuf);
1267 sleepTime = 0;
1268 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001269 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001270 // If no tracks are ready, sleep once for the duration of an output
1271 // buffer size, then write 0s to the output
1272 if (sleepTime == 0) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001273 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1274 sleepTime = activeSleepTime;
1275 } else {
1276 sleepTime = idleSleepTime;
1277 }
1278 } else if (mBytesWritten != 0 ||
1279 (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001280 memset (curBuf, 0, mixBufferSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001281 sleepTime = 0;
Eric Laurent0e49d352009-11-09 23:32:22 -08001282 LOGV_IF((mBytesWritten == 0 && (mixerStatus == MIXER_TRACKS_ENABLED && longStandbyExit)), "anticipated start");
Eric Laurent3522c802009-09-07 08:38:38 -07001283 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001284 }
1285
1286 if (mSuspended) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001287 sleepTime = idleSleepTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07001288 }
1289 // sleepTime == 0 means we must write to audio hardware
1290 if (sleepTime == 0) {
1291 mLastWriteTime = systemTime();
1292 mInWrite = true;
Eric Laurentaef692f2009-09-22 00:35:48 -07001293 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1294 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1295 mNumWrites++;
1296 mInWrite = false;
Dave Sparks8a95a452009-09-30 03:09:03 -07001297 nsecs_t now = systemTime();
1298 nsecs_t delta = now - mLastWriteTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07001299 if (delta > maxPeriod) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001300 mNumDelayedWrites++;
Dave Sparks8a95a452009-09-30 03:09:03 -07001301 if ((now - lastWarning) > kWarningThrottle) {
1302 LOGW("write blocked for %llu msecs, %d delayed writes, thread %p",
1303 ns2ms(delta), mNumDelayedWrites, this);
1304 lastWarning = now;
1305 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001306 if (mStandby) {
1307 longStandbyExit = true;
1308 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001309 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001310 mStandby = false;
Eric Laurentaef692f2009-09-22 00:35:48 -07001311 } else {
1312 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001313 }
1314
1315 // finally let go of all our tracks, without the lock held
1316 // since we can't guarantee the destructors won't acquire that
1317 // same lock.
1318 tracksToRemove.clear();
1319 }
1320
1321 if (!mStandby) {
1322 mOutput->standby();
1323 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001324
1325 LOGV("MixerThread %p exiting", this);
1326 return false;
1327}
1328
1329// prepareTracks_l() must be called with ThreadBase::mLock held
Eric Laurent0e49d352009-11-09 23:32:22 -08001330uint32_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
Eric Laurent9d91ad52009-07-17 12:17:14 -07001331{
1332
Eric Laurent0e49d352009-11-09 23:32:22 -08001333 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001334 // find out which tracks need to be processed
1335 size_t count = activeTracks.size();
1336 for (size_t i=0 ; i<count ; i++) {
1337 sp<Track> t = activeTracks[i].promote();
1338 if (t == 0) continue;
1339
1340 Track* const track = t.get();
1341 audio_track_cblk_t* cblk = track->cblk();
1342
1343 // The first time a track is added we wait
1344 // for all its buffers to be filled before processing it
1345 mAudioMixer->setActiveTrack(track->name());
1346 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1347 !track->isPaused())
1348 {
Eric Laurent7e2aad12009-12-18 05:47:48 -08001349 //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 -07001350
1351 // compute volume for this track
1352 int16_t left, right;
1353 if (track->isMuted() || mMasterMute || track->isPausing() ||
1354 mStreamTypes[track->type()].mute) {
1355 left = right = 0;
1356 if (track->isPausing()) {
1357 track->setPaused();
1358 }
1359 } else {
1360 float typeVolume = mStreamTypes[track->type()].volume;
1361 float v = mMasterVolume * typeVolume;
1362 float v_clamped = v * cblk->volume[0];
1363 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1364 left = int16_t(v_clamped);
1365 v_clamped = v * cblk->volume[1];
1366 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1367 right = int16_t(v_clamped);
1368 }
1369
1370 // XXX: these things DON'T need to be done each time
1371 mAudioMixer->setBufferProvider(track);
1372 mAudioMixer->enable(AudioMixer::MIXING);
1373
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001374 int param = AudioMixer::VOLUME;
1375 if (track->mFillingUpStatus == Track::FS_FILLED) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001376 // no ramp for the first volume setting
1377 track->mFillingUpStatus = Track::FS_ACTIVE;
1378 if (track->mState == TrackBase::RESUMING) {
1379 track->mState = TrackBase::ACTIVE;
1380 param = AudioMixer::RAMP_VOLUME;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001381 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001382 } else if (cblk->server != 0) {
1383 // If the track is stopped before the first frame was mixed,
1384 // do not apply ramp
Eric Laurent9d91ad52009-07-17 12:17:14 -07001385 param = AudioMixer::RAMP_VOLUME;
1386 }
Eric Laurent08d3d1d2009-09-03 03:45:52 -07001387
Eric Laurent9d91ad52009-07-17 12:17:14 -07001388 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1389 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1390 mAudioMixer->setParameter(
1391 AudioMixer::TRACK,
1392 AudioMixer::FORMAT, track->format());
1393 mAudioMixer->setParameter(
1394 AudioMixer::TRACK,
1395 AudioMixer::CHANNEL_COUNT, track->channelCount());
1396 mAudioMixer->setParameter(
1397 AudioMixer::RESAMPLE,
1398 AudioMixer::SAMPLE_RATE,
1399 int(cblk->sampleRate));
1400
1401 // reset retry count
1402 track->mRetryCount = kMaxTrackRetries;
Eric Laurent0e49d352009-11-09 23:32:22 -08001403 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001404 } else {
Eric Laurent7e2aad12009-12-18 05:47:48 -08001405 //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 -07001406 if (track->isStopped()) {
1407 track->reset();
1408 }
1409 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1410 // We have consumed all the buffers of this track.
1411 // Remove it from the list of active tracks.
1412 tracksToRemove->add(track);
1413 mAudioMixer->disable(AudioMixer::MIXING);
1414 } else {
1415 // No buffers for this track. Give it a few chances to
1416 // fill a buffer, then remove it from active list.
1417 if (--(track->mRetryCount) <= 0) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001418 LOGV("BUFFER TIMEOUT: remove(%d) from active list on thread %p", track->name(), this);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001419 tracksToRemove->add(track);
Eric Laurent0e49d352009-11-09 23:32:22 -08001420 } else if (mixerStatus != MIXER_TRACKS_READY) {
1421 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001422 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001423
1424 mAudioMixer->disable(AudioMixer::MIXING);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001425 }
1426 }
1427 }
1428
1429 // remove all the tracks that need to be...
1430 count = tracksToRemove->size();
1431 if (UNLIKELY(count)) {
1432 for (size_t i=0 ; i<count ; i++) {
1433 const sp<Track>& track = tracksToRemove->itemAt(i);
1434 mActiveTracks.remove(track);
1435 if (track->isTerminated()) {
1436 mTracks.remove(track);
1437 deleteTrackName_l(track->mName);
1438 }
1439 }
1440 }
1441
Eric Laurent0e49d352009-11-09 23:32:22 -08001442 return mixerStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001443}
1444
1445void AudioFlinger::MixerThread::getTracks(
1446 SortedVector < sp<Track> >& tracks,
1447 SortedVector < wp<Track> >& activeTracks,
1448 int streamType)
1449{
1450 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1451 Mutex::Autolock _l(mLock);
1452 size_t size = mTracks.size();
1453 for (size_t i = 0; i < size; i++) {
1454 sp<Track> t = mTracks[i];
1455 if (t->type() == streamType) {
1456 tracks.add(t);
1457 int j = mActiveTracks.indexOf(t);
1458 if (j >= 0) {
1459 t = mActiveTracks[j].promote();
1460 if (t != NULL) {
1461 activeTracks.add(t);
1462 }
1463 }
1464 }
1465 }
1466
1467 size = activeTracks.size();
1468 for (size_t i = 0; i < size; i++) {
1469 mActiveTracks.remove(activeTracks[i]);
1470 }
1471
1472 size = tracks.size();
1473 for (size_t i = 0; i < size; i++) {
1474 sp<Track> t = tracks[i];
1475 mTracks.remove(t);
1476 deleteTrackName_l(t->name());
1477 }
1478}
1479
1480void AudioFlinger::MixerThread::putTracks(
1481 SortedVector < sp<Track> >& tracks,
1482 SortedVector < wp<Track> >& activeTracks)
1483{
1484 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1485 Mutex::Autolock _l(mLock);
1486 size_t size = tracks.size();
1487 for (size_t i = 0; i < size ; i++) {
1488 sp<Track> t = tracks[i];
1489 int name = getTrackName_l();
1490
1491 if (name < 0) return;
1492
1493 t->mName = name;
1494 t->mThread = this;
1495 mTracks.add(t);
1496
1497 int j = activeTracks.indexOf(t);
1498 if (j >= 0) {
1499 mActiveTracks.add(t);
Eric Laurent06437712009-09-01 05:56:26 -07001500 // force buffer refilling and no ramp volume when the track is mixed for the first time
1501 t->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001502 }
1503 }
1504}
1505
Eric Laurent9d91ad52009-07-17 12:17:14 -07001506// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001507int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001508{
1509 return mAudioMixer->getTrackName();
1510}
1511
Eric Laurent9d91ad52009-07-17 12:17:14 -07001512// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001513void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001514{
Eric Laurentfed93822009-12-07 10:53:10 -08001515 LOGV("remove track (%d) and delete from mixer", name);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001516 mAudioMixer->deleteTrackName(name);
1517}
1518
Eric Laurent9d91ad52009-07-17 12:17:14 -07001519// checkForNewParameters_l() must be called with ThreadBase::mLock held
1520bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001521{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001522 bool reconfig = false;
1523
Eric Laurent3464c012009-08-04 09:45:33 -07001524 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001525 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001526 String8 keyValuePair = mNewParameters[0];
1527 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001528 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001529
Eric Laurent9d91ad52009-07-17 12:17:14 -07001530 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1531 reconfig = true;
1532 }
1533 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1534 if (value != AudioSystem::PCM_16_BIT) {
1535 status = BAD_VALUE;
1536 } else {
1537 reconfig = true;
1538 }
1539 }
1540 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1541 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1542 status = BAD_VALUE;
1543 } else {
1544 reconfig = true;
1545 }
1546 }
1547 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1548 // do not accept frame count changes if tracks are open as the track buffer
1549 // size depends on frame count and correct behavior would not be garantied
1550 // if frame count is changed after track creation
1551 if (!mTracks.isEmpty()) {
1552 status = INVALID_OPERATION;
1553 } else {
1554 reconfig = true;
1555 }
1556 }
1557 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001558 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001559 if (!mStandby && status == INVALID_OPERATION) {
1560 mOutput->standby();
1561 mStandby = true;
1562 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001563 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001564 }
1565 if (status == NO_ERROR && reconfig) {
1566 delete mAudioMixer;
1567 readOutputParameters();
1568 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1569 for (size_t i = 0; i < mTracks.size() ; i++) {
1570 int name = getTrackName_l();
1571 if (name < 0) break;
1572 mTracks[i]->mName = name;
Eric Laurent878c0e12009-08-10 08:15:12 -07001573 // limit track sample rate to 2 x new output sample rate
1574 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1575 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1576 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001577 }
Eric Laurent3464c012009-08-04 09:45:33 -07001578 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001579 }
1580 }
Eric Laurentee47d432009-11-07 00:01:32 -08001581
1582 mNewParameters.removeAt(0);
1583
Eric Laurent9d91ad52009-07-17 12:17:14 -07001584 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001585 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001586 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001587 }
1588 return reconfig;
1589}
1590
1591status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1592{
1593 const size_t SIZE = 256;
1594 char buffer[SIZE];
1595 String8 result;
1596
1597 PlaybackThread::dumpInternals(fd, args);
1598
1599 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1600 result.append(buffer);
1601 write(fd, result.string(), result.size());
1602 return NO_ERROR;
1603}
1604
Eric Laurent0e49d352009-11-09 23:32:22 -08001605uint32_t AudioFlinger::MixerThread::activeSleepTimeUs()
Eric Laurentf5e868b2009-10-05 20:29:18 -07001606{
Eric Laurent0e49d352009-11-09 23:32:22 -08001607 return (uint32_t)(mOutput->latency() * 1000) / 2;
1608}
1609
1610uint32_t AudioFlinger::MixerThread::idleSleepTimeUs()
1611{
1612 return (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001613}
1614
Eric Laurent9d91ad52009-07-17 12:17:14 -07001615// ----------------------------------------------------------------------------
Eric Laurent09b4ba82009-11-19 09:00:56 -08001616AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output, int id)
1617 : PlaybackThread(audioFlinger, output, id),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001618 mLeftVolume (1.0), mRightVolume(1.0)
1619{
1620 mType = PlaybackThread::DIRECT;
1621}
1622
1623AudioFlinger::DirectOutputThread::~DirectOutputThread()
1624{
1625}
1626
1627
1628bool AudioFlinger::DirectOutputThread::threadLoop()
1629{
Eric Laurent0e49d352009-11-09 23:32:22 -08001630 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001631 sp<Track> trackToRemove;
1632 sp<Track> activeTrack;
1633 nsecs_t standbyTime = systemTime();
1634 int8_t *curBuf;
1635 size_t mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent0e49d352009-11-09 23:32:22 -08001636 uint32_t activeSleepTime = activeSleepTimeUs();
1637 uint32_t idleSleepTime = idleSleepTimeUs();
1638 uint32_t sleepTime = idleSleepTime;
1639
Eric Laurent9d91ad52009-07-17 12:17:14 -07001640
1641 while (!exitPending())
1642 {
1643 processConfigEvents();
1644
Eric Laurent0e49d352009-11-09 23:32:22 -08001645 mixerStatus = MIXER_IDLE;
1646
Eric Laurent9d91ad52009-07-17 12:17:14 -07001647 { // scope for the mLock
1648
1649 Mutex::Autolock _l(mLock);
1650
1651 if (checkForNewParameters_l()) {
1652 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent0e49d352009-11-09 23:32:22 -08001653 activeSleepTime = activeSleepTimeUs();
1654 idleSleepTime = idleSleepTimeUs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001655 }
1656
1657 // put audio hardware into standby after short delay
1658 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1659 mSuspended) {
1660 // wait until we have something to do...
1661 if (!mStandby) {
1662 LOGV("Audio hardware entering standby, mixer %p\n", this);
1663 mOutput->standby();
1664 mStandby = true;
1665 mBytesWritten = 0;
1666 }
1667
1668 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1669 // we're about to wait, flush the binder command buffer
1670 IPCThreadState::self()->flushCommands();
1671
1672 if (exitPending()) break;
1673
1674 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1675 mWaitWorkCV.wait(mLock);
1676 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1677
1678 if (mMasterMute == false) {
1679 char value[PROPERTY_VALUE_MAX];
1680 property_get("ro.audio.silent", value, "0");
1681 if (atoi(value)) {
1682 LOGD("Silence is golden");
1683 setMasterMute(true);
1684 }
1685 }
1686
1687 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent0e49d352009-11-09 23:32:22 -08001688 sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001689 continue;
1690 }
1691 }
1692
1693 // find out which tracks need to be processed
1694 if (mActiveTracks.size() != 0) {
1695 sp<Track> t = mActiveTracks[0].promote();
1696 if (t == 0) continue;
1697
1698 Track* const track = t.get();
1699 audio_track_cblk_t* cblk = track->cblk();
1700
1701 // The first time a track is added we wait
1702 // for all its buffers to be filled before processing it
1703 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1704 !track->isPaused())
1705 {
1706 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1707
1708 // compute volume for this track
1709 float left, right;
1710 if (track->isMuted() || mMasterMute || track->isPausing() ||
1711 mStreamTypes[track->type()].mute) {
1712 left = right = 0;
1713 if (track->isPausing()) {
1714 track->setPaused();
1715 }
1716 } else {
1717 float typeVolume = mStreamTypes[track->type()].volume;
1718 float v = mMasterVolume * typeVolume;
1719 float v_clamped = v * cblk->volume[0];
1720 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1721 left = v_clamped/MAX_GAIN;
1722 v_clamped = v * cblk->volume[1];
1723 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1724 right = v_clamped/MAX_GAIN;
1725 }
1726
1727 if (left != mLeftVolume || right != mRightVolume) {
1728 mOutput->setVolume(left, right);
1729 left = mLeftVolume;
1730 right = mRightVolume;
1731 }
1732
1733 if (track->mFillingUpStatus == Track::FS_FILLED) {
1734 track->mFillingUpStatus = Track::FS_ACTIVE;
1735 if (track->mState == TrackBase::RESUMING) {
1736 track->mState = TrackBase::ACTIVE;
1737 }
1738 }
1739
1740 // reset retry count
1741 track->mRetryCount = kMaxTrackRetries;
1742 activeTrack = t;
Eric Laurent0e49d352009-11-09 23:32:22 -08001743 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001744 } else {
1745 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1746 if (track->isStopped()) {
1747 track->reset();
1748 }
1749 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1750 // We have consumed all the buffers of this track.
1751 // Remove it from the list of active tracks.
1752 trackToRemove = track;
1753 } else {
1754 // No buffers for this track. Give it a few chances to
1755 // fill a buffer, then remove it from active list.
1756 if (--(track->mRetryCount) <= 0) {
1757 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1758 trackToRemove = track;
Eric Laurent0e49d352009-11-09 23:32:22 -08001759 } else {
1760 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001761 }
Eric Laurent0e49d352009-11-09 23:32:22 -08001762 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001763 }
1764 }
1765
1766 // remove all the tracks that need to be...
1767 if (UNLIKELY(trackToRemove != 0)) {
1768 mActiveTracks.remove(trackToRemove);
1769 if (trackToRemove->isTerminated()) {
1770 mTracks.remove(trackToRemove);
1771 deleteTrackName_l(trackToRemove->mName);
1772 }
1773 }
1774 }
1775
Eric Laurent0e49d352009-11-09 23:32:22 -08001776 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001777 AudioBufferProvider::Buffer buffer;
1778 size_t frameCount = mFrameCount;
1779 curBuf = (int8_t *)mMixBuffer;
1780 // output audio to hardware
1781 while(frameCount) {
1782 buffer.frameCount = frameCount;
1783 activeTrack->getNextBuffer(&buffer);
1784 if (UNLIKELY(buffer.raw == 0)) {
1785 memset(curBuf, 0, frameCount * mFrameSize);
1786 break;
1787 }
1788 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1789 frameCount -= buffer.frameCount;
1790 curBuf += buffer.frameCount * mFrameSize;
1791 activeTrack->releaseBuffer(&buffer);
1792 }
1793 sleepTime = 0;
1794 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent3522c802009-09-07 08:38:38 -07001795 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07001796 if (sleepTime == 0) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001797 if (mixerStatus == MIXER_TRACKS_ENABLED) {
1798 sleepTime = activeSleepTime;
1799 } else {
1800 sleepTime = idleSleepTime;
1801 }
Eric Laurentf5e868b2009-10-05 20:29:18 -07001802 } else if (mBytesWritten != 0 && AudioSystem::isLinearPCM(mFormat)) {
Eric Laurentaef692f2009-09-22 00:35:48 -07001803 memset (mMixBuffer, 0, mFrameCount * mFrameSize);
Eric Laurent3522c802009-09-07 08:38:38 -07001804 sleepTime = 0;
Eric Laurent3522c802009-09-07 08:38:38 -07001805 }
Eric Laurentaef692f2009-09-22 00:35:48 -07001806 }
Eric Laurent3522c802009-09-07 08:38:38 -07001807
Eric Laurentaef692f2009-09-22 00:35:48 -07001808 if (mSuspended) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001809 sleepTime = idleSleepTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07001810 }
1811 // sleepTime == 0 means we must write to audio hardware
1812 if (sleepTime == 0) {
1813 mLastWriteTime = systemTime();
1814 mInWrite = true;
1815 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1816 if (bytesWritten) mBytesWritten += bytesWritten;
1817 mNumWrites++;
1818 mInWrite = false;
1819 mStandby = false;
1820 } else {
1821 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001822 }
1823
1824 // finally let go of removed track, without the lock held
1825 // since we can't guarantee the destructors won't acquire that
1826 // same lock.
1827 trackToRemove.clear();
1828 activeTrack.clear();
1829 }
1830
1831 if (!mStandby) {
1832 mOutput->standby();
1833 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001834
1835 LOGV("DirectOutputThread %p exiting", this);
1836 return false;
1837}
1838
1839// getTrackName_l() must be called with ThreadBase::mLock held
1840int AudioFlinger::DirectOutputThread::getTrackName_l()
1841{
1842 return 0;
1843}
1844
1845// deleteTrackName_l() must be called with ThreadBase::mLock held
1846void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1847{
1848}
1849
1850// checkForNewParameters_l() must be called with ThreadBase::mLock held
1851bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1852{
1853 bool reconfig = false;
1854
Eric Laurent3464c012009-08-04 09:45:33 -07001855 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001856 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07001857 String8 keyValuePair = mNewParameters[0];
1858 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001859 int value;
Eric Laurent3464c012009-08-04 09:45:33 -07001860
Eric Laurent9d91ad52009-07-17 12:17:14 -07001861 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1862 // do not accept frame count changes if tracks are open as the track buffer
1863 // size depends on frame count and correct behavior would not be garantied
1864 // if frame count is changed after track creation
1865 if (!mTracks.isEmpty()) {
1866 status = INVALID_OPERATION;
1867 } else {
1868 reconfig = true;
1869 }
1870 }
1871 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07001872 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001873 if (!mStandby && status == INVALID_OPERATION) {
1874 mOutput->standby();
1875 mStandby = true;
1876 mBytesWritten = 0;
Eric Laurent3464c012009-08-04 09:45:33 -07001877 status = mOutput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001878 }
1879 if (status == NO_ERROR && reconfig) {
1880 readOutputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07001881 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001882 }
1883 }
Eric Laurentee47d432009-11-07 00:01:32 -08001884
1885 mNewParameters.removeAt(0);
1886
Eric Laurent9d91ad52009-07-17 12:17:14 -07001887 mParamStatus = status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001888 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07001889 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07001890 }
1891 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001892}
1893
Eric Laurent0e49d352009-11-09 23:32:22 -08001894uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs()
Eric Laurentf5e868b2009-10-05 20:29:18 -07001895{
1896 uint32_t time;
1897 if (AudioSystem::isLinearPCM(mFormat)) {
Eric Laurent0e49d352009-11-09 23:32:22 -08001898 time = (uint32_t)(mOutput->latency() * 1000) / 2;
1899 } else {
1900 time = 10000;
1901 }
1902 return time;
1903}
1904
1905uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs()
1906{
1907 uint32_t time;
1908 if (AudioSystem::isLinearPCM(mFormat)) {
1909 time = (uint32_t)((mFrameCount * 1000) / mSampleRate) * 1000;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001910 } else {
1911 time = 10000;
1912 }
1913 return time;
1914}
1915
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001916// ----------------------------------------------------------------------------
1917
Eric Laurent09b4ba82009-11-19 09:00:56 -08001918AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread, int id)
Eric Laurent7e2aad12009-12-18 05:47:48 -08001919 : MixerThread(audioFlinger, mainThread->getOutput(), id), mWaitTimeMs(UINT_MAX)
Eric Laurent9d91ad52009-07-17 12:17:14 -07001920{
1921 mType = PlaybackThread::DUPLICATING;
1922 addOutputTrack(mainThread);
1923}
1924
1925AudioFlinger::DuplicatingThread::~DuplicatingThread()
1926{
Eric Laurentfed93822009-12-07 10:53:10 -08001927 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1928 mOutputTracks[i]->destroy();
1929 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001930 mOutputTracks.clear();
1931}
1932
1933bool AudioFlinger::DuplicatingThread::threadLoop()
1934{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001935 int16_t* curBuf = mMixBuffer;
1936 Vector< sp<Track> > tracksToRemove;
Eric Laurent0e49d352009-11-09 23:32:22 -08001937 uint32_t mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001938 nsecs_t standbyTime = systemTime();
1939 size_t mixBufferSize = mFrameCount*mFrameSize;
1940 SortedVector< sp<OutputTrack> > outputTracks;
Eric Laurentf5e868b2009-10-05 20:29:18 -07001941 uint32_t writeFrames = 0;
Eric Laurent0e49d352009-11-09 23:32:22 -08001942 uint32_t activeSleepTime = activeSleepTimeUs();
1943 uint32_t idleSleepTime = idleSleepTimeUs();
1944 uint32_t sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001945
1946 while (!exitPending())
1947 {
1948 processConfigEvents();
1949
Eric Laurent0e49d352009-11-09 23:32:22 -08001950 mixerStatus = MIXER_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001951 { // scope for the mLock
1952
1953 Mutex::Autolock _l(mLock);
1954
1955 if (checkForNewParameters_l()) {
1956 mixBufferSize = mFrameCount*mFrameSize;
Eric Laurent7e2aad12009-12-18 05:47:48 -08001957 updateWaitTime();
Eric Laurent0e49d352009-11-09 23:32:22 -08001958 activeSleepTime = activeSleepTimeUs();
1959 idleSleepTime = idleSleepTimeUs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001960 }
1961
1962 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1963
1964 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1965 outputTracks.add(mOutputTracks[i]);
1966 }
1967
1968 // put audio hardware into standby after short delay
1969 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1970 mSuspended) {
1971 if (!mStandby) {
1972 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07001973 outputTracks[i]->stop();
Eric Laurent9d91ad52009-07-17 12:17:14 -07001974 }
1975 mStandby = true;
1976 mBytesWritten = 0;
1977 }
1978
1979 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1980 // we're about to wait, flush the binder command buffer
1981 IPCThreadState::self()->flushCommands();
1982 outputTracks.clear();
1983
1984 if (exitPending()) break;
1985
1986 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1987 mWaitWorkCV.wait(mLock);
1988 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1989 if (mMasterMute == false) {
1990 char value[PROPERTY_VALUE_MAX];
1991 property_get("ro.audio.silent", value, "0");
1992 if (atoi(value)) {
1993 LOGD("Silence is golden");
1994 setMasterMute(true);
1995 }
1996 }
1997
1998 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurent0e49d352009-11-09 23:32:22 -08001999 sleepTime = idleSleepTime;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002000 continue;
2001 }
2002 }
2003
Eric Laurent0e49d352009-11-09 23:32:22 -08002004 mixerStatus = prepareTracks_l(activeTracks, &tracksToRemove);
Eric Laurentaef692f2009-09-22 00:35:48 -07002005 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002006
Eric Laurent0e49d352009-11-09 23:32:22 -08002007 if (LIKELY(mixerStatus == MIXER_TRACKS_READY)) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002008 // mix buffers...
Eric Laurent7e2aad12009-12-18 05:47:48 -08002009 if (outputsReady(outputTracks)) {
2010 mAudioMixer->process(curBuf);
2011 } else {
2012 memset(curBuf, 0, mixBufferSize);
2013 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002014 sleepTime = 0;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002015 writeFrames = mFrameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002016 } else {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002017 if (sleepTime == 0) {
Eric Laurent0e49d352009-11-09 23:32:22 -08002018 if (mixerStatus == MIXER_TRACKS_ENABLED) {
2019 sleepTime = activeSleepTime;
2020 } else {
2021 sleepTime = idleSleepTime;
2022 }
Eric Laurentf5e868b2009-10-05 20:29:18 -07002023 } else if (mBytesWritten != 0) {
2024 // flush remaining overflow buffers in output tracks
2025 for (size_t i = 0; i < outputTracks.size(); i++) {
2026 if (outputTracks[i]->isActive()) {
2027 sleepTime = 0;
2028 writeFrames = 0;
2029 break;
2030 }
2031 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002032 }
2033 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002034
2035 if (mSuspended) {
Eric Laurent0e49d352009-11-09 23:32:22 -08002036 sleepTime = idleSleepTime;
Eric Laurentaef692f2009-09-22 00:35:48 -07002037 }
2038 // sleepTime == 0 means we must write to audio hardware
2039 if (sleepTime == 0) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002040 standbyTime = systemTime() + kStandbyTimeInNsecs;
Eric Laurentaef692f2009-09-22 00:35:48 -07002041 for (size_t i = 0; i < outputTracks.size(); i++) {
Eric Laurentf5e868b2009-10-05 20:29:18 -07002042 outputTracks[i]->write(curBuf, writeFrames);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002043 }
Eric Laurentaef692f2009-09-22 00:35:48 -07002044 mStandby = false;
2045 mBytesWritten += mixBufferSize;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002046 } else {
Eric Laurentaef692f2009-09-22 00:35:48 -07002047 usleep(sleepTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002048 }
2049
2050 // finally let go of all our tracks, without the lock held
2051 // since we can't guarantee the destructors won't acquire that
2052 // same lock.
2053 tracksToRemove.clear();
2054 outputTracks.clear();
2055 }
2056
Eric Laurent9d91ad52009-07-17 12:17:14 -07002057 return false;
2058}
2059
2060void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
2061{
2062 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
2063 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
Eric Laurent7e2aad12009-12-18 05:47:48 -08002064 this,
Eric Laurent9d91ad52009-07-17 12:17:14 -07002065 mSampleRate,
2066 mFormat,
2067 mChannelCount,
2068 frameCount);
Eric Laurentf5aba822009-08-10 23:22:32 -07002069 if (outputTrack->cblk() != NULL) {
2070 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
2071 mOutputTracks.add(outputTrack);
2072 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
Eric Laurent7e2aad12009-12-18 05:47:48 -08002073 updateWaitTime();
Eric Laurentf5aba822009-08-10 23:22:32 -07002074 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002075}
2076
2077void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
2078{
2079 Mutex::Autolock _l(mLock);
2080 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2081 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
Eric Laurentf5aba822009-08-10 23:22:32 -07002082 mOutputTracks[i]->destroy();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002083 mOutputTracks.removeAt(i);
Eric Laurent7e2aad12009-12-18 05:47:48 -08002084 updateWaitTime();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002085 return;
2086 }
2087 }
2088 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
2089}
2090
Eric Laurent7e2aad12009-12-18 05:47:48 -08002091void AudioFlinger::DuplicatingThread::updateWaitTime()
2092{
2093 mWaitTimeMs = UINT_MAX;
2094 for (size_t i = 0; i < mOutputTracks.size(); i++) {
2095 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
2096 if (strong != NULL) {
2097 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
2098 if (waitTimeMs < mWaitTimeMs) {
2099 mWaitTimeMs = waitTimeMs;
2100 }
2101 }
2102 }
2103}
2104
2105
2106bool AudioFlinger::DuplicatingThread::outputsReady(SortedVector< sp<OutputTrack> > &outputTracks)
2107{
2108 for (size_t i = 0; i < outputTracks.size(); i++) {
2109 sp <ThreadBase> thread = outputTracks[i]->thread().promote();
2110 if (thread == 0) {
2111 LOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p", outputTracks[i].get());
2112 return false;
2113 }
2114 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2115 if (playbackThread->standby() && !playbackThread->isSuspended()) {
2116 LOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(), thread.get());
2117 return false;
2118 }
2119 }
2120 return true;
2121}
2122
2123uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs()
2124{
2125 return (mWaitTimeMs * 1000) / 2;
2126}
2127
Eric Laurent9d91ad52009-07-17 12:17:14 -07002128// ----------------------------------------------------------------------------
2129
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002130// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002131AudioFlinger::ThreadBase::TrackBase::TrackBase(
2132 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002133 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002134 uint32_t sampleRate,
2135 int format,
2136 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002137 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002139 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002140 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002141 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002142 mClient(client),
Eric Laurent6ad8c642009-09-09 05:16:08 -07002143 mCblk(0),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002144 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002145 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002146 mClientTid(-1),
2147 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002149{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002150 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2151
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002152 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002153 size_t size = sizeof(audio_track_cblk_t);
2154 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2155 if (sharedBuffer == 0) {
2156 size += bufferSize;
2157 }
2158
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002159 if (client != NULL) {
2160 mCblkMemory = client->heap()->allocate(size);
2161 if (mCblkMemory != 0) {
2162 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2163 if (mCblk) { // construct the shared structure in-place.
2164 new(mCblk) audio_track_cblk_t();
2165 // clear all buffers
2166 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002167 mCblk->sampleRate = sampleRate;
2168 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169 if (sharedBuffer == 0) {
2170 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2171 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2172 // Force underrun condition to avoid false underrun callback until first data is
2173 // written to buffer
2174 mCblk->flowControlFlag = 1;
2175 } else {
2176 mBuffer = sharedBuffer->pointer();
2177 }
2178 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002179 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180 } else {
2181 LOGE("not enough memory for AudioTrack size=%u", size);
2182 client->heap()->dump("AudioTrack");
2183 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002184 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002185 } else {
2186 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2187 if (mCblk) { // construct the shared structure in-place.
2188 new(mCblk) audio_track_cblk_t();
2189 // clear all buffers
2190 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002191 mCblk->sampleRate = sampleRate;
2192 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2194 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2195 // Force underrun condition to avoid false underrun callback until first data is
2196 // written to buffer
2197 mCblk->flowControlFlag = 1;
2198 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2199 }
2200 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002201}
2202
Eric Laurentbdc0f842009-09-16 06:02:45 -07002203AudioFlinger::ThreadBase::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002204{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002205 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002206 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2207 if (mClient == NULL) {
2208 delete mCblk;
2209 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002210 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002211 mCblkMemory.clear(); // and free the shared memory
Eric Laurent0f8ab672009-09-17 05:12:56 -07002212 if (mClient != NULL) {
2213 Mutex::Autolock _l(mClient->audioFlinger()->mLock);
2214 mClient.clear();
2215 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002216}
2217
Eric Laurentbdc0f842009-09-16 06:02:45 -07002218void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002219{
2220 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002221 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002222 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002223 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002224}
2225
Eric Laurentbdc0f842009-09-16 06:02:45 -07002226bool AudioFlinger::ThreadBase::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002227 bool result;
2228 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002229
2230 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002231 if (!result) {
2232 LOGV("stepServer failed acquiring cblk mutex");
2233 mFlags |= STEPSERVER_FAILED;
2234 }
2235 return result;
2236}
2237
Eric Laurentbdc0f842009-09-16 06:02:45 -07002238void AudioFlinger::ThreadBase::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002239 audio_track_cblk_t* cblk = this->cblk();
2240
2241 cblk->user = 0;
2242 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002243 cblk->userBase = 0;
2244 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002246 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002247}
2248
Eric Laurentbdc0f842009-09-16 06:02:45 -07002249sp<IMemory> AudioFlinger::ThreadBase::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002250{
2251 return mCblkMemory;
2252}
2253
Eric Laurentbdc0f842009-09-16 06:02:45 -07002254int AudioFlinger::ThreadBase::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002255 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002256}
2257
Eric Laurentbdc0f842009-09-16 06:02:45 -07002258int AudioFlinger::ThreadBase::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002259 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002260}
2261
Eric Laurentbdc0f842009-09-16 06:02:45 -07002262void* AudioFlinger::ThreadBase::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002263 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002264 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2265 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002266
2267 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002268 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2269 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002270 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2271 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002272 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002273 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002274 return 0;
2275 }
2276
2277 return bufferStart;
2278}
2279
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002280// ----------------------------------------------------------------------------
2281
Eric Laurent9d91ad52009-07-17 12:17:14 -07002282// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2283AudioFlinger::PlaybackThread::Track::Track(
2284 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002285 const sp<Client>& client,
2286 int streamType,
2287 uint32_t sampleRate,
2288 int format,
2289 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002290 int frameCount,
2291 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002292 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2293 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002294{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002295 if (mCblk != NULL) {
2296 sp<ThreadBase> baseThread = thread.promote();
2297 if (baseThread != 0) {
2298 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2299 mName = playbackThread->getTrackName_l();
2300 }
2301 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2302 if (mName < 0) {
2303 LOGE("no more track names available");
2304 }
2305 mVolume[0] = 1.0f;
2306 mVolume[1] = 1.0f;
2307 mStreamType = streamType;
2308 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2309 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2310 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002311 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002312}
2313
Eric Laurent9d91ad52009-07-17 12:17:14 -07002314AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002315{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002316 LOGV("PlaybackThread::Track destructor");
2317 sp<ThreadBase> thread = mThread.promote();
2318 if (thread != 0) {
Eric Laurentd3fc8ac2009-12-01 02:17:41 -08002319 Mutex::Autolock _l(thread->mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002320 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002321 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002322}
2323
Eric Laurent9d91ad52009-07-17 12:17:14 -07002324void AudioFlinger::PlaybackThread::Track::destroy()
2325{
2326 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2327 // by removing it from mTracks vector, so there is a risk that this Tracks's
2328 // desctructor is called. As the destructor needs to lock mLock,
2329 // we must acquire a strong reference on this Track before locking mLock
2330 // here so that the destructor is called only when exiting this function.
2331 // On the other hand, as long as Track::destroy() is only called by
2332 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2333 // this Track with its member mTrack.
2334 sp<Track> keep(this);
2335 { // scope for mLock
2336 sp<ThreadBase> thread = mThread.promote();
2337 if (thread != 0) {
Eric Laurentd3fc8ac2009-12-01 02:17:41 -08002338 if (!isOutputTrack()) {
2339 if (mState == ACTIVE || mState == RESUMING) {
2340 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2341 }
2342 AudioSystem::releaseOutput(thread->id());
Eric Laurent09b4ba82009-11-19 09:00:56 -08002343 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002344 Mutex::Autolock _l(thread->mLock);
2345 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2346 playbackThread->destroyTrack_l(this);
2347 }
2348 }
2349}
2350
2351void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002352{
Eric Laurentee47d432009-11-07 00:01:32 -08002353 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 -07002354 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002356 mStreamType,
2357 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002358 mCblk->channels,
2359 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002360 mState,
2361 mMute,
2362 mFillingUpStatus,
2363 mCblk->sampleRate,
2364 mCblk->volume[0],
2365 mCblk->volume[1],
2366 mCblk->server,
2367 mCblk->user);
2368}
2369
Eric Laurent9d91ad52009-07-17 12:17:14 -07002370status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002371{
2372 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002373 uint32_t framesReady;
2374 uint32_t framesReq = buffer->frameCount;
2375
2376 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002377 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2378 if (!step()) goto getNextBuffer_exit;
2379 LOGV("stepServer recovered");
2380 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2381 }
2382
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002383 framesReady = cblk->framesReady();
2384
2385 if (LIKELY(framesReady)) {
2386 uint32_t s = cblk->server;
2387 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2388
2389 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2390 if (framesReq > framesReady) {
2391 framesReq = framesReady;
2392 }
2393 if (s + framesReq > bufferEnd) {
2394 framesReq = bufferEnd - s;
2395 }
2396
2397 buffer->raw = getBuffer(s, framesReq);
2398 if (buffer->raw == 0) goto getNextBuffer_exit;
2399
2400 buffer->frameCount = framesReq;
2401 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002402 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002403
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002404getNextBuffer_exit:
2405 buffer->raw = 0;
2406 buffer->frameCount = 0;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002407 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 -07002408 return NOT_ENOUGH_DATA;
2409}
2410
Eric Laurent9d91ad52009-07-17 12:17:14 -07002411bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002412 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002413
2414 if (mCblk->framesReady() >= mCblk->frameCount ||
2415 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002416 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002417 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002418 return true;
2419 }
2420 return false;
2421}
2422
Eric Laurent9d91ad52009-07-17 12:17:14 -07002423status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002424{
Eric Laurent09b4ba82009-11-19 09:00:56 -08002425 status_t status = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002426 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2427 sp<ThreadBase> thread = mThread.promote();
2428 if (thread != 0) {
2429 Mutex::Autolock _l(thread->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08002430 int state = mState;
2431 // here the track could be either new, or restarted
2432 // in both cases "unstop" the track
2433 if (mState == PAUSED) {
2434 mState = TrackBase::RESUMING;
2435 LOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
2436 } else {
2437 mState = TrackBase::ACTIVE;
2438 LOGV("? => ACTIVE (%d) on thread %p", mName, this);
2439 }
2440
2441 if (!isOutputTrack() && state != ACTIVE && state != RESUMING) {
2442 thread->mLock.unlock();
2443 status = AudioSystem::startOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2444 thread->mLock.lock();
2445 }
2446 if (status == NO_ERROR) {
2447 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2448 playbackThread->addTrack_l(this);
2449 } else {
2450 mState = state;
2451 }
2452 } else {
2453 status = BAD_VALUE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002454 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08002455 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002456}
2457
Eric Laurent9d91ad52009-07-17 12:17:14 -07002458void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002459{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002460 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2461 sp<ThreadBase> thread = mThread.promote();
2462 if (thread != 0) {
2463 Mutex::Autolock _l(thread->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08002464 int state = mState;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002465 if (mState > STOPPED) {
2466 mState = STOPPED;
2467 // If the track is not active (PAUSED and buffers full), flush buffers
2468 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2469 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2470 reset();
2471 }
Eric Laurentf5e868b2009-10-05 20:29:18 -07002472 LOGV("(> STOPPED) => STOPPED (%d) on thread %p", mName, playbackThread);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002473 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08002474 if (!isOutputTrack() && (state == ACTIVE || state == RESUMING)) {
2475 thread->mLock.unlock();
2476 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2477 thread->mLock.lock();
2478 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002479 }
2480}
2481
Eric Laurent9d91ad52009-07-17 12:17:14 -07002482void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002483{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002485 sp<ThreadBase> thread = mThread.promote();
2486 if (thread != 0) {
2487 Mutex::Autolock _l(thread->mLock);
2488 if (mState == ACTIVE || mState == RESUMING) {
2489 mState = PAUSING;
Eric Laurentf5e868b2009-10-05 20:29:18 -07002490 LOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
Eric Laurent09b4ba82009-11-19 09:00:56 -08002491 if (!isOutputTrack()) {
2492 thread->mLock.unlock();
2493 AudioSystem::stopOutput(thread->id(), (AudioSystem::stream_type)mStreamType);
2494 thread->mLock.lock();
2495 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002496 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002497 }
2498}
2499
Eric Laurent9d91ad52009-07-17 12:17:14 -07002500void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002501{
2502 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002503 sp<ThreadBase> thread = mThread.promote();
2504 if (thread != 0) {
2505 Mutex::Autolock _l(thread->mLock);
2506 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2507 return;
2508 }
2509 // No point remaining in PAUSED state after a flush => go to
2510 // STOPPED state
2511 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002512
Eric Laurent9d91ad52009-07-17 12:17:14 -07002513 mCblk->lock.lock();
2514 // NOTE: reset() will reset cblk->user and cblk->server with
2515 // the risk that at the same time, the AudioMixer is trying to read
2516 // data. In this case, getNextBuffer() would return a NULL pointer
2517 // as audio buffer => the AudioMixer code MUST always test that pointer
2518 // returned by getNextBuffer() is not NULL!
2519 reset();
2520 mCblk->lock.unlock();
2521 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002522}
2523
Eric Laurent9d91ad52009-07-17 12:17:14 -07002524void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002525{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002526 // Do not reset twice to avoid discarding data written just after a flush and before
2527 // the audioflinger thread detects the track is stopped.
2528 if (!mResetDone) {
2529 TrackBase::reset();
2530 // Force underrun condition to avoid false underrun callback until first data is
2531 // written to buffer
2532 mCblk->flowControlFlag = 1;
2533 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002534 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002535 mResetDone = true;
2536 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002537}
2538
Eric Laurent9d91ad52009-07-17 12:17:14 -07002539void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002540{
2541 mMute = muted;
2542}
2543
Eric Laurent9d91ad52009-07-17 12:17:14 -07002544void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002545{
2546 mVolume[0] = left;
2547 mVolume[1] = right;
2548}
2549
2550// ----------------------------------------------------------------------------
2551
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002552// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002553AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2554 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002555 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556 uint32_t sampleRate,
2557 int format,
2558 int channelCount,
2559 int frameCount,
2560 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002561 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002563 mOverflow(false)
2564{
Eric Laurent6ad8c642009-09-09 05:16:08 -07002565 if (mCblk != NULL) {
2566 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2567 if (format == AudioSystem::PCM_16_BIT) {
2568 mCblk->frameSize = channelCount * sizeof(int16_t);
2569 } else if (format == AudioSystem::PCM_8_BIT) {
2570 mCblk->frameSize = channelCount * sizeof(int8_t);
2571 } else {
2572 mCblk->frameSize = sizeof(int8_t);
2573 }
2574 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002575}
2576
2577AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578{
Eric Laurent09b4ba82009-11-19 09:00:56 -08002579 sp<ThreadBase> thread = mThread.promote();
2580 if (thread != 0) {
2581 AudioSystem::releaseInput(thread->id());
2582 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583}
2584
Eric Laurent9d91ad52009-07-17 12:17:14 -07002585status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586{
2587 audio_track_cblk_t* cblk = this->cblk();
2588 uint32_t framesAvail;
2589 uint32_t framesReq = buffer->frameCount;
2590
2591 // Check if last stepServer failed, try to step now
2592 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2593 if (!step()) goto getNextBuffer_exit;
2594 LOGV("stepServer recovered");
2595 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2596 }
2597
2598 framesAvail = cblk->framesAvailable_l();
2599
2600 if (LIKELY(framesAvail)) {
2601 uint32_t s = cblk->server;
2602 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2603
2604 if (framesReq > framesAvail) {
2605 framesReq = framesAvail;
2606 }
2607 if (s + framesReq > bufferEnd) {
2608 framesReq = bufferEnd - s;
2609 }
2610
2611 buffer->raw = getBuffer(s, framesReq);
2612 if (buffer->raw == 0) goto getNextBuffer_exit;
2613
2614 buffer->frameCount = framesReq;
2615 return NO_ERROR;
2616 }
2617
2618getNextBuffer_exit:
2619 buffer->raw = 0;
2620 buffer->frameCount = 0;
2621 return NOT_ENOUGH_DATA;
2622}
2623
Eric Laurent9d91ad52009-07-17 12:17:14 -07002624status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002626 sp<ThreadBase> thread = mThread.promote();
2627 if (thread != 0) {
2628 RecordThread *recordThread = (RecordThread *)thread.get();
2629 return recordThread->start(this);
Eric Laurent09b4ba82009-11-19 09:00:56 -08002630 } else {
2631 return BAD_VALUE;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002632 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633}
2634
Eric Laurent9d91ad52009-07-17 12:17:14 -07002635void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002636{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002637 sp<ThreadBase> thread = mThread.promote();
2638 if (thread != 0) {
2639 RecordThread *recordThread = (RecordThread *)thread.get();
2640 recordThread->stop(this);
2641 TrackBase::reset();
2642 // Force overerrun condition to avoid false overrun callback until first data is
2643 // read from buffer
2644 mCblk->flowControlFlag = 1;
2645 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646}
2647
Eric Laurentee47d432009-11-07 00:01:32 -08002648void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
2649{
2650 snprintf(buffer, size, " %05d %03u %03u %04u %01d %05u %08x %08x\n",
2651 (mClient == NULL) ? getpid() : mClient->pid(),
2652 mFormat,
2653 mCblk->channels,
2654 mFrameCount,
2655 mState,
2656 mCblk->sampleRate,
2657 mCblk->server,
2658 mCblk->user);
2659}
2660
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661
2662// ----------------------------------------------------------------------------
2663
Eric Laurent9d91ad52009-07-17 12:17:14 -07002664AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2665 const wp<ThreadBase>& thread,
Eric Laurent7e2aad12009-12-18 05:47:48 -08002666 DuplicatingThread *sourceThread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 uint32_t sampleRate,
2668 int format,
2669 int channelCount,
2670 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002671 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
Eric Laurent7e2aad12009-12-18 05:47:48 -08002672 mActive(false), mSourceThread(sourceThread)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002673{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002674
2675 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
Eric Laurentf5aba822009-08-10 23:22:32 -07002676 if (mCblk != NULL) {
2677 mCblk->out = 1;
2678 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2679 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2680 mOutBuffer.frameCount = 0;
Eric Laurentf5aba822009-08-10 23:22:32 -07002681 playbackThread->mTracks.add(this);
Eric Laurent7e2aad12009-12-18 05:47:48 -08002682 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p",
2683 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd);
Eric Laurentf5aba822009-08-10 23:22:32 -07002684 } else {
2685 LOGW("Error creating output track on thread %p", playbackThread);
2686 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687}
2688
Eric Laurent9d91ad52009-07-17 12:17:14 -07002689AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690{
Eric Laurentf5aba822009-08-10 23:22:32 -07002691 clearBufferQueue();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002692}
2693
Eric Laurent9d91ad52009-07-17 12:17:14 -07002694status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695{
2696 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002697 if (status != NO_ERROR) {
2698 return status;
2699 }
2700
2701 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 mRetryCount = 127;
2703 return status;
2704}
2705
Eric Laurent9d91ad52009-07-17 12:17:14 -07002706void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707{
2708 Track::stop();
2709 clearBufferQueue();
2710 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002711 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712}
2713
Eric Laurent9d91ad52009-07-17 12:17:14 -07002714bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715{
2716 Buffer *pInBuffer;
2717 Buffer inBuffer;
2718 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002719 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720 inBuffer.frameCount = frames;
2721 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002722
Eric Laurent7e2aad12009-12-18 05:47:48 -08002723 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002724
Eric Laurentf5e868b2009-10-05 20:29:18 -07002725 if (!mActive && frames != 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002726 start();
2727 sp<ThreadBase> thread = mThread.promote();
2728 if (thread != 0) {
2729 MixerThread *mixerThread = (MixerThread *)thread.get();
2730 if (mCblk->frameCount > frames){
2731 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2732 uint32_t startFrames = (mCblk->frameCount - frames);
2733 pInBuffer = new Buffer;
2734 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2735 pInBuffer->frameCount = startFrames;
2736 pInBuffer->i16 = pInBuffer->mBuffer;
2737 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2738 mBufferQueue.add(pInBuffer);
2739 } else {
2740 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002743 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 }
2745
Eric Laurent9d91ad52009-07-17 12:17:14 -07002746 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747 // First write pending buffers, then new data
2748 if (mBufferQueue.size()) {
2749 pInBuffer = mBufferQueue.itemAt(0);
2750 } else {
2751 pInBuffer = &inBuffer;
2752 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002753
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002754 if (pInBuffer->frameCount == 0) {
2755 break;
2756 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002757
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 if (mOutBuffer.frameCount == 0) {
2759 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002760 nsecs_t startTime = systemTime();
2761 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
Eric Laurent7e2aad12009-12-18 05:47:48 -08002762 LOGV ("OutputTrack::write() %p thread %p no more output buffers", this, mThread.unsafe_get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002763 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 break;
2765 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002766 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002767 if (waitTimeLeftMs >= waitTimeMs) {
2768 waitTimeLeftMs -= waitTimeMs;
2769 } else {
2770 waitTimeLeftMs = 0;
2771 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2775 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2776 mCblk->stepUser(outFrames);
2777 pInBuffer->frameCount -= outFrames;
2778 pInBuffer->i16 += outFrames * channels;
2779 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002780 mOutBuffer.i16 += outFrames * channels;
2781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002782 if (pInBuffer->frameCount == 0) {
2783 if (mBufferQueue.size()) {
2784 mBufferQueue.removeAt(0);
2785 delete [] pInBuffer->mBuffer;
2786 delete pInBuffer;
Eric Laurent7e2aad12009-12-18 05:47:48 -08002787 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 -08002788 } else {
2789 break;
2790 }
2791 }
2792 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002793
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794 // If we could not write all frames, allocate a buffer and queue it for next time.
2795 if (inBuffer.frameCount) {
Eric Laurent7e2aad12009-12-18 05:47:48 -08002796 sp<ThreadBase> thread = mThread.promote();
2797 if (thread != 0 && !thread->standby()) {
2798 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2799 pInBuffer = new Buffer;
2800 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2801 pInBuffer->frameCount = inBuffer.frameCount;
2802 pInBuffer->i16 = pInBuffer->mBuffer;
2803 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2804 mBufferQueue.add(pInBuffer);
2805 LOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, mThread.unsafe_get(), mBufferQueue.size());
2806 } else {
2807 LOGW("OutputTrack::write() %p thread %p no more overflow buffers", mThread.unsafe_get(), this);
2808 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002809 }
2810 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002811
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002813 // 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 -08002814 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002815 if (frames == 0 && mBufferQueue.size() == 0) {
2816 if (mCblk->user < mCblk->frameCount) {
2817 frames = mCblk->frameCount - mCblk->user;
2818 pInBuffer = new Buffer;
2819 pInBuffer->mBuffer = new int16_t[frames * channels];
2820 pInBuffer->frameCount = frames;
2821 pInBuffer->i16 = pInBuffer->mBuffer;
2822 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2823 mBufferQueue.add(pInBuffer);
Eric Laurentf5e868b2009-10-05 20:29:18 -07002824 } else if (mActive) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002825 stop();
2826 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 }
2828
Eric Laurent9d91ad52009-07-17 12:17:14 -07002829 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830}
2831
Eric Laurent9d91ad52009-07-17 12:17:14 -07002832status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833{
2834 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 status_t result;
2836 audio_track_cblk_t* cblk = mCblk;
2837 uint32_t framesReq = buffer->frameCount;
2838
Eric Laurent9d91ad52009-07-17 12:17:14 -07002839// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002841
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002842 uint32_t framesAvail = cblk->framesAvailable();
2843
Eric Laurent9d91ad52009-07-17 12:17:14 -07002844
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002846 Mutex::Autolock _l(cblk->lock);
2847 goto start_loop_here;
2848 while (framesAvail == 0) {
2849 active = mActive;
2850 if (UNLIKELY(!active)) {
2851 LOGV("Not active and NO_MORE_BUFFERS");
2852 return AudioTrack::NO_MORE_BUFFERS;
2853 }
2854 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2855 if (result != NO_ERROR) {
2856 return AudioTrack::NO_MORE_BUFFERS;
2857 }
2858 // read the server count again
2859 start_loop_here:
2860 framesAvail = cblk->framesAvailable_l();
2861 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 }
2863
Eric Laurent9d91ad52009-07-17 12:17:14 -07002864// if (framesAvail < framesReq) {
2865// return AudioTrack::NO_MORE_BUFFERS;
2866// }
2867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 if (framesReq > framesAvail) {
2869 framesReq = framesAvail;
2870 }
2871
2872 uint32_t u = cblk->user;
2873 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2874
2875 if (u + framesReq > bufferEnd) {
2876 framesReq = bufferEnd - u;
2877 }
2878
2879 buffer->frameCount = framesReq;
2880 buffer->raw = (void *)cblk->buffer(u);
2881 return NO_ERROR;
2882}
2883
2884
Eric Laurent9d91ad52009-07-17 12:17:14 -07002885void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886{
2887 size_t size = mBufferQueue.size();
2888 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002889
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 for (size_t i = 0; i < size; i++) {
2891 pBuffer = mBufferQueue.itemAt(i);
2892 delete [] pBuffer->mBuffer;
2893 delete pBuffer;
2894 }
2895 mBufferQueue.clear();
2896}
2897
2898// ----------------------------------------------------------------------------
2899
2900AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2901 : RefBase(),
2902 mAudioFlinger(audioFlinger),
2903 mMemoryDealer(new MemoryDealer(1024*1024)),
2904 mPid(pid)
2905{
2906 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2907}
2908
Eric Laurent0f8ab672009-09-17 05:12:56 -07002909// Client destructor must be called with AudioFlinger::mLock held
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910AudioFlinger::Client::~Client()
2911{
Eric Laurent0f8ab672009-09-17 05:12:56 -07002912 mAudioFlinger->removeClient_l(mPid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913}
2914
2915const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2916{
2917 return mMemoryDealer;
2918}
2919
2920// ----------------------------------------------------------------------------
2921
Eric Laurent9d91ad52009-07-17 12:17:14 -07002922AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002923 : BnAudioTrack(),
2924 mTrack(track)
2925{
2926}
2927
2928AudioFlinger::TrackHandle::~TrackHandle() {
2929 // just stop the track on deletion, associated resources
2930 // will be freed from the main thread once all pending buffers have
2931 // been played. Unless it's not in the active track list, in which
2932 // case we free everything now...
2933 mTrack->destroy();
2934}
2935
2936status_t AudioFlinger::TrackHandle::start() {
2937 return mTrack->start();
2938}
2939
2940void AudioFlinger::TrackHandle::stop() {
2941 mTrack->stop();
2942}
2943
2944void AudioFlinger::TrackHandle::flush() {
2945 mTrack->flush();
2946}
2947
2948void AudioFlinger::TrackHandle::mute(bool e) {
2949 mTrack->mute(e);
2950}
2951
2952void AudioFlinger::TrackHandle::pause() {
2953 mTrack->pause();
2954}
2955
2956void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2957 mTrack->setVolume(left, right);
2958}
2959
2960sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2961 return mTrack->getCblk();
2962}
2963
2964status_t AudioFlinger::TrackHandle::onTransact(
2965 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2966{
2967 return BnAudioTrack::onTransact(code, data, reply, flags);
2968}
2969
2970// ----------------------------------------------------------------------------
2971
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002972sp<IAudioRecord> AudioFlinger::openRecord(
2973 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002974 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002975 uint32_t sampleRate,
2976 int format,
2977 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002978 int frameCount,
2979 uint32_t flags,
2980 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002981{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002982 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002983 sp<RecordHandle> recordHandle;
2984 sp<Client> client;
2985 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002986 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002987 RecordThread *thread;
2988 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002989
2990 // check calling permissions
2991 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002992 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002993 goto Exit;
2994 }
2995
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002996 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002997 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002998 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002999 thread = checkRecordThread_l(input);
3000 if (thread == NULL) {
3001 lStatus = BAD_VALUE;
3002 goto Exit;
3003 }
3004
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003005 wclient = mClients.valueFor(pid);
3006 if (wclient != NULL) {
3007 client = wclient.promote();
3008 } else {
3009 client = new Client(this, pid);
3010 mClients.add(pid, client);
3011 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07003012
The Android Open Source Project22f8def2009-03-09 11:52:12 -07003013 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07003014 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07003015 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003016 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017 if (recordTrack->getCblk() == NULL) {
Eric Laurent0f8ab672009-09-17 05:12:56 -07003018 // remove local strong reference to Client before deleting the RecordTrack so that the Client
3019 // destructor is called by the TrackBase destructor with mLock held
3020 client.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021 recordTrack.clear();
3022 lStatus = NO_MEMORY;
3023 goto Exit;
3024 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003025
3026 // return to handle to client
3027 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003028 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003029
3030Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003031 if (status) {
3032 *status = lStatus;
3033 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003034 return recordHandle;
3035}
3036
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003037// ----------------------------------------------------------------------------
3038
Eric Laurent9d91ad52009-07-17 12:17:14 -07003039AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003040 : BnAudioRecord(),
3041 mRecordTrack(recordTrack)
3042{
3043}
3044
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003045AudioFlinger::RecordHandle::~RecordHandle() {
3046 stop();
3047}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003048
3049status_t AudioFlinger::RecordHandle::start() {
3050 LOGV("RecordHandle::start()");
3051 return mRecordTrack->start();
3052}
3053
3054void AudioFlinger::RecordHandle::stop() {
3055 LOGV("RecordHandle::stop()");
3056 mRecordTrack->stop();
3057}
3058
3059sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
3060 return mRecordTrack->getCblk();
3061}
3062
3063status_t AudioFlinger::RecordHandle::onTransact(
3064 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3065{
3066 return BnAudioRecord::onTransact(code, data, reply, flags);
3067}
3068
3069// ----------------------------------------------------------------------------
3070
Eric Laurent09b4ba82009-11-19 09:00:56 -08003071AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels, int id) :
3072 ThreadBase(audioFlinger, id),
Eric Laurent9d91ad52009-07-17 12:17:14 -07003073 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003074{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003075 mReqChannelCount = AudioSystem::popCount(channels);
3076 mReqSampleRate = sampleRate;
3077 readInputParameters();
3078 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003079}
3080
Eric Laurent9d91ad52009-07-17 12:17:14 -07003081
3082AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003083{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003084 delete[] mRsmpInBuffer;
3085 if (mResampler != 0) {
3086 delete mResampler;
3087 delete[] mRsmpOutBuffer;
3088 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003089}
3090
Eric Laurent9d91ad52009-07-17 12:17:14 -07003091void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003092{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003093 const size_t SIZE = 256;
3094 char buffer[SIZE];
3095
3096 snprintf(buffer, SIZE, "Record Thread %p", this);
3097
3098 run(buffer, PRIORITY_URGENT_AUDIO);
3099}
Eric Laurent09b4ba82009-11-19 09:00:56 -08003100
Eric Laurent9d91ad52009-07-17 12:17:14 -07003101bool AudioFlinger::RecordThread::threadLoop()
3102{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003103 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003104 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003105
3106 // start recording
3107 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003108
Eric Laurent9d91ad52009-07-17 12:17:14 -07003109 processConfigEvents();
3110
3111 { // scope for mLock
3112 Mutex::Autolock _l(mLock);
3113 checkForNewParameters_l();
3114 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
3115 if (!mStandby) {
3116 mInput->standby();
3117 mStandby = true;
3118 }
3119
3120 if (exitPending()) break;
3121
3122 LOGV("RecordThread: loop stopping");
3123 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003124 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003125 LOGV("RecordThread: loop starting");
3126 continue;
3127 }
3128 if (mActiveTrack != 0) {
3129 if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent52910952009-12-05 05:20:01 -08003130 if (!mStandby) {
3131 mInput->standby();
3132 mStandby = true;
3133 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003134 mActiveTrack.clear();
3135 mStartStopCond.broadcast();
3136 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003137 if (mReqChannelCount != mActiveTrack->channelCount()) {
3138 mActiveTrack.clear();
Eric Laurent52910952009-12-05 05:20:01 -08003139 mStartStopCond.broadcast();
3140 } else if (mBytesRead != 0) {
3141 // record start succeeds only if first read from audio input
3142 // succeeds
3143 if (mBytesRead > 0) {
3144 mActiveTrack->mState = TrackBase::ACTIVE;
3145 } else {
3146 mActiveTrack.clear();
3147 }
3148 mStartStopCond.broadcast();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003149 }
Eric Laurent52910952009-12-05 05:20:01 -08003150 mStandby = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003151 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003152 }
3153 }
3154
3155 if (mActiveTrack != 0) {
Eric Laurent52910952009-12-05 05:20:01 -08003156 if (mActiveTrack->mState != TrackBase::ACTIVE &&
3157 mActiveTrack->mState != TrackBase::RESUMING) {
Eric Laurent09b4ba82009-11-19 09:00:56 -08003158 usleep(5000);
3159 continue;
3160 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003161 buffer.frameCount = mFrameCount;
3162 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
3163 size_t framesOut = buffer.frameCount;
3164 if (mResampler == 0) {
3165 // no resampling
3166 while (framesOut) {
3167 size_t framesIn = mFrameCount - mRsmpInIndex;
3168 if (framesIn) {
3169 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
3170 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
3171 if (framesIn > framesOut)
3172 framesIn = framesOut;
3173 mRsmpInIndex += framesIn;
3174 framesOut -= framesIn;
3175 if (mChannelCount == mReqChannelCount ||
3176 mFormat != AudioSystem::PCM_16_BIT) {
3177 memcpy(dst, src, framesIn * mFrameSize);
3178 } else {
3179 int16_t *src16 = (int16_t *)src;
3180 int16_t *dst16 = (int16_t *)dst;
3181 if (mChannelCount == 1) {
3182 while (framesIn--) {
3183 *dst16++ = *src16;
3184 *dst16++ = *src16++;
3185 }
3186 } else {
3187 while (framesIn--) {
3188 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
3189 src16 += 2;
3190 }
3191 }
3192 }
3193 }
3194 if (framesOut && mFrameCount == mRsmpInIndex) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003195 if (framesOut == mFrameCount &&
3196 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
Eric Laurent52910952009-12-05 05:20:01 -08003197 mBytesRead = mInput->read(buffer.raw, mInputBytes);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003198 framesOut = 0;
3199 } else {
Eric Laurent52910952009-12-05 05:20:01 -08003200 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003201 mRsmpInIndex = 0;
3202 }
Eric Laurent52910952009-12-05 05:20:01 -08003203 if (mBytesRead < 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003204 LOGE("Error reading audio input");
Eric Laurent52910952009-12-05 05:20:01 -08003205 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3206 sleep(1);
3207 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003208 mRsmpInIndex = mFrameCount;
3209 framesOut = 0;
3210 buffer.frameCount = 0;
3211 }
3212 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003213 }
3214 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003215 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003216
Eric Laurent9d91ad52009-07-17 12:17:14 -07003217 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
3218 // alter output frame count as if we were expecting stereo samples
3219 if (mChannelCount == 1 && mReqChannelCount == 1) {
3220 framesOut >>= 1;
3221 }
3222 mResampler->resample(mRsmpOutBuffer, framesOut, this);
3223 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
3224 // are 32 bit aligned which should be always true.
3225 if (mChannelCount == 2 && mReqChannelCount == 1) {
3226 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
3227 // the resampler always outputs stereo samples: do post stereo to mono conversion
3228 int16_t *src = (int16_t *)mRsmpOutBuffer;
3229 int16_t *dst = buffer.i16;
3230 while (framesOut--) {
3231 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
3232 src += 2;
3233 }
3234 } else {
3235 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
3236 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003237
Eric Laurent9d91ad52009-07-17 12:17:14 -07003238 }
3239 mActiveTrack->releaseBuffer(&buffer);
3240 mActiveTrack->overflow();
3241 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003242 // client isn't retrieving buffers fast enough
3243 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003244 if (!mActiveTrack->setOverflow())
3245 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003246 // Release the processor for a while before asking for a new buffer.
3247 // This will give the application more chance to read from the buffer and
3248 // clear the overflow.
3249 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003250 }
3251 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003252 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003253
Eric Laurent9d91ad52009-07-17 12:17:14 -07003254 if (!mStandby) {
3255 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003256 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003257 mActiveTrack.clear();
3258
Eric Laurent09b4ba82009-11-19 09:00:56 -08003259 mStartStopCond.broadcast();
3260
Eric Laurent9d91ad52009-07-17 12:17:14 -07003261 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003262 return false;
3263}
3264
Eric Laurent9d91ad52009-07-17 12:17:14 -07003265status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003266{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003267 LOGV("RecordThread::start");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003268 sp <ThreadBase> strongMe = this;
3269 status_t status = NO_ERROR;
3270 {
3271 AutoMutex lock(&mLock);
3272 if (mActiveTrack != 0) {
3273 if (recordTrack != mActiveTrack.get()) {
3274 status = -EBUSY;
3275 } else if (mActiveTrack->mState == TrackBase::PAUSING) {
Eric Laurent52910952009-12-05 05:20:01 -08003276 mActiveTrack->mState = TrackBase::ACTIVE;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003277 }
3278 return status;
3279 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003280
Eric Laurent09b4ba82009-11-19 09:00:56 -08003281 recordTrack->mState = TrackBase::IDLE;
3282 mActiveTrack = recordTrack;
3283 mLock.unlock();
3284 status_t status = AudioSystem::startInput(mId);
3285 mLock.lock();
3286 if (status != NO_ERROR) {
3287 mActiveTrack.clear();
3288 return status;
3289 }
3290 mActiveTrack->mState = TrackBase::RESUMING;
Eric Laurent52910952009-12-05 05:20:01 -08003291 mRsmpInIndex = mFrameCount;
3292 mBytesRead = 0;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003293 // signal thread to start
3294 LOGV("Signal record thread");
3295 mWaitWorkCV.signal();
3296 // do not wait for mStartStopCond if exiting
3297 if (mExiting) {
3298 mActiveTrack.clear();
3299 status = INVALID_OPERATION;
3300 goto startError;
3301 }
3302 mStartStopCond.wait(mLock);
3303 if (mActiveTrack == 0) {
3304 LOGV("Record failed to start");
3305 status = BAD_VALUE;
3306 goto startError;
3307 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003308 LOGV("Record started OK");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003309 return status;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003310 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08003311startError:
3312 AudioSystem::stopInput(mId);
3313 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003314}
3315
Eric Laurent9d91ad52009-07-17 12:17:14 -07003316void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3317 LOGV("RecordThread::stop");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003318 sp <ThreadBase> strongMe = this;
3319 {
3320 AutoMutex lock(&mLock);
3321 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3322 mActiveTrack->mState = TrackBase::PAUSING;
3323 // do not wait for mStartStopCond if exiting
3324 if (mExiting) {
3325 return;
3326 }
3327 mStartStopCond.wait(mLock);
3328 // if we have been restarted, recordTrack == mActiveTrack.get() here
3329 if (mActiveTrack == 0 || recordTrack != mActiveTrack.get()) {
3330 mLock.unlock();
3331 AudioSystem::stopInput(mId);
3332 mLock.lock();
Eric Laurent52910952009-12-05 05:20:01 -08003333 LOGV("Record stopped OK");
Eric Laurent09b4ba82009-11-19 09:00:56 -08003334 }
3335 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003336 }
3337}
3338
Eric Laurent9d91ad52009-07-17 12:17:14 -07003339status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003340{
3341 const size_t SIZE = 256;
3342 char buffer[SIZE];
3343 String8 result;
3344 pid_t pid = 0;
3345
Eric Laurentee47d432009-11-07 00:01:32 -08003346 snprintf(buffer, SIZE, "\nInput thread %p internals\n", this);
3347 result.append(buffer);
3348
3349 if (mActiveTrack != 0) {
3350 result.append("Active Track:\n");
3351 result.append(" Clien Fmt Chn Buf S SRate Serv User\n");
3352 mActiveTrack->dump(buffer, SIZE);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 result.append(buffer);
Eric Laurentee47d432009-11-07 00:01:32 -08003354
3355 snprintf(buffer, SIZE, "In index: %d\n", mRsmpInIndex);
3356 result.append(buffer);
3357 snprintf(buffer, SIZE, "In size: %d\n", mInputBytes);
3358 result.append(buffer);
3359 snprintf(buffer, SIZE, "Resampling: %d\n", (mResampler != 0));
3360 result.append(buffer);
3361 snprintf(buffer, SIZE, "Out channel count: %d\n", mReqChannelCount);
3362 result.append(buffer);
3363 snprintf(buffer, SIZE, "Out sample rate: %d\n", mReqSampleRate);
3364 result.append(buffer);
3365
3366
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003367 } else {
3368 result.append("No record client\n");
3369 }
3370 write(fd, result.string(), result.size());
Eric Laurentee47d432009-11-07 00:01:32 -08003371
3372 dumpBase(fd, args);
3373
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003374 return NO_ERROR;
3375}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003376
Eric Laurent9d91ad52009-07-17 12:17:14 -07003377status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3378{
3379 size_t framesReq = buffer->frameCount;
3380 size_t framesReady = mFrameCount - mRsmpInIndex;
3381 int channelCount;
3382
3383 if (framesReady == 0) {
Eric Laurent52910952009-12-05 05:20:01 -08003384 mBytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3385 if (mBytesRead < 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003386 LOGE("RecordThread::getNextBuffer() Error reading audio input");
Eric Laurent52910952009-12-05 05:20:01 -08003387 if (mActiveTrack->mState == TrackBase::ACTIVE) {
3388 sleep(1);
3389 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003390 buffer->raw = 0;
3391 buffer->frameCount = 0;
3392 return NOT_ENOUGH_DATA;
3393 }
3394 mRsmpInIndex = 0;
3395 framesReady = mFrameCount;
3396 }
3397
3398 if (framesReq > framesReady) {
3399 framesReq = framesReady;
3400 }
3401
3402 if (mChannelCount == 1 && mReqChannelCount == 2) {
3403 channelCount = 1;
3404 } else {
3405 channelCount = 2;
3406 }
3407 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3408 buffer->frameCount = framesReq;
3409 return NO_ERROR;
3410}
3411
3412void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3413{
3414 mRsmpInIndex += buffer->frameCount;
3415 buffer->frameCount = 0;
3416}
3417
3418bool AudioFlinger::RecordThread::checkForNewParameters_l()
3419{
3420 bool reconfig = false;
3421
Eric Laurent3464c012009-08-04 09:45:33 -07003422 while (!mNewParameters.isEmpty()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07003423 status_t status = NO_ERROR;
Eric Laurent3464c012009-08-04 09:45:33 -07003424 String8 keyValuePair = mNewParameters[0];
3425 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003426 int value;
3427 int reqFormat = mFormat;
3428 int reqSamplingRate = mReqSampleRate;
3429 int reqChannelCount = mReqChannelCount;
Eric Laurent3464c012009-08-04 09:45:33 -07003430
Eric Laurent9d91ad52009-07-17 12:17:14 -07003431 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3432 reqSamplingRate = value;
3433 reconfig = true;
3434 }
3435 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3436 reqFormat = value;
3437 reconfig = true;
3438 }
3439 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3440 reqChannelCount = AudioSystem::popCount(value);
3441 reconfig = true;
3442 }
3443 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3444 // do not accept frame count changes if tracks are open as the track buffer
3445 // size depends on frame count and correct behavior would not be garantied
3446 // if frame count is changed after track creation
3447 if (mActiveTrack != 0) {
3448 status = INVALID_OPERATION;
3449 } else {
3450 reconfig = true;
3451 }
3452 }
3453 if (status == NO_ERROR) {
Eric Laurent3464c012009-08-04 09:45:33 -07003454 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003455 if (status == INVALID_OPERATION) {
3456 mInput->standby();
Eric Laurent3464c012009-08-04 09:45:33 -07003457 status = mInput->setParameters(keyValuePair);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003458 }
3459 if (reconfig) {
3460 if (status == BAD_VALUE &&
3461 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3462 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3463 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3464 status = NO_ERROR;
3465 }
3466 if (status == NO_ERROR) {
3467 readInputParameters();
Eric Laurent3464c012009-08-04 09:45:33 -07003468 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003469 }
3470 }
3471 }
Eric Laurentee47d432009-11-07 00:01:32 -08003472
3473 mNewParameters.removeAt(0);
3474
Eric Laurent9d91ad52009-07-17 12:17:14 -07003475 mParamStatus = status;
3476 mParamCond.signal();
Eric Laurent3464c012009-08-04 09:45:33 -07003477 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003478 }
3479 return reconfig;
3480}
3481
3482String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3483{
3484 return mInput->getParameters(keys);
3485}
3486
3487void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3488 AudioSystem::OutputDescriptor desc;
3489 void *param2 = 0;
3490
3491 switch (event) {
3492 case AudioSystem::INPUT_OPENED:
3493 case AudioSystem::INPUT_CONFIG_CHANGED:
3494 desc.channels = mChannelCount;
3495 desc.samplingRate = mSampleRate;
3496 desc.format = mFormat;
3497 desc.frameCount = mFrameCount;
3498 desc.latency = 0;
3499 param2 = &desc;
3500 break;
3501
3502 case AudioSystem::INPUT_CLOSED:
3503 default:
3504 break;
3505 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003506 Mutex::Autolock _l(mAudioFlinger->mLock);
Eric Laurent09b4ba82009-11-19 09:00:56 -08003507 mAudioFlinger->audioConfigChanged_l(event, mId, param2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003508}
3509
3510void AudioFlinger::RecordThread::readInputParameters()
3511{
3512 if (mRsmpInBuffer) delete mRsmpInBuffer;
3513 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3514 if (mResampler) delete mResampler;
3515 mResampler = 0;
3516
3517 mSampleRate = mInput->sampleRate();
3518 mChannelCount = AudioSystem::popCount(mInput->channels());
3519 mFormat = mInput->format();
3520 mFrameSize = mInput->frameSize();
3521 mInputBytes = mInput->bufferSize();
3522 mFrameCount = mInputBytes / mFrameSize;
3523 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3524
3525 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3526 {
3527 int channelCount;
3528 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3529 // stereo to mono post process as the resampler always outputs stereo.
3530 if (mChannelCount == 1 && mReqChannelCount == 2) {
3531 channelCount = 1;
3532 } else {
3533 channelCount = 2;
3534 }
3535 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3536 mResampler->setSampleRate(mSampleRate);
3537 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3538 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3539
3540 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3541 if (mChannelCount == 1 && mReqChannelCount == 1) {
3542 mFrameCount >>= 1;
3543 }
3544
3545 }
3546 mRsmpInIndex = mFrameCount;
3547}
3548
3549// ----------------------------------------------------------------------------
3550
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003551int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003552 uint32_t *pSamplingRate,
3553 uint32_t *pFormat,
3554 uint32_t *pChannels,
3555 uint32_t *pLatencyMs,
3556 uint32_t flags)
3557{
3558 status_t status;
3559 PlaybackThread *thread = NULL;
3560 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3561 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3562 uint32_t format = pFormat ? *pFormat : 0;
3563 uint32_t channels = pChannels ? *pChannels : 0;
3564 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3565
3566 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3567 pDevices ? *pDevices : 0,
3568 samplingRate,
3569 format,
3570 channels,
3571 flags);
3572
3573 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003574 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003575 }
3576 Mutex::Autolock _l(mLock);
3577
3578 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3579 (int *)&format,
3580 &channels,
3581 &samplingRate,
3582 &status);
3583 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3584 output,
3585 samplingRate,
3586 format,
3587 channels,
3588 status);
3589
3590 mHardwareStatus = AUDIO_HW_IDLE;
3591 if (output != 0) {
3592 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3593 (format != AudioSystem::PCM_16_BIT) ||
3594 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
Eric Laurent09b4ba82009-11-19 09:00:56 -08003595 thread = new DirectOutputThread(this, output, ++mNextThreadId);
3596 LOGV("openOutput() created direct output: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003597 } else {
Eric Laurent09b4ba82009-11-19 09:00:56 -08003598 thread = new MixerThread(this, output, ++mNextThreadId);
3599 LOGV("openOutput() created mixer output: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003600 }
Eric Laurent09b4ba82009-11-19 09:00:56 -08003601 mPlaybackThreads.add(mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003602
3603 if (pSamplingRate) *pSamplingRate = samplingRate;
3604 if (pFormat) *pFormat = format;
3605 if (pChannels) *pChannels = channels;
3606 if (pLatencyMs) *pLatencyMs = thread->latency();
Eric Laurent52910952009-12-05 05:20:01 -08003607
3608 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003609 }
3610
Eric Laurent52910952009-12-05 05:20:01 -08003611 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003612}
3613
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003614int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003615{
3616 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003617 MixerThread *thread1 = checkMixerThread_l(output1);
3618 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003619
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003620 if (thread1 == NULL || thread2 == NULL) {
3621 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3622 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003623 }
3624
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003625
Eric Laurent09b4ba82009-11-19 09:00:56 -08003626 DuplicatingThread *thread = new DuplicatingThread(this, thread1, ++mNextThreadId);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003627 thread->addOutputTrack(thread2);
Eric Laurent09b4ba82009-11-19 09:00:56 -08003628 mPlaybackThreads.add(mNextThreadId, thread);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003629 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003630}
3631
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003632status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003633{
Eric Laurentdae20d92009-08-04 08:37:05 -07003634 // keep strong reference on the playback thread so that
3635 // it is not destroyed while exit() is executed
3636 sp <PlaybackThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003637 {
3638 Mutex::Autolock _l(mLock);
3639 thread = checkPlaybackThread_l(output);
3640 if (thread == NULL) {
3641 return BAD_VALUE;
3642 }
3643
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003644 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003645
3646 if (thread->type() == PlaybackThread::MIXER) {
3647 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003648 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3649 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurentdae20d92009-08-04 08:37:05 -07003650 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurent9d91ad52009-07-17 12:17:14 -07003651 }
3652 }
3653 }
Eric Laurentb3687ae2009-09-15 07:10:12 -07003654 void *param2 = 0;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003655 audioConfigChanged_l(AudioSystem::OUTPUT_CLOSED, output, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003656 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003657 }
3658 thread->exit();
3659
Eric Laurentdae20d92009-08-04 08:37:05 -07003660 if (thread->type() != PlaybackThread::DUPLICATING) {
3661 mAudioHardware->closeOutputStream(thread->getOutput());
3662 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003663 return NO_ERROR;
3664}
3665
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003666status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003667{
3668 Mutex::Autolock _l(mLock);
3669 PlaybackThread *thread = checkPlaybackThread_l(output);
3670
3671 if (thread == NULL) {
3672 return BAD_VALUE;
3673 }
3674
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003675 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003676 thread->suspend();
3677
3678 return NO_ERROR;
3679}
3680
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003681status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003682{
3683 Mutex::Autolock _l(mLock);
3684 PlaybackThread *thread = checkPlaybackThread_l(output);
3685
3686 if (thread == NULL) {
3687 return BAD_VALUE;
3688 }
3689
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003690 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003691
3692 thread->restore();
3693
3694 return NO_ERROR;
3695}
3696
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003697int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003698 uint32_t *pSamplingRate,
3699 uint32_t *pFormat,
3700 uint32_t *pChannels,
3701 uint32_t acoustics)
3702{
3703 status_t status;
3704 RecordThread *thread = NULL;
3705 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3706 uint32_t format = pFormat ? *pFormat : 0;
3707 uint32_t channels = pChannels ? *pChannels : 0;
3708 uint32_t reqSamplingRate = samplingRate;
3709 uint32_t reqFormat = format;
3710 uint32_t reqChannels = channels;
3711
3712 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003713 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003714 }
3715 Mutex::Autolock _l(mLock);
3716
3717 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3718 (int *)&format,
3719 &channels,
3720 &samplingRate,
3721 &status,
3722 (AudioSystem::audio_in_acoustics)acoustics);
3723 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3724 input,
3725 samplingRate,
3726 format,
3727 channels,
3728 acoustics,
3729 status);
3730
3731 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3732 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3733 // or stereo to mono conversions on 16 bit PCM inputs.
3734 if (input == 0 && status == BAD_VALUE &&
3735 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3736 (samplingRate <= 2 * reqSamplingRate) &&
3737 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3738 LOGV("openInput() reopening with proposed sampling rate and channels");
3739 input = mAudioHardware->openInputStream(*pDevices,
3740 (int *)&format,
3741 &channels,
3742 &samplingRate,
3743 &status,
3744 (AudioSystem::audio_in_acoustics)acoustics);
3745 }
3746
3747 if (input != 0) {
3748 // Start record thread
Eric Laurent09b4ba82009-11-19 09:00:56 -08003749 thread = new RecordThread(this, input, reqSamplingRate, reqChannels, ++mNextThreadId);
3750 mRecordThreads.add(mNextThreadId, thread);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003751 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003752 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3753 if (pFormat) *pFormat = format;
3754 if (pChannels) *pChannels = reqChannels;
3755
3756 input->standby();
Eric Laurent52910952009-12-05 05:20:01 -08003757
3758 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003759 }
3760
Eric Laurent52910952009-12-05 05:20:01 -08003761 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003762}
3763
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003764status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003765{
Eric Laurentdae20d92009-08-04 08:37:05 -07003766 // keep strong reference on the record thread so that
3767 // it is not destroyed while exit() is executed
3768 sp <RecordThread> thread;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003769 {
3770 Mutex::Autolock _l(mLock);
3771 thread = checkRecordThread_l(input);
3772 if (thread == NULL) {
3773 return BAD_VALUE;
3774 }
3775
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003776 LOGV("closeInput() %d", input);
Eric Laurentb3687ae2009-09-15 07:10:12 -07003777 void *param2 = 0;
Eric Laurent09b4ba82009-11-19 09:00:56 -08003778 audioConfigChanged_l(AudioSystem::INPUT_CLOSED, input, param2);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003779 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003780 }
3781 thread->exit();
3782
Eric Laurentdae20d92009-08-04 08:37:05 -07003783 mAudioHardware->closeInputStream(thread->getInput());
3784
Eric Laurent9d91ad52009-07-17 12:17:14 -07003785 return NO_ERROR;
3786}
3787
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003788status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003789{
3790 Mutex::Autolock _l(mLock);
3791 MixerThread *dstThread = checkMixerThread_l(output);
3792 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003793 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003794 return BAD_VALUE;
3795 }
3796
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003797 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003798
3799 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003800 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003801 if (thread != dstThread &&
3802 thread->type() != PlaybackThread::DIRECT) {
3803 MixerThread *srcThread = (MixerThread *)thread;
3804 SortedVector < sp<MixerThread::Track> > tracks;
3805 SortedVector < wp<MixerThread::Track> > activeTracks;
3806 srcThread->getTracks(tracks, activeTracks, stream);
3807 if (tracks.size()) {
3808 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003809 }
3810 }
3811 }
3812
Eric Laurent06437712009-09-01 05:56:26 -07003813 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
3814
Eric Laurent9d91ad52009-07-17 12:17:14 -07003815 return NO_ERROR;
3816}
3817
3818// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003819AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003820{
3821 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003822 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3823 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003824 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003825 return thread;
3826}
3827
3828// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003829AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003830{
3831 PlaybackThread *thread = checkPlaybackThread_l(output);
3832 if (thread != NULL) {
3833 if (thread->type() == PlaybackThread::DIRECT) {
3834 thread = NULL;
3835 }
3836 }
3837 return (MixerThread *)thread;
3838}
3839
3840// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003841AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003842{
3843 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003844 if (mRecordThreads.indexOfKey(input) >= 0) {
3845 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003846 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003847 return thread;
3848}
3849
3850// ----------------------------------------------------------------------------
3851
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003852status_t AudioFlinger::onTransact(
3853 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3854{
3855 return BnAudioFlinger::onTransact(code, data, reply, flags);
3856}
3857
3858// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003859
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003860void AudioFlinger::instantiate() {
3861 defaultServiceManager()->addService(
3862 String16("media.audio_flinger"), new AudioFlinger());
3863}
3864
3865}; // namespace android