blob: b34f214e61700087f6b782e2e96a9370aead4a43 [file] [log] [blame]
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001/* //device/include/server/AudioFlinger/AudioFlinger.cpp
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include <math.h>
23#include <signal.h>
24#include <sys/time.h>
25#include <sys/resource.h>
26
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070036#include <media/AudioTrack.h>
37#include <media/AudioRecord.h>
38
39#include <private/media/AudioTrackShared.h>
40
The Android Open Source Project8a7a6752009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050// ----------------------------------------------------------------------------
51// the sim build doesn't have gettid
52
53#ifndef HAVE_GETTID
54# define gettid getpid
55#endif
56
57// ----------------------------------------------------------------------------
58
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070059namespace android {
60
The Android Open Source Project4f68be12009-03-18 17:39:46 -070061static const char* kDeadlockedString = "AudioFlinger may be deadlocked\n";
62static const char* kHardwareLockedString = "Hardware lock is taken\n";
63
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -080064//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070065static const unsigned long kBufferRecoveryInUsecs = 2000;
66static const unsigned long kMaxBufferRecoveryInUsecs = 20000;
67static const float MAX_GAIN = 4096.0f;
68
69// retry counts for buffer fill timeout
70// 50 * ~20msecs = 1 second
71static const int8_t kMaxTrackRetries = 50;
72static const int8_t kMaxTrackStartupRetries = 50;
73
The Android Open Source Project22f8def2009-03-09 11:52:12 -070074static const int kDumpLockRetries = 50;
75static const int kDumpLockSleep = 20000;
76
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -070078#define AUDIOFLINGER_SECURITY_ENABLED 1
79
80// ----------------------------------------------------------------------------
81
82static bool recordingAllowed() {
83#ifndef HAVE_ANDROID_OS
84 return true;
85#endif
86#if AUDIOFLINGER_SECURITY_ENABLED
87 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
88 bool ok = checkCallingPermission(String16("android.permission.RECORD_AUDIO"));
89 if (!ok) LOGE("Request requires android.permission.RECORD_AUDIO");
90 return ok;
91#else
92 if (!checkCallingPermission(String16("android.permission.RECORD_AUDIO")))
93 LOGW("WARNING: Need to add android.permission.RECORD_AUDIO to manifest");
94 return true;
95#endif
96}
97
98static bool settingsAllowed() {
99#ifndef HAVE_ANDROID_OS
100 return true;
101#endif
102#if AUDIOFLINGER_SECURITY_ENABLED
103 if (getpid() == IPCThreadState::self()->getCallingPid()) return true;
104 bool ok = checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS"));
105 if (!ok) LOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
106 return ok;
107#else
108 if (!checkCallingPermission(String16("android.permission.MODIFY_AUDIO_SETTINGS")))
109 LOGW("WARNING: Need to add android.permission.MODIFY_AUDIO_SETTINGS to manifest");
110 return true;
111#endif
112}
113
114// ----------------------------------------------------------------------------
115
116AudioFlinger::AudioFlinger()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800117 : BnAudioFlinger(),
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700118 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700119{
120 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700121
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700122 mAudioHardware = AudioHardwareInterface::create();
Eric Laurent9d91ad52009-07-17 12:17:14 -0700123
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700124 mHardwareStatus = AUDIO_HW_INIT;
125 if (mAudioHardware->initCheck() == NO_ERROR) {
126 // open 16-bit output stream for s/w mixer
Eric Laurent9d91ad52009-07-17 12:17:14 -0700127
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 setMode(AudioSystem::MODE_NORMAL);
129
130 setMasterVolume(1.0f);
131 setMasterMute(false);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700132 } else {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700133 LOGE("Couldn't even initialize the stubbed audio hardware!");
134 }
135}
136
137AudioFlinger::~AudioFlinger()
138{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700139 mRecordThreads.clear();
140 mPlaybackThreads.clear();
The Android Open Source Project27629322009-01-09 17:51:23 -0800141}
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800142
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700143
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700144
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700145status_t AudioFlinger::dumpClients(int fd, const Vector<String16>& args)
146{
147 const size_t SIZE = 256;
148 char buffer[SIZE];
149 String8 result;
150
151 result.append("Clients:\n");
152 for (size_t i = 0; i < mClients.size(); ++i) {
153 wp<Client> wClient = mClients.valueAt(i);
154 if (wClient != 0) {
155 sp<Client> client = wClient.promote();
156 if (client != 0) {
157 snprintf(buffer, SIZE, " pid: %d\n", client->pid());
158 result.append(buffer);
159 }
160 }
161 }
162 write(fd, result.string(), result.size());
163 return NO_ERROR;
164}
165
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700166
167status_t AudioFlinger::dumpInternals(int fd, const Vector<String16>& args)
168{
169 const size_t SIZE = 256;
170 char buffer[SIZE];
171 String8 result;
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700172 int hardwareStatus = mHardwareStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700173
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700174 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700175 result.append(buffer);
176 write(fd, result.string(), result.size());
177 return NO_ERROR;
178}
179
180status_t AudioFlinger::dumpPermissionDenial(int fd, const Vector<String16>& args)
181{
182 const size_t SIZE = 256;
183 char buffer[SIZE];
184 String8 result;
185 snprintf(buffer, SIZE, "Permission Denial: "
186 "can't dump AudioFlinger from pid=%d, uid=%d\n",
187 IPCThreadState::self()->getCallingPid(),
188 IPCThreadState::self()->getCallingUid());
189 result.append(buffer);
190 write(fd, result.string(), result.size());
191 return NO_ERROR;
192}
193
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700194static bool tryLock(Mutex& mutex)
195{
196 bool locked = false;
197 for (int i = 0; i < kDumpLockRetries; ++i) {
198 if (mutex.tryLock() == NO_ERROR) {
199 locked = true;
200 break;
201 }
202 usleep(kDumpLockSleep);
203 }
204 return locked;
205}
206
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700207status_t AudioFlinger::dump(int fd, const Vector<String16>& args)
208{
209 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
210 dumpPermissionDenial(fd, args);
211 } else {
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700212 // get state of hardware lock
213 bool hardwareLocked = tryLock(mHardwareLock);
214 if (!hardwareLocked) {
215 String8 result(kHardwareLockedString);
216 write(fd, result.string(), result.size());
217 } else {
218 mHardwareLock.unlock();
219 }
220
221 bool locked = tryLock(mLock);
222
223 // failed to lock - AudioFlinger is probably deadlocked
224 if (!locked) {
225 String8 result(kDeadlockedString);
226 write(fd, result.string(), result.size());
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700227 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700228
229 dumpClients(fd, args);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700230 dumpInternals(fd, args);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231
Eric Laurent9d91ad52009-07-17 12:17:14 -0700232 // dump playback threads
233 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700234 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700235 }
236
237 // dump record threads
Eric Laurentfd558a92009-07-23 13:35:01 -0700238 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700239 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700240 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800241
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700242 if (mAudioHardware) {
243 mAudioHardware->dumpState(fd, args);
244 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700245 if (locked) mLock.unlock();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700246 }
247 return NO_ERROR;
248}
249
Eric Laurent9d91ad52009-07-17 12:17:14 -0700250
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700251// IAudioFlinger interface
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252
253
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700254sp<IAudioTrack> AudioFlinger::createTrack(
255 pid_t pid,
256 int streamType,
257 uint32_t sampleRate,
258 int format,
259 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800260 int frameCount,
261 uint32_t flags,
262 const sp<IMemory>& sharedBuffer,
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700263 int output,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800264 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700265{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700266 sp<PlaybackThread::Track> track;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700267 sp<TrackHandle> trackHandle;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700268 sp<Client> client;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800269 wp<Client> wclient;
270 status_t lStatus;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700271
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800273 LOGE("invalid stream type");
274 lStatus = BAD_VALUE;
275 goto Exit;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700276 }
277
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800278 {
279 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700280 PlaybackThread *thread = checkPlaybackThread_l(output);
281 if (thread == NULL) {
282 LOGE("unknown output thread");
283 lStatus = BAD_VALUE;
284 goto Exit;
285 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800286
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800287 wclient = mClients.valueFor(pid);
288
289 if (wclient != NULL) {
290 client = wclient.promote();
291 } else {
292 client = new Client(this, pid);
293 mClients.add(pid, client);
294 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700295 track = thread->createTrack_l(client, streamType, sampleRate, format,
296 channelCount, frameCount, sharedBuffer, &lStatus);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700297 }
298 if (lStatus == NO_ERROR) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800299 trackHandle = new TrackHandle(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700300 } else {
301 track.clear();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800302 }
303
304Exit:
305 if(status) {
306 *status = lStatus;
307 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700308 return trackHandle;
309}
310
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700311uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700312{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700313 Mutex::Autolock _l(mLock);
314 PlaybackThread *thread = checkPlaybackThread_l(output);
315 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700316 LOGW("sampleRate() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700317 return 0;
318 }
319 return thread->sampleRate();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700320}
321
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700322int AudioFlinger::channelCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700323{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700324 Mutex::Autolock _l(mLock);
325 PlaybackThread *thread = checkPlaybackThread_l(output);
326 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700327 LOGW("channelCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700328 return 0;
329 }
330 return thread->channelCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700331}
332
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700333int AudioFlinger::format(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700334{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700335 Mutex::Autolock _l(mLock);
336 PlaybackThread *thread = checkPlaybackThread_l(output);
337 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700338 LOGW("format() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700339 return 0;
340 }
341 return thread->format();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700342}
343
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700344size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700345{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700346 Mutex::Autolock _l(mLock);
347 PlaybackThread *thread = checkPlaybackThread_l(output);
348 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700349 LOGW("frameCount() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700350 return 0;
351 }
352 return thread->frameCount();
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700353}
354
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700355uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800356{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700357 Mutex::Autolock _l(mLock);
358 PlaybackThread *thread = checkPlaybackThread_l(output);
359 if (thread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700360 LOGW("latency() unknown thread %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700361 return 0;
362 }
363 return thread->latency();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800364}
365
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700366status_t AudioFlinger::setMasterVolume(float value)
367{
368 // check calling permissions
369 if (!settingsAllowed()) {
370 return PERMISSION_DENIED;
371 }
372
373 // when hw supports master volume, don't scale in sw mixer
374 AutoMutex lock(mHardwareLock);
375 mHardwareStatus = AUDIO_HW_SET_MASTER_VOLUME;
376 if (mAudioHardware->setMasterVolume(value) == NO_ERROR) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377 value = 1.0f;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700378 }
379 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700380
381 mMasterVolume = value;
382 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700383 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700384
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700385 return NO_ERROR;
386}
387
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700388status_t AudioFlinger::setMode(int mode)
389{
390 // check calling permissions
391 if (!settingsAllowed()) {
392 return PERMISSION_DENIED;
393 }
394 if ((mode < 0) || (mode >= AudioSystem::NUM_MODES)) {
395 LOGW("Illegal value: setMode(%d)", mode);
396 return BAD_VALUE;
397 }
398
399 AutoMutex lock(mHardwareLock);
400 mHardwareStatus = AUDIO_HW_SET_MODE;
401 status_t ret = mAudioHardware->setMode(mode);
402 mHardwareStatus = AUDIO_HW_IDLE;
403 return ret;
404}
405
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700406status_t AudioFlinger::setMicMute(bool state)
407{
408 // check calling permissions
409 if (!settingsAllowed()) {
410 return PERMISSION_DENIED;
411 }
412
413 AutoMutex lock(mHardwareLock);
414 mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
415 status_t ret = mAudioHardware->setMicMute(state);
416 mHardwareStatus = AUDIO_HW_IDLE;
417 return ret;
418}
419
420bool AudioFlinger::getMicMute() const
421{
422 bool state = AudioSystem::MODE_INVALID;
423 mHardwareStatus = AUDIO_HW_GET_MIC_MUTE;
424 mAudioHardware->getMicMute(&state);
425 mHardwareStatus = AUDIO_HW_IDLE;
426 return state;
427}
428
429status_t AudioFlinger::setMasterMute(bool muted)
430{
431 // check calling permissions
432 if (!settingsAllowed()) {
433 return PERMISSION_DENIED;
434 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700435
436 mMasterMute = muted;
437 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700438 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700439
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700440 return NO_ERROR;
441}
442
443float AudioFlinger::masterVolume() const
444{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700445 return mMasterVolume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700446}
447
448bool AudioFlinger::masterMute() const
449{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700450 return mMasterMute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700451}
452
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700453status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700454{
455 // check calling permissions
456 if (!settingsAllowed()) {
457 return PERMISSION_DENIED;
458 }
459
Eric Laurent9d91ad52009-07-17 12:17:14 -0700460 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700461 return BAD_VALUE;
462 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -0800463
Eric Laurent9d91ad52009-07-17 12:17:14 -0700464 AutoMutex lock(mLock);
465 PlaybackThread *thread = NULL;
466 if (output) {
467 thread = checkPlaybackThread_l(output);
468 if (thread == NULL) {
469 return BAD_VALUE;
470 }
471 }
472
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700473 status_t ret = NO_ERROR;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700474
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800475 if (stream == AudioSystem::VOICE_CALL ||
476 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700477 float hwValue;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800478 if (stream == AudioSystem::VOICE_CALL) {
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700479 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurent4dd495b2009-04-21 07:56:33 -0700480 // offset value to reflect actual hardware volume that never reaches 0
481 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
482 value = 0.01 + 0.99 * value;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800483 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700484 hwValue = 1.0f;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800485 }
486
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700487 AutoMutex lock(mHardwareLock);
488 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700489 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700490 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800491
Eric Laurent9d91ad52009-07-17 12:17:14 -0700492 }
493
494 mStreamTypes[stream].volume = value;
495
496 if (thread == NULL) {
497 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700498 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700499
500 } else {
501 thread->setStreamVolume(stream, value);
502 }
Eric Laurent4dd495b2009-04-21 07:56:33 -0700503
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700504 return ret;
505}
506
507status_t AudioFlinger::setStreamMute(int stream, bool muted)
508{
509 // check calling permissions
510 if (!settingsAllowed()) {
511 return PERMISSION_DENIED;
512 }
513
Eric Laurent9d91ad52009-07-17 12:17:14 -0700514 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurentb1596ee2009-03-26 01:57:59 -0700515 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700516 return BAD_VALUE;
517 }
The Android Open Source Project4f68be12009-03-18 17:39:46 -0700518
Eric Laurent9d91ad52009-07-17 12:17:14 -0700519 mStreamTypes[stream].mute = muted;
520 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700521 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800522
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700523 return NO_ERROR;
524}
525
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700526float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700527{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700528 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700529 return 0.0f;
530 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700531
532 AutoMutex lock(mLock);
533 float volume;
534 if (output) {
535 PlaybackThread *thread = checkPlaybackThread_l(output);
536 if (thread == NULL) {
537 return 0.0f;
538 }
539 volume = thread->streamVolume(stream);
540 } else {
541 volume = mStreamTypes[stream].volume;
542 }
543
Eric Laurent4dd495b2009-04-21 07:56:33 -0700544 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru732ca392009-03-18 11:33:14 -0700545 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurent4dd495b2009-04-21 07:56:33 -0700546 volume = (volume - 0.01) / 0.99 ;
James E. Blair6015dfc2009-01-17 13:30:20 -0800547 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700548
Eric Laurent4dd495b2009-04-21 07:56:33 -0700549 return volume;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700550}
551
552bool AudioFlinger::streamMute(int stream) const
553{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700554 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700555 return true;
556 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700557
558 return mStreamTypes[stream].mute;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700559}
560
561bool AudioFlinger::isMusicActive() const
562{
Eric Laurentb025ca02009-07-09 03:20:57 -0700563 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700564 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700565 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700566 return true;
567 }
568 }
569 return false;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700570}
571
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700572status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700573{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700574 status_t result;
575
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700576 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700577 ioHandle, keyValuePairs.string(), gettid(), IPCThreadState::self()->getCallingPid());
578 // check calling permissions
579 if (!settingsAllowed()) {
580 return PERMISSION_DENIED;
The Android Open Source Project8a7a6752009-01-15 16:12:10 -0800581 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700582
583 // ioHandle == 0 means the parameters are global to the audio hardware interface
584 if (ioHandle == 0) {
585 AutoMutex lock(mHardwareLock);
586 mHardwareStatus = AUDIO_SET_PARAMETER;
587 result = mAudioHardware->setParameters(keyValuePairs);
588 mHardwareStatus = AUDIO_HW_IDLE;
589 return result;
590 }
591
592 // Check if parameters are for an output
593 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
594 if (playbackThread != NULL) {
595 return playbackThread->setParameters(keyValuePairs);
596 }
597
598 // Check if parameters are for an input
599 RecordThread *recordThread = checkRecordThread_l(ioHandle);
600 if (recordThread != NULL) {
601 return recordThread->setParameters(keyValuePairs);
602 }
603
604 return BAD_VALUE;
605}
606
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700607String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurent9d91ad52009-07-17 12:17:14 -0700608{
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700609// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurent9d91ad52009-07-17 12:17:14 -0700610// ioHandle, keys.string(), gettid(), IPCThreadState::self()->getCallingPid());
611
612 if (ioHandle == 0) {
613 return mAudioHardware->getParameters(keys);
614 }
615 PlaybackThread *playbackThread = checkPlaybackThread_l(ioHandle);
616 if (playbackThread != NULL) {
617 return playbackThread->getParameters(keys);
618 }
619 RecordThread *recordThread = checkRecordThread_l(ioHandle);
620 if (recordThread != NULL) {
621 return recordThread->getParameters(keys);
622 }
623 return String8("");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700624}
625
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800626size_t AudioFlinger::getInputBufferSize(uint32_t sampleRate, int format, int channelCount)
627{
628 return mAudioHardware->getInputBufferSize(sampleRate, format, channelCount);
629}
630
631void AudioFlinger::registerClient(const sp<IAudioFlingerClient>& client)
632{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700633
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800634 LOGV("registerClient() %p, tid %d, calling tid %d", client.get(), gettid(), IPCThreadState::self()->getCallingPid());
635 Mutex::Autolock _l(mLock);
636
637 sp<IBinder> binder = client->asBinder();
638 if (mNotificationClients.indexOf(binder) < 0) {
639 LOGV("Adding notification client %p", binder.get());
640 binder->linkToDeath(this);
641 mNotificationClients.add(binder);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700642 }
643
644 // the config change is always sent from playback or record threads to avoid deadlock
645 // with AudioSystem::gLock
646 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700647 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurent9d91ad52009-07-17 12:17:14 -0700648 }
649
650 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700651 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800652 }
653}
654
655void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700656
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657 LOGV("binderDied() %p, tid %d, calling tid %d", who.unsafe_get(), gettid(), IPCThreadState::self()->getCallingPid());
658 Mutex::Autolock _l(mLock);
659
660 IBinder *binder = who.unsafe_get();
661
662 if (binder != NULL) {
663 int index = mNotificationClients.indexOf(binder);
664 if (index >= 0) {
665 LOGV("Removing notification client %p", binder);
666 mNotificationClients.removeAt(index);
667 }
668 }
669}
670
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700671void AudioFlinger::audioConfigChanged(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurent9d91ad52009-07-17 12:17:14 -0700672 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -0700673 int ioHandle = 0;
674
675 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
676 if (mPlaybackThreads.valueAt(i) == thread) {
677 ioHandle = mPlaybackThreads.keyAt(i);
678 break;
679 }
680 }
681 if (ioHandle == 0) {
682 for (size_t i = 0; i < mRecordThreads.size(); i++) {
683 if (mRecordThreads.valueAt(i) == thread) {
684 ioHandle = mRecordThreads.keyAt(i);
685 break;
686 }
687 }
688 }
689
690 if (ioHandle != 0) {
691 size_t size = mNotificationClients.size();
692 for (size_t i = 0; i < size; i++) {
693 sp<IBinder> binder = mNotificationClients.itemAt(i);
694 LOGV("audioConfigChanged() Notifying change to client %p", binder.get());
695 sp<IAudioFlingerClient> client = interface_cast<IAudioFlingerClient> (binder);
696 client->ioConfigChanged(event, ioHandle, param2);
697 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700698 }
699}
700
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700701void AudioFlinger::removeClient(pid_t pid)
702{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800703 LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700704 Mutex::Autolock _l(mLock);
705 mClients.removeItem(pid);
706}
707
Eric Laurent9d91ad52009-07-17 12:17:14 -0700708// ----------------------------------------------------------------------------
709
710AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger)
711 : Thread(false),
712 mAudioFlinger(audioFlinger), mSampleRate(0), mFrameCount(0), mChannelCount(0),
713 mFormat(0), mFrameSize(1), mNewParameters(String8("")), mStandby(false)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -0700714{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800715}
716
Eric Laurent9d91ad52009-07-17 12:17:14 -0700717AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800718{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800719}
720
Eric Laurent9d91ad52009-07-17 12:17:14 -0700721void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700722{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700723 // keep a strong ref on ourself so that we want get
724 // destroyed in the middle of requestExitAndWait()
725 sp <ThreadBase> strongMe = this;
726
727 LOGV("ThreadBase::exit");
728 {
729 AutoMutex lock(&mLock);
730 requestExit();
731 mWaitWorkCV.signal();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700732 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700733 requestExitAndWait();
The Android Open Source Projectbcef13b2009-03-11 12:11:56 -0700734}
Eric Laurent9d91ad52009-07-17 12:17:14 -0700735
736uint32_t AudioFlinger::ThreadBase::sampleRate() const
737{
738 return mSampleRate;
739}
740
741int AudioFlinger::ThreadBase::channelCount() const
742{
743 return mChannelCount;
744}
745
746int AudioFlinger::ThreadBase::format() const
747{
748 return mFormat;
749}
750
751size_t AudioFlinger::ThreadBase::frameCount() const
752{
753 return mFrameCount;
754}
755
756status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
757{
758 status_t result;
759
760 Mutex::Autolock _l(mLock);
761 mNewParameters = keyValuePairs;
762
763 mWaitWorkCV.signal();
764 mParamCond.wait(mLock);
765
766 return mParamStatus;
767}
768
769void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
770{
771 Mutex::Autolock _l(mLock);
772 ConfigEvent *configEvent = new ConfigEvent();
773 configEvent->mEvent = event;
774 configEvent->mParam = param;
775 mConfigEvents.add(configEvent);
776 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
777 mWaitWorkCV.signal();
778}
779
780void AudioFlinger::ThreadBase::processConfigEvents()
781{
782 mLock.lock();
783 while(!mConfigEvents.isEmpty()) {
784 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
785 ConfigEvent *configEvent = mConfigEvents[0];
786 mConfigEvents.removeAt(0);
787 // release mLock because audioConfigChanged() will call
788 // Audioflinger::audioConfigChanged() which locks AudioFlinger mLock thus creating
789 // potential cross deadlock between AudioFlinger::mLock and mLock
790 mLock.unlock();
791 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
792 delete configEvent;
793 mLock.lock();
794 }
795 mLock.unlock();
796}
797
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800798
799// ----------------------------------------------------------------------------
800
Eric Laurent9d91ad52009-07-17 12:17:14 -0700801AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
802 : ThreadBase(audioFlinger),
Eric Laurent9395d9b2009-07-23 13:17:39 -0700803 mMixBuffer(0), mSuspended(false), mBytesWritten(0), mOutput(output),
804 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805{
Eric Laurent9d91ad52009-07-17 12:17:14 -0700806 readOutputParameters();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800807
Eric Laurent9d91ad52009-07-17 12:17:14 -0700808 mMasterVolume = mAudioFlinger->masterVolume();
809 mMasterMute = mAudioFlinger->masterMute();
810
811 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
812 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
813 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800814 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700815 // notify client processes that a new input has been opened
816 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800817}
818
Eric Laurent9d91ad52009-07-17 12:17:14 -0700819AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800820{
821 delete [] mMixBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700822 if (mType != DUPLICATING) {
823 mAudioFlinger->mAudioHardware->closeOutputStream(mOutput);
824 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800825}
826
Eric Laurent9d91ad52009-07-17 12:17:14 -0700827status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800828{
829 dumpInternals(fd, args);
830 dumpTracks(fd, args);
831 return NO_ERROR;
832}
833
Eric Laurent9d91ad52009-07-17 12:17:14 -0700834status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800835{
836 const size_t SIZE = 256;
837 char buffer[SIZE];
838 String8 result;
839
Eric Laurent9d91ad52009-07-17 12:17:14 -0700840 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800841 result.append(buffer);
842 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
843 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700844 sp<Track> track = mTracks[i];
845 if (track != 0) {
846 track->dump(buffer, SIZE);
847 result.append(buffer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800848 }
849 }
850
Eric Laurent9d91ad52009-07-17 12:17:14 -0700851 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800852 result.append(buffer);
853 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
854 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentc828f6a2009-03-31 14:34:35 -0700855 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800856 if (wTrack != 0) {
857 sp<Track> track = wTrack.promote();
858 if (track != 0) {
859 track->dump(buffer, SIZE);
860 result.append(buffer);
861 }
862 }
863 }
864 write(fd, result.string(), result.size());
865 return NO_ERROR;
866}
867
Eric Laurent9d91ad52009-07-17 12:17:14 -0700868status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800869{
870 const size_t SIZE = 256;
871 char buffer[SIZE];
872 String8 result;
873
Eric Laurent9d91ad52009-07-17 12:17:14 -0700874 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800875 result.append(buffer);
876 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
877 result.append(buffer);
878 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
879 result.append(buffer);
880 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
881 result.append(buffer);
882 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
883 result.append(buffer);
884 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
885 result.append(buffer);
886 write(fd, result.string(), result.size());
887 return NO_ERROR;
888}
889
890// Thread virtuals
Eric Laurent9d91ad52009-07-17 12:17:14 -0700891status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800892{
893 if (mSampleRate == 0) {
894 LOGE("No working audio driver found.");
895 return NO_INIT;
896 }
Eric Laurent9d91ad52009-07-17 12:17:14 -0700897 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800898 return NO_ERROR;
899}
900
Eric Laurent9d91ad52009-07-17 12:17:14 -0700901void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800902{
903 const size_t SIZE = 256;
904 char buffer[SIZE];
905
Eric Laurent9d91ad52009-07-17 12:17:14 -0700906 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800907
908 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
909}
910
Eric Laurent9d91ad52009-07-17 12:17:14 -0700911// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
912sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800913 const sp<AudioFlinger::Client>& client,
914 int streamType,
915 uint32_t sampleRate,
916 int format,
917 int channelCount,
918 int frameCount,
919 const sp<IMemory>& sharedBuffer,
920 status_t *status)
921{
922 sp<Track> track;
923 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -0700924
925 if (mType == DIRECT) {
926 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
927 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
928 sampleRate, format, channelCount, mOutput);
929 lStatus = BAD_VALUE;
930 goto Exit;
931 }
932 } else {
933 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
934 if (sampleRate > mSampleRate*2) {
935 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
936 lStatus = BAD_VALUE;
937 goto Exit;
938 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800939 }
940
Eric Laurent9d91ad52009-07-17 12:17:14 -0700941 if (mOutput == 0) {
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700942 LOGE("Audio driver not initialized.");
943 lStatus = NO_INIT;
944 goto Exit;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800945 }
946
Eric Laurent9d91ad52009-07-17 12:17:14 -0700947 { // scope for mLock
948 Mutex::Autolock _l(mLock);
949 track = new Track(this, client, streamType, sampleRate, format,
950 channelCount, frameCount, sharedBuffer);
951 if (track->getCblk() == NULL) {
952 lStatus = NO_MEMORY;
953 goto Exit;
954 }
955 mTracks.add(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700956 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -0700957 lStatus = NO_ERROR;
958
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800959Exit:
960 if(status) {
961 *status = lStatus;
962 }
963 return track;
964}
965
Eric Laurent9d91ad52009-07-17 12:17:14 -0700966uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800967{
968 if (mOutput) {
969 return mOutput->latency();
970 }
971 else {
972 return 0;
973 }
974}
975
Eric Laurent9d91ad52009-07-17 12:17:14 -0700976status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800977{
978 mMasterVolume = value;
979 return NO_ERROR;
980}
981
Eric Laurent9d91ad52009-07-17 12:17:14 -0700982status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800983{
984 mMasterMute = muted;
985 return NO_ERROR;
986}
987
Eric Laurent9d91ad52009-07-17 12:17:14 -0700988float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800989{
990 return mMasterVolume;
991}
992
Eric Laurent9d91ad52009-07-17 12:17:14 -0700993bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800994{
995 return mMasterMute;
996}
997
Eric Laurent9d91ad52009-07-17 12:17:14 -0700998status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800999{
1000 mStreamTypes[stream].volume = value;
1001 return NO_ERROR;
1002}
1003
Eric Laurent9d91ad52009-07-17 12:17:14 -07001004status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001005{
1006 mStreamTypes[stream].mute = muted;
1007 return NO_ERROR;
1008}
1009
Eric Laurent9d91ad52009-07-17 12:17:14 -07001010float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001011{
1012 return mStreamTypes[stream].volume;
1013}
1014
Eric Laurent9d91ad52009-07-17 12:17:14 -07001015bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001016{
1017 return mStreamTypes[stream].mute;
1018}
1019
Eric Laurent9d91ad52009-07-17 12:17:14 -07001020bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001021{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001022 Mutex::Autolock _l(mLock);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001023 size_t count = mActiveTracks.size();
1024 for (size_t i = 0 ; i < count ; ++i) {
1025 sp<Track> t = mActiveTracks[i].promote();
1026 if (t == 0) continue;
1027 Track* const track = t.get();
Eric Laurent9395d9b2009-07-23 13:17:39 -07001028 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001029 return true;
1030 }
1031 return false;
1032}
1033
Eric Laurent9d91ad52009-07-17 12:17:14 -07001034// addTrack_l() must be called with ThreadBase::mLock held
1035status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036{
1037 status_t status = ALREADY_EXISTS;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001038
1039 // here the track could be either new, or restarted
1040 // in both cases "unstop" the track
1041 if (track->isPaused()) {
1042 track->mState = TrackBase::RESUMING;
1043 LOGV("PAUSED => RESUMING (%d)", track->name());
1044 } else {
1045 track->mState = TrackBase::ACTIVE;
1046 LOGV("? => ACTIVE (%d)", track->name());
1047 }
1048 // set retry count for buffer fill
1049 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001050 if (mActiveTracks.indexOf(track) < 0) {
1051 // the track is newly added, make sure it fills up all its
1052 // buffers before playing. This is to ensure the client will
1053 // effectively get the latency it requested.
1054 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001055 track->mResetDone = false;
Eric Laurent9d91ad52009-07-17 12:17:14 -07001056 mActiveTracks.add(track);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001057 status = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001058 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07001059
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001060 LOGV("mWaitWorkCV.broadcast");
Eric Laurent9d91ad52009-07-17 12:17:14 -07001061 mWaitWorkCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062
1063 return status;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001064}
1065
Eric Laurent9d91ad52009-07-17 12:17:14 -07001066// destroyTrack_l() must be called with ThreadBase::mLock held
1067void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001068{
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001069 track->mState = TrackBase::TERMINATED;
1070 if (mActiveTracks.indexOf(track) < 0) {
1071 LOGV("remove track (%d) and delete from mixer", track->name());
1072 mTracks.remove(track);
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001073 deleteTrackName_l(track->name());
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001074 }
1075}
1076
Eric Laurent9d91ad52009-07-17 12:17:14 -07001077String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001078{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001079 return mOutput->getParameters(keys);
1080}
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001081
Eric Laurent9d91ad52009-07-17 12:17:14 -07001082void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1083 AudioSystem::OutputDescriptor desc;
1084 void *param2 = 0;
1085
1086 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1087
1088 switch (event) {
1089 case AudioSystem::OUTPUT_OPENED:
1090 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1091 desc.channels = mChannelCount;
1092 desc.samplingRate = mSampleRate;
1093 desc.format = mFormat;
1094 desc.frameCount = mFrameCount;
1095 desc.latency = latency();
1096 param2 = &desc;
1097 break;
1098
1099 case AudioSystem::STREAM_CONFIG_CHANGED:
1100 param2 = &param;
1101 case AudioSystem::OUTPUT_CLOSED:
1102 default:
1103 break;
1104 }
1105 mAudioFlinger->audioConfigChanged(event, this, param2);
1106}
1107
1108void AudioFlinger::PlaybackThread::readOutputParameters()
1109{
1110 mSampleRate = mOutput->sampleRate();
1111 mChannelCount = AudioSystem::popCount(mOutput->channels());
1112
1113 mFormat = mOutput->format();
1114 mFrameSize = mOutput->frameSize();
1115 mFrameCount = mOutput->bufferSize() / mFrameSize;
1116
1117 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1118 // FIXME - Current mixer implementation only supports stereo output: Always
1119 // Allocate a stereo buffer even if HW output is mono.
1120 if (mMixBuffer != NULL) delete mMixBuffer;
1121 mMixBuffer = new int16_t[mFrameCount * 2];
1122 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1123}
1124
1125// ----------------------------------------------------------------------------
1126
1127AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1128 : PlaybackThread(audioFlinger, output),
1129 mAudioMixer(0)
1130{
1131 mType = PlaybackThread::MIXER;
1132 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1133
1134 // FIXME - Current mixer implementation only supports stereo output
1135 if (mChannelCount == 1) {
1136 LOGE("Invalid audio hardware channel count");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001137 }
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001138}
1139
Eric Laurent9d91ad52009-07-17 12:17:14 -07001140AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001141{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001142 delete mAudioMixer;
1143}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001144
Eric Laurent9d91ad52009-07-17 12:17:14 -07001145bool AudioFlinger::MixerThread::threadLoop()
1146{
1147 unsigned long sleepTime = kBufferRecoveryInUsecs;
1148 int16_t* curBuf = mMixBuffer;
1149 Vector< sp<Track> > tracksToRemove;
1150 size_t enabledTracks = 0;
1151 nsecs_t standbyTime = systemTime();
1152 size_t mixBufferSize = mFrameCount * mFrameSize;
1153 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001154
Eric Laurent9d91ad52009-07-17 12:17:14 -07001155 while (!exitPending())
1156 {
1157 processConfigEvents();
1158
1159 enabledTracks = 0;
1160 { // scope for mLock
1161
1162 Mutex::Autolock _l(mLock);
1163
1164 if (checkForNewParameters_l()) {
1165 mixBufferSize = mFrameCount * mFrameSize;
1166 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1167 }
1168
1169 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1170
1171 // put audio hardware into standby after short delay
1172 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1173 mSuspended) {
1174 if (!mStandby) {
1175 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1176 mOutput->standby();
1177 mStandby = true;
1178 mBytesWritten = 0;
1179 }
1180
1181 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1182 // we're about to wait, flush the binder command buffer
1183 IPCThreadState::self()->flushCommands();
1184
1185 if (exitPending()) break;
1186
1187 // wait until we have something to do...
1188 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1189 mWaitWorkCV.wait(mLock);
1190 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1191
1192 if (mMasterMute == false) {
1193 char value[PROPERTY_VALUE_MAX];
1194 property_get("ro.audio.silent", value, "0");
1195 if (atoi(value)) {
1196 LOGD("Silence is golden");
1197 setMasterMute(true);
1198 }
1199 }
1200
1201 standbyTime = systemTime() + kStandbyTimeInNsecs;
1202 continue;
1203 }
1204 }
1205
1206 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1207 }
1208
1209 if (LIKELY(enabledTracks)) {
1210 // mix buffers...
1211 mAudioMixer->process(curBuf);
1212
1213 // output audio to hardware
1214 if (mSuspended) {
1215 usleep(kMaxBufferRecoveryInUsecs);
1216 } else {
1217 mLastWriteTime = systemTime();
1218 mInWrite = true;
1219 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1220 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1221 mNumWrites++;
1222 mInWrite = false;
1223 mStandby = false;
1224 nsecs_t temp = systemTime();
1225 standbyTime = temp + kStandbyTimeInNsecs;
1226 nsecs_t delta = temp - mLastWriteTime;
1227 if (delta > maxPeriod) {
1228 LOGW("write blocked for %llu msecs", ns2ms(delta));
1229 mNumDelayedWrites++;
1230 }
1231 sleepTime = kBufferRecoveryInUsecs;
1232 }
1233 } else {
1234 // There was nothing to mix this round, which means all
1235 // active tracks were late. Sleep a little bit to give
1236 // them another chance. If we're too late, the audio
1237 // hardware will zero-fill for us.
1238 // LOGV("thread %p no buffers - usleep(%lu)", this, sleepTime);
1239 usleep(sleepTime);
1240 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1241 sleepTime += kBufferRecoveryInUsecs;
1242 }
1243 }
1244
1245 // finally let go of all our tracks, without the lock held
1246 // since we can't guarantee the destructors won't acquire that
1247 // same lock.
1248 tracksToRemove.clear();
1249 }
1250
1251 if (!mStandby) {
1252 mOutput->standby();
1253 }
1254 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1255 processConfigEvents();
1256
1257 LOGV("MixerThread %p exiting", this);
1258 return false;
1259}
1260
1261// prepareTracks_l() must be called with ThreadBase::mLock held
1262size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1263{
1264
1265 size_t enabledTracks = 0;
1266 // find out which tracks need to be processed
1267 size_t count = activeTracks.size();
1268 for (size_t i=0 ; i<count ; i++) {
1269 sp<Track> t = activeTracks[i].promote();
1270 if (t == 0) continue;
1271
1272 Track* const track = t.get();
1273 audio_track_cblk_t* cblk = track->cblk();
1274
1275 // The first time a track is added we wait
1276 // for all its buffers to be filled before processing it
1277 mAudioMixer->setActiveTrack(track->name());
1278 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1279 !track->isPaused())
1280 {
1281 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1282
1283 // compute volume for this track
1284 int16_t left, right;
1285 if (track->isMuted() || mMasterMute || track->isPausing() ||
1286 mStreamTypes[track->type()].mute) {
1287 left = right = 0;
1288 if (track->isPausing()) {
1289 track->setPaused();
1290 }
1291 } else {
1292 float typeVolume = mStreamTypes[track->type()].volume;
1293 float v = mMasterVolume * typeVolume;
1294 float v_clamped = v * cblk->volume[0];
1295 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1296 left = int16_t(v_clamped);
1297 v_clamped = v * cblk->volume[1];
1298 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1299 right = int16_t(v_clamped);
1300 }
1301
1302 // XXX: these things DON'T need to be done each time
1303 mAudioMixer->setBufferProvider(track);
1304 mAudioMixer->enable(AudioMixer::MIXING);
1305
1306 int param;
1307 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1308 // no ramp for the first volume setting
1309 track->mFillingUpStatus = Track::FS_ACTIVE;
1310 if (track->mState == TrackBase::RESUMING) {
1311 track->mState = TrackBase::ACTIVE;
1312 param = AudioMixer::RAMP_VOLUME;
1313 } else {
1314 param = AudioMixer::VOLUME;
1315 }
1316 } else {
1317 param = AudioMixer::RAMP_VOLUME;
1318 }
1319 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1320 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1321 mAudioMixer->setParameter(
1322 AudioMixer::TRACK,
1323 AudioMixer::FORMAT, track->format());
1324 mAudioMixer->setParameter(
1325 AudioMixer::TRACK,
1326 AudioMixer::CHANNEL_COUNT, track->channelCount());
1327 mAudioMixer->setParameter(
1328 AudioMixer::RESAMPLE,
1329 AudioMixer::SAMPLE_RATE,
1330 int(cblk->sampleRate));
1331
1332 // reset retry count
1333 track->mRetryCount = kMaxTrackRetries;
1334 enabledTracks++;
1335 } else {
1336 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1337 if (track->isStopped()) {
1338 track->reset();
1339 }
1340 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1341 // We have consumed all the buffers of this track.
1342 // Remove it from the list of active tracks.
1343 tracksToRemove->add(track);
1344 mAudioMixer->disable(AudioMixer::MIXING);
1345 } else {
1346 // No buffers for this track. Give it a few chances to
1347 // fill a buffer, then remove it from active list.
1348 if (--(track->mRetryCount) <= 0) {
1349 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1350 tracksToRemove->add(track);
1351 }
1352 // For tracks using static shared memry buffer, make sure that we have
1353 // written enough data to audio hardware before disabling the track
1354 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1355 // don't care about code removing track from active list above.
1356 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1357 mAudioMixer->disable(AudioMixer::MIXING);
1358 } else {
1359 enabledTracks++;
1360 }
1361 }
1362 }
1363 }
1364
1365 // remove all the tracks that need to be...
1366 count = tracksToRemove->size();
1367 if (UNLIKELY(count)) {
1368 for (size_t i=0 ; i<count ; i++) {
1369 const sp<Track>& track = tracksToRemove->itemAt(i);
1370 mActiveTracks.remove(track);
1371 if (track->isTerminated()) {
1372 mTracks.remove(track);
1373 deleteTrackName_l(track->mName);
1374 }
1375 }
1376 }
1377
1378 return enabledTracks;
1379}
1380
1381void AudioFlinger::MixerThread::getTracks(
1382 SortedVector < sp<Track> >& tracks,
1383 SortedVector < wp<Track> >& activeTracks,
1384 int streamType)
1385{
1386 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1387 Mutex::Autolock _l(mLock);
1388 size_t size = mTracks.size();
1389 for (size_t i = 0; i < size; i++) {
1390 sp<Track> t = mTracks[i];
1391 if (t->type() == streamType) {
1392 tracks.add(t);
1393 int j = mActiveTracks.indexOf(t);
1394 if (j >= 0) {
1395 t = mActiveTracks[j].promote();
1396 if (t != NULL) {
1397 activeTracks.add(t);
1398 }
1399 }
1400 }
1401 }
1402
1403 size = activeTracks.size();
1404 for (size_t i = 0; i < size; i++) {
1405 mActiveTracks.remove(activeTracks[i]);
1406 }
1407
1408 size = tracks.size();
1409 for (size_t i = 0; i < size; i++) {
1410 sp<Track> t = tracks[i];
1411 mTracks.remove(t);
1412 deleteTrackName_l(t->name());
1413 }
1414}
1415
1416void AudioFlinger::MixerThread::putTracks(
1417 SortedVector < sp<Track> >& tracks,
1418 SortedVector < wp<Track> >& activeTracks)
1419{
1420 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1421 Mutex::Autolock _l(mLock);
1422 size_t size = tracks.size();
1423 for (size_t i = 0; i < size ; i++) {
1424 sp<Track> t = tracks[i];
1425 int name = getTrackName_l();
1426
1427 if (name < 0) return;
1428
1429 t->mName = name;
1430 t->mThread = this;
1431 mTracks.add(t);
1432
1433 int j = activeTracks.indexOf(t);
1434 if (j >= 0) {
1435 mActiveTracks.add(t);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001436 }
1437 }
1438}
1439
Eric Laurent9d91ad52009-07-17 12:17:14 -07001440// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001441int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001442{
1443 return mAudioMixer->getTrackName();
1444}
1445
Eric Laurent9d91ad52009-07-17 12:17:14 -07001446// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001447void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001448{
1449 mAudioMixer->deleteTrackName(name);
1450}
1451
Eric Laurent9d91ad52009-07-17 12:17:14 -07001452// checkForNewParameters_l() must be called with ThreadBase::mLock held
1453bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001454{
Eric Laurent9d91ad52009-07-17 12:17:14 -07001455 bool reconfig = false;
1456
1457 if (mNewParameters != "") {
1458 status_t status = NO_ERROR;
1459 AudioParameter param = AudioParameter(mNewParameters);
1460 int value;
1461 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1462 reconfig = true;
1463 }
1464 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1465 if (value != AudioSystem::PCM_16_BIT) {
1466 status = BAD_VALUE;
1467 } else {
1468 reconfig = true;
1469 }
1470 }
1471 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1472 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1473 status = BAD_VALUE;
1474 } else {
1475 reconfig = true;
1476 }
1477 }
1478 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1479 // do not accept frame count changes if tracks are open as the track buffer
1480 // size depends on frame count and correct behavior would not be garantied
1481 // if frame count is changed after track creation
1482 if (!mTracks.isEmpty()) {
1483 status = INVALID_OPERATION;
1484 } else {
1485 reconfig = true;
1486 }
1487 }
1488 if (status == NO_ERROR) {
1489 status = mOutput->setParameters(mNewParameters);
1490 if (!mStandby && status == INVALID_OPERATION) {
1491 mOutput->standby();
1492 mStandby = true;
1493 mBytesWritten = 0;
1494 status = mOutput->setParameters(mNewParameters);
1495 }
1496 if (status == NO_ERROR && reconfig) {
1497 delete mAudioMixer;
1498 readOutputParameters();
1499 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1500 for (size_t i = 0; i < mTracks.size() ; i++) {
1501 int name = getTrackName_l();
1502 if (name < 0) break;
1503 mTracks[i]->mName = name;
1504 }
1505 sendConfigEvent(AudioSystem::OUTPUT_CONFIG_CHANGED);
1506 }
1507 }
1508 mParamStatus = status;
1509 mNewParameters = "";
1510 mParamCond.signal();
1511 }
1512 return reconfig;
1513}
1514
1515status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1516{
1517 const size_t SIZE = 256;
1518 char buffer[SIZE];
1519 String8 result;
1520
1521 PlaybackThread::dumpInternals(fd, args);
1522
1523 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1524 result.append(buffer);
1525 write(fd, result.string(), result.size());
1526 return NO_ERROR;
1527}
1528
1529// ----------------------------------------------------------------------------
1530AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1531 : PlaybackThread(audioFlinger, output),
1532 mLeftVolume (1.0), mRightVolume(1.0)
1533{
1534 mType = PlaybackThread::DIRECT;
1535}
1536
1537AudioFlinger::DirectOutputThread::~DirectOutputThread()
1538{
1539}
1540
1541
1542bool AudioFlinger::DirectOutputThread::threadLoop()
1543{
1544 unsigned long sleepTime = kBufferRecoveryInUsecs;
1545 sp<Track> trackToRemove;
1546 sp<Track> activeTrack;
1547 nsecs_t standbyTime = systemTime();
1548 int8_t *curBuf;
1549 size_t mixBufferSize = mFrameCount*mFrameSize;
1550
1551 while (!exitPending())
1552 {
1553 processConfigEvents();
1554
1555 { // scope for the mLock
1556
1557 Mutex::Autolock _l(mLock);
1558
1559 if (checkForNewParameters_l()) {
1560 mixBufferSize = mFrameCount*mFrameSize;
1561 }
1562
1563 // put audio hardware into standby after short delay
1564 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1565 mSuspended) {
1566 // wait until we have something to do...
1567 if (!mStandby) {
1568 LOGV("Audio hardware entering standby, mixer %p\n", this);
1569 mOutput->standby();
1570 mStandby = true;
1571 mBytesWritten = 0;
1572 }
1573
1574 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1575 // we're about to wait, flush the binder command buffer
1576 IPCThreadState::self()->flushCommands();
1577
1578 if (exitPending()) break;
1579
1580 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1581 mWaitWorkCV.wait(mLock);
1582 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1583
1584 if (mMasterMute == false) {
1585 char value[PROPERTY_VALUE_MAX];
1586 property_get("ro.audio.silent", value, "0");
1587 if (atoi(value)) {
1588 LOGD("Silence is golden");
1589 setMasterMute(true);
1590 }
1591 }
1592
1593 standbyTime = systemTime() + kStandbyTimeInNsecs;
1594 continue;
1595 }
1596 }
1597
1598 // find out which tracks need to be processed
1599 if (mActiveTracks.size() != 0) {
1600 sp<Track> t = mActiveTracks[0].promote();
1601 if (t == 0) continue;
1602
1603 Track* const track = t.get();
1604 audio_track_cblk_t* cblk = track->cblk();
1605
1606 // The first time a track is added we wait
1607 // for all its buffers to be filled before processing it
1608 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1609 !track->isPaused())
1610 {
1611 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1612
1613 // compute volume for this track
1614 float left, right;
1615 if (track->isMuted() || mMasterMute || track->isPausing() ||
1616 mStreamTypes[track->type()].mute) {
1617 left = right = 0;
1618 if (track->isPausing()) {
1619 track->setPaused();
1620 }
1621 } else {
1622 float typeVolume = mStreamTypes[track->type()].volume;
1623 float v = mMasterVolume * typeVolume;
1624 float v_clamped = v * cblk->volume[0];
1625 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1626 left = v_clamped/MAX_GAIN;
1627 v_clamped = v * cblk->volume[1];
1628 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1629 right = v_clamped/MAX_GAIN;
1630 }
1631
1632 if (left != mLeftVolume || right != mRightVolume) {
1633 mOutput->setVolume(left, right);
1634 left = mLeftVolume;
1635 right = mRightVolume;
1636 }
1637
1638 if (track->mFillingUpStatus == Track::FS_FILLED) {
1639 track->mFillingUpStatus = Track::FS_ACTIVE;
1640 if (track->mState == TrackBase::RESUMING) {
1641 track->mState = TrackBase::ACTIVE;
1642 }
1643 }
1644
1645 // reset retry count
1646 track->mRetryCount = kMaxTrackRetries;
1647 activeTrack = t;
1648 } else {
1649 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1650 if (track->isStopped()) {
1651 track->reset();
1652 }
1653 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1654 // We have consumed all the buffers of this track.
1655 // Remove it from the list of active tracks.
1656 trackToRemove = track;
1657 } else {
1658 // No buffers for this track. Give it a few chances to
1659 // fill a buffer, then remove it from active list.
1660 if (--(track->mRetryCount) <= 0) {
1661 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1662 trackToRemove = track;
1663 }
1664
1665 // For tracks using static shared memry buffer, make sure that we have
1666 // written enough data to audio hardware before disabling the track
1667 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1668 // don't care about code removing track from active list above.
1669 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1670 activeTrack = t;
1671 }
1672 }
1673 }
1674 }
1675
1676 // remove all the tracks that need to be...
1677 if (UNLIKELY(trackToRemove != 0)) {
1678 mActiveTracks.remove(trackToRemove);
1679 if (trackToRemove->isTerminated()) {
1680 mTracks.remove(trackToRemove);
1681 deleteTrackName_l(trackToRemove->mName);
1682 }
1683 }
1684 }
1685
1686 if (activeTrack != 0) {
1687 AudioBufferProvider::Buffer buffer;
1688 size_t frameCount = mFrameCount;
1689 curBuf = (int8_t *)mMixBuffer;
1690 // output audio to hardware
1691 mLastWriteTime = systemTime();
1692 mInWrite = true;
1693 while(frameCount) {
1694 buffer.frameCount = frameCount;
1695 activeTrack->getNextBuffer(&buffer);
1696 if (UNLIKELY(buffer.raw == 0)) {
1697 memset(curBuf, 0, frameCount * mFrameSize);
1698 break;
1699 }
1700 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1701 frameCount -= buffer.frameCount;
1702 curBuf += buffer.frameCount * mFrameSize;
1703 activeTrack->releaseBuffer(&buffer);
1704 }
1705 if (mSuspended) {
1706 usleep(kMaxBufferRecoveryInUsecs);
1707 } else {
1708 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1709 if (bytesWritten) mBytesWritten += bytesWritten;
1710 mNumWrites++;
1711 mInWrite = false;
1712 mStandby = false;
1713 nsecs_t temp = systemTime();
1714 standbyTime = temp + kStandbyTimeInNsecs;
1715 sleepTime = kBufferRecoveryInUsecs;
1716 }
1717 } else {
1718 // There was nothing to mix this round, which means all
1719 // active tracks were late. Sleep a little bit to give
1720 // them another chance. If we're too late, the audio
1721 // hardware will zero-fill for us.
1722 //LOGV("no buffers - usleep(%lu)", sleepTime);
1723 usleep(sleepTime);
1724 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1725 sleepTime += kBufferRecoveryInUsecs;
1726 }
1727 }
1728
1729 // finally let go of removed track, without the lock held
1730 // since we can't guarantee the destructors won't acquire that
1731 // same lock.
1732 trackToRemove.clear();
1733 activeTrack.clear();
1734 }
1735
1736 if (!mStandby) {
1737 mOutput->standby();
1738 }
1739 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1740 processConfigEvents();
1741
1742 LOGV("DirectOutputThread %p exiting", this);
1743 return false;
1744}
1745
1746// getTrackName_l() must be called with ThreadBase::mLock held
1747int AudioFlinger::DirectOutputThread::getTrackName_l()
1748{
1749 return 0;
1750}
1751
1752// deleteTrackName_l() must be called with ThreadBase::mLock held
1753void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1754{
1755}
1756
1757// checkForNewParameters_l() must be called with ThreadBase::mLock held
1758bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1759{
1760 bool reconfig = false;
1761
1762 if (mNewParameters != "") {
1763 status_t status = NO_ERROR;
1764 AudioParameter param = AudioParameter(mNewParameters);
1765 int value;
1766 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1767 // do not accept frame count changes if tracks are open as the track buffer
1768 // size depends on frame count and correct behavior would not be garantied
1769 // if frame count is changed after track creation
1770 if (!mTracks.isEmpty()) {
1771 status = INVALID_OPERATION;
1772 } else {
1773 reconfig = true;
1774 }
1775 }
1776 if (status == NO_ERROR) {
1777 status = mOutput->setParameters(mNewParameters);
1778 if (!mStandby && status == INVALID_OPERATION) {
1779 mOutput->standby();
1780 mStandby = true;
1781 mBytesWritten = 0;
1782 status = mOutput->setParameters(mNewParameters);
1783 }
1784 if (status == NO_ERROR && reconfig) {
1785 readOutputParameters();
1786 sendConfigEvent(AudioSystem::OUTPUT_CONFIG_CHANGED);
1787 }
1788 }
1789 mParamStatus = status;
1790 mNewParameters = "";
1791 mParamCond.signal();
1792 }
1793 return reconfig;
The Android Open Source Projecte41dd752009-01-22 00:13:42 -08001794}
1795
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001796// ----------------------------------------------------------------------------
1797
Eric Laurent9d91ad52009-07-17 12:17:14 -07001798AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1799 : MixerThread(audioFlinger, mainThread->getOutput())
1800{
1801 mType = PlaybackThread::DUPLICATING;
1802 addOutputTrack(mainThread);
1803}
1804
1805AudioFlinger::DuplicatingThread::~DuplicatingThread()
1806{
1807 mOutputTracks.clear();
1808}
1809
1810bool AudioFlinger::DuplicatingThread::threadLoop()
1811{
1812 unsigned long sleepTime = kBufferRecoveryInUsecs;
1813 int16_t* curBuf = mMixBuffer;
1814 Vector< sp<Track> > tracksToRemove;
1815 size_t enabledTracks = 0;
1816 nsecs_t standbyTime = systemTime();
1817 size_t mixBufferSize = mFrameCount*mFrameSize;
1818 SortedVector< sp<OutputTrack> > outputTracks;
1819
1820 while (!exitPending())
1821 {
1822 processConfigEvents();
1823
1824 enabledTracks = 0;
1825 { // scope for the mLock
1826
1827 Mutex::Autolock _l(mLock);
1828
1829 if (checkForNewParameters_l()) {
1830 mixBufferSize = mFrameCount*mFrameSize;
1831 }
1832
1833 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1834
1835 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1836 outputTracks.add(mOutputTracks[i]);
1837 }
1838
1839 // put audio hardware into standby after short delay
1840 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1841 mSuspended) {
1842 if (!mStandby) {
1843 for (size_t i = 0; i < outputTracks.size(); i++) {
1844 mLock.unlock();
1845 outputTracks[i]->stop();
1846 mLock.lock();
1847 }
1848 mStandby = true;
1849 mBytesWritten = 0;
1850 }
1851
1852 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1853 // we're about to wait, flush the binder command buffer
1854 IPCThreadState::self()->flushCommands();
1855 outputTracks.clear();
1856
1857 if (exitPending()) break;
1858
1859 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1860 mWaitWorkCV.wait(mLock);
1861 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1862 if (mMasterMute == false) {
1863 char value[PROPERTY_VALUE_MAX];
1864 property_get("ro.audio.silent", value, "0");
1865 if (atoi(value)) {
1866 LOGD("Silence is golden");
1867 setMasterMute(true);
1868 }
1869 }
1870
1871 standbyTime = systemTime() + kStandbyTimeInNsecs;
1872 sleepTime = kBufferRecoveryInUsecs;
1873 continue;
1874 }
1875 }
1876
1877 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1878 }
1879
1880 bool mustSleep = true;
1881 if (LIKELY(enabledTracks)) {
1882 // mix buffers...
1883 mAudioMixer->process(curBuf);
1884 if (!mSuspended) {
1885 for (size_t i = 0; i < outputTracks.size(); i++) {
1886 outputTracks[i]->write(curBuf, mFrameCount);
1887 }
1888 mStandby = false;
1889 mustSleep = false;
1890 mBytesWritten += mixBufferSize;
1891 }
1892 } else {
1893 // flush remaining overflow buffers in output tracks
1894 for (size_t i = 0; i < outputTracks.size(); i++) {
1895 if (outputTracks[i]->isActive()) {
1896 outputTracks[i]->write(curBuf, 0);
1897 standbyTime = systemTime() + kStandbyTimeInNsecs;
1898 mustSleep = false;
1899 }
1900 }
1901 }
1902 if (mustSleep) {
1903// LOGV("threadLoop() sleeping %d", sleepTime);
1904 usleep(sleepTime);
1905 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1906 sleepTime += kBufferRecoveryInUsecs;
1907 }
1908 } else {
1909 sleepTime = kBufferRecoveryInUsecs;
1910 }
1911
1912 // finally let go of all our tracks, without the lock held
1913 // since we can't guarantee the destructors won't acquire that
1914 // same lock.
1915 tracksToRemove.clear();
1916 outputTracks.clear();
1917 }
1918
1919 if (!mStandby) {
1920 for (size_t i = 0; i < outputTracks.size(); i++) {
1921 mLock.unlock();
1922 outputTracks[i]->stop();
1923 mLock.lock();
1924 }
1925 }
1926
1927 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1928 processConfigEvents();
1929
1930 return false;
1931}
1932
1933void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1934{
1935 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1936 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1937 mSampleRate,
1938 mFormat,
1939 mChannelCount,
1940 frameCount);
1941 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1942 mOutputTracks.add(outputTrack);
1943 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1944}
1945
1946void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1947{
1948 Mutex::Autolock _l(mLock);
1949 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1950 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
1951 mOutputTracks.removeAt(i);
1952 return;
1953 }
1954 }
1955 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1956}
1957
1958
1959// ----------------------------------------------------------------------------
1960
The Android Open Source Project22f8def2009-03-09 11:52:12 -07001961// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07001962AudioFlinger::ThreadBase::TrackBase::TrackBase(
1963 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001964 const sp<Client>& client,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001965 uint32_t sampleRate,
1966 int format,
1967 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001968 int frameCount,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001969 uint32_t flags,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001970 const sp<IMemory>& sharedBuffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001971 : RefBase(),
Eric Laurent9d91ad52009-07-17 12:17:14 -07001972 mThread(thread),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001973 mClient(client),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001974 mFrameCount(0),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001975 mState(IDLE),
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001976 mClientTid(-1),
1977 mFormat(format),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001978 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001979{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001980 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
1981
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07001982 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08001983 size_t size = sizeof(audio_track_cblk_t);
1984 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
1985 if (sharedBuffer == 0) {
1986 size += bufferSize;
1987 }
1988
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001989 if (client != NULL) {
1990 mCblkMemory = client->heap()->allocate(size);
1991 if (mCblkMemory != 0) {
1992 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
1993 if (mCblk) { // construct the shared structure in-place.
1994 new(mCblk) audio_track_cblk_t();
1995 // clear all buffers
1996 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07001997 mCblk->sampleRate = sampleRate;
1998 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001999 if (sharedBuffer == 0) {
2000 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2001 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2002 // Force underrun condition to avoid false underrun callback until first data is
2003 // written to buffer
2004 mCblk->flowControlFlag = 1;
2005 } else {
2006 mBuffer = sharedBuffer->pointer();
2007 }
2008 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002009 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010 } else {
2011 LOGE("not enough memory for AudioTrack size=%u", size);
2012 client->heap()->dump("AudioTrack");
2013 return;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002014 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002015 } else {
2016 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2017 if (mCblk) { // construct the shared structure in-place.
2018 new(mCblk) audio_track_cblk_t();
2019 // clear all buffers
2020 mCblk->frameCount = frameCount;
Eric Laurent0bac5382009-07-07 07:10:45 -07002021 mCblk->sampleRate = sampleRate;
2022 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002023 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2024 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2025 // Force underrun condition to avoid false underrun callback until first data is
2026 // written to buffer
2027 mCblk->flowControlFlag = 1;
2028 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2029 }
2030 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002031}
2032
Eric Laurent9d91ad52009-07-17 12:17:14 -07002033AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002034{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035 if (mCblk) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002036 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2037 if (mClient == NULL) {
2038 delete mCblk;
2039 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002041 mCblkMemory.clear(); // and free the shared memory
2042 mClient.clear();
2043}
2044
Eric Laurent9d91ad52009-07-17 12:17:14 -07002045void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002046{
2047 buffer->raw = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002048 mFrameCount = buffer->frameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002049 step();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002050 buffer->frameCount = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002051}
2052
Eric Laurent9d91ad52009-07-17 12:17:14 -07002053bool AudioFlinger::PlaybackThread::TrackBase::step() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002054 bool result;
2055 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002056
2057 result = cblk->stepServer(mFrameCount);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002058 if (!result) {
2059 LOGV("stepServer failed acquiring cblk mutex");
2060 mFlags |= STEPSERVER_FAILED;
2061 }
2062 return result;
2063}
2064
Eric Laurent9d91ad52009-07-17 12:17:14 -07002065void AudioFlinger::PlaybackThread::TrackBase::reset() {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002066 audio_track_cblk_t* cblk = this->cblk();
2067
2068 cblk->user = 0;
2069 cblk->server = 0;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002070 cblk->userBase = 0;
2071 cblk->serverBase = 0;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002073 LOGV("TrackBase::reset");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002074}
2075
Eric Laurent9d91ad52009-07-17 12:17:14 -07002076sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002077{
2078 return mCblkMemory;
2079}
2080
Eric Laurent9d91ad52009-07-17 12:17:14 -07002081int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002082 return (int)mCblk->sampleRate;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002083}
2084
Eric Laurent9d91ad52009-07-17 12:17:14 -07002085int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
Eric Laurent0bac5382009-07-07 07:10:45 -07002086 return (int)mCblk->channels;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002087}
2088
Eric Laurent9d91ad52009-07-17 12:17:14 -07002089void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002090 audio_track_cblk_t* cblk = this->cblk();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002091 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2092 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002093
2094 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002095 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2096 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002097 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2098 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002099 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project4f68be12009-03-18 17:39:46 -07002100 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002101 return 0;
2102 }
2103
2104 return bufferStart;
2105}
2106
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002107// ----------------------------------------------------------------------------
2108
Eric Laurent9d91ad52009-07-17 12:17:14 -07002109// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2110AudioFlinger::PlaybackThread::Track::Track(
2111 const wp<ThreadBase>& thread,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002112 const sp<Client>& client,
2113 int streamType,
2114 uint32_t sampleRate,
2115 int format,
2116 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002117 int frameCount,
2118 const sp<IMemory>& sharedBuffer)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002119 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2120 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002121{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002122 sp<ThreadBase> baseThread = thread.promote();
2123 if (baseThread != 0) {
2124 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2125 mName = playbackThread->getTrackName_l();
2126 }
2127 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2128 if (mName < 0) {
2129 LOGE("no more track names available");
2130 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002131 mVolume[0] = 1.0f;
2132 mVolume[1] = 1.0f;
Eric Laurent570dd0b2009-05-22 09:18:15 -07002133 mStreamType = streamType;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002134 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2135 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2136 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002137}
2138
Eric Laurent9d91ad52009-07-17 12:17:14 -07002139AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002140{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002141 LOGV("PlaybackThread::Track destructor");
2142 sp<ThreadBase> thread = mThread.promote();
2143 if (thread != 0) {
2144 Mutex::Autolock _l(thread->mLock);
2145 mState = TERMINATED;
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002146 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002147}
2148
Eric Laurent9d91ad52009-07-17 12:17:14 -07002149void AudioFlinger::PlaybackThread::Track::destroy()
2150{
2151 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2152 // by removing it from mTracks vector, so there is a risk that this Tracks's
2153 // desctructor is called. As the destructor needs to lock mLock,
2154 // we must acquire a strong reference on this Track before locking mLock
2155 // here so that the destructor is called only when exiting this function.
2156 // On the other hand, as long as Track::destroy() is only called by
2157 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2158 // this Track with its member mTrack.
2159 sp<Track> keep(this);
2160 { // scope for mLock
2161 sp<ThreadBase> thread = mThread.promote();
2162 if (thread != 0) {
2163 Mutex::Autolock _l(thread->mLock);
2164 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2165 playbackThread->destroyTrack_l(this);
2166 }
2167 }
2168}
2169
2170void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002171{
2172 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2173 mName - AudioMixer::TRACK0,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002174 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002175 mStreamType,
2176 mFormat,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002177 mCblk->channels,
2178 mFrameCount,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002179 mState,
2180 mMute,
2181 mFillingUpStatus,
2182 mCblk->sampleRate,
2183 mCblk->volume[0],
2184 mCblk->volume[1],
2185 mCblk->server,
2186 mCblk->user);
2187}
2188
Eric Laurent9d91ad52009-07-17 12:17:14 -07002189status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002190{
2191 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002192 uint32_t framesReady;
2193 uint32_t framesReq = buffer->frameCount;
2194
2195 // Check if last stepServer failed, try to step now
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002196 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2197 if (!step()) goto getNextBuffer_exit;
2198 LOGV("stepServer recovered");
2199 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2200 }
2201
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002202 framesReady = cblk->framesReady();
2203
2204 if (LIKELY(framesReady)) {
2205 uint32_t s = cblk->server;
2206 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2207
2208 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2209 if (framesReq > framesReady) {
2210 framesReq = framesReady;
2211 }
2212 if (s + framesReq > bufferEnd) {
2213 framesReq = bufferEnd - s;
2214 }
2215
2216 buffer->raw = getBuffer(s, framesReq);
2217 if (buffer->raw == 0) goto getNextBuffer_exit;
2218
2219 buffer->frameCount = framesReq;
2220 return NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002221 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002222
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002223getNextBuffer_exit:
2224 buffer->raw = 0;
2225 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002226 LOGV("getNextBuffer() no more data");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002227 return NOT_ENOUGH_DATA;
2228}
2229
Eric Laurent9d91ad52009-07-17 12:17:14 -07002230bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002231 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002232
2233 if (mCblk->framesReady() >= mCblk->frameCount ||
2234 mCblk->forceReady) {
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002235 mFillingUpStatus = FS_FILLED;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002236 mCblk->forceReady = 0;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002237 return true;
2238 }
2239 return false;
2240}
2241
Eric Laurent9d91ad52009-07-17 12:17:14 -07002242status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002243{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002244 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2245 sp<ThreadBase> thread = mThread.promote();
2246 if (thread != 0) {
2247 Mutex::Autolock _l(thread->mLock);
2248 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2249 playbackThread->addTrack_l(this);
2250 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002251 return NO_ERROR;
2252}
2253
Eric Laurent9d91ad52009-07-17 12:17:14 -07002254void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002255{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002256 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2257 sp<ThreadBase> thread = mThread.promote();
2258 if (thread != 0) {
2259 Mutex::Autolock _l(thread->mLock);
2260 if (mState > STOPPED) {
2261 mState = STOPPED;
2262 // If the track is not active (PAUSED and buffers full), flush buffers
2263 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2264 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2265 reset();
2266 }
2267 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002268 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002269 }
2270}
2271
Eric Laurent9d91ad52009-07-17 12:17:14 -07002272void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002273{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002274 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurent9d91ad52009-07-17 12:17:14 -07002275 sp<ThreadBase> thread = mThread.promote();
2276 if (thread != 0) {
2277 Mutex::Autolock _l(thread->mLock);
2278 if (mState == ACTIVE || mState == RESUMING) {
2279 mState = PAUSING;
2280 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2281 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002282 }
2283}
2284
Eric Laurent9d91ad52009-07-17 12:17:14 -07002285void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002286{
2287 LOGV("flush(%d)", mName);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002288 sp<ThreadBase> thread = mThread.promote();
2289 if (thread != 0) {
2290 Mutex::Autolock _l(thread->mLock);
2291 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2292 return;
2293 }
2294 // No point remaining in PAUSED state after a flush => go to
2295 // STOPPED state
2296 mState = STOPPED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002297
Eric Laurent9d91ad52009-07-17 12:17:14 -07002298 mCblk->lock.lock();
2299 // NOTE: reset() will reset cblk->user and cblk->server with
2300 // the risk that at the same time, the AudioMixer is trying to read
2301 // data. In this case, getNextBuffer() would return a NULL pointer
2302 // as audio buffer => the AudioMixer code MUST always test that pointer
2303 // returned by getNextBuffer() is not NULL!
2304 reset();
2305 mCblk->lock.unlock();
2306 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002307}
2308
Eric Laurent9d91ad52009-07-17 12:17:14 -07002309void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002310{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002311 // Do not reset twice to avoid discarding data written just after a flush and before
2312 // the audioflinger thread detects the track is stopped.
2313 if (!mResetDone) {
2314 TrackBase::reset();
2315 // Force underrun condition to avoid false underrun callback until first data is
2316 // written to buffer
2317 mCblk->flowControlFlag = 1;
2318 mCblk->forceReady = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002319 mFillingUpStatus = FS_FILLING;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002320 mResetDone = true;
2321 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002322}
2323
Eric Laurent9d91ad52009-07-17 12:17:14 -07002324void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002325{
2326 mMute = muted;
2327}
2328
Eric Laurent9d91ad52009-07-17 12:17:14 -07002329void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002330{
2331 mVolume[0] = left;
2332 mVolume[1] = right;
2333}
2334
2335// ----------------------------------------------------------------------------
2336
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002337// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurent9d91ad52009-07-17 12:17:14 -07002338AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2339 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340 const sp<Client>& client,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 uint32_t sampleRate,
2342 int format,
2343 int channelCount,
2344 int frameCount,
2345 uint32_t flags)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002346 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 channelCount, frameCount, flags, 0),
Eric Laurent9d91ad52009-07-17 12:17:14 -07002348 mOverflow(false)
2349{
2350 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2351 if (format == AudioSystem::PCM_16_BIT) {
2352 mCblk->frameSize = channelCount * sizeof(int16_t);
2353 } else if (format == AudioSystem::PCM_8_BIT) {
2354 mCblk->frameSize = channelCount * sizeof(int8_t);
2355 } else {
2356 mCblk->frameSize = sizeof(int8_t);
2357 }
2358}
2359
2360AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361{
2362}
2363
Eric Laurent9d91ad52009-07-17 12:17:14 -07002364status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365{
2366 audio_track_cblk_t* cblk = this->cblk();
2367 uint32_t framesAvail;
2368 uint32_t framesReq = buffer->frameCount;
2369
2370 // Check if last stepServer failed, try to step now
2371 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2372 if (!step()) goto getNextBuffer_exit;
2373 LOGV("stepServer recovered");
2374 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2375 }
2376
2377 framesAvail = cblk->framesAvailable_l();
2378
2379 if (LIKELY(framesAvail)) {
2380 uint32_t s = cblk->server;
2381 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2382
2383 if (framesReq > framesAvail) {
2384 framesReq = framesAvail;
2385 }
2386 if (s + framesReq > bufferEnd) {
2387 framesReq = bufferEnd - s;
2388 }
2389
2390 buffer->raw = getBuffer(s, framesReq);
2391 if (buffer->raw == 0) goto getNextBuffer_exit;
2392
2393 buffer->frameCount = framesReq;
2394 return NO_ERROR;
2395 }
2396
2397getNextBuffer_exit:
2398 buffer->raw = 0;
2399 buffer->frameCount = 0;
2400 return NOT_ENOUGH_DATA;
2401}
2402
Eric Laurent9d91ad52009-07-17 12:17:14 -07002403status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002405 sp<ThreadBase> thread = mThread.promote();
2406 if (thread != 0) {
2407 RecordThread *recordThread = (RecordThread *)thread.get();
2408 return recordThread->start(this);
2409 }
2410 return NO_INIT;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411}
2412
Eric Laurent9d91ad52009-07-17 12:17:14 -07002413void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002415 sp<ThreadBase> thread = mThread.promote();
2416 if (thread != 0) {
2417 RecordThread *recordThread = (RecordThread *)thread.get();
2418 recordThread->stop(this);
2419 TrackBase::reset();
2420 // Force overerrun condition to avoid false overrun callback until first data is
2421 // read from buffer
2422 mCblk->flowControlFlag = 1;
2423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424}
2425
2426
2427// ----------------------------------------------------------------------------
2428
Eric Laurent9d91ad52009-07-17 12:17:14 -07002429AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2430 const wp<ThreadBase>& thread,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431 uint32_t sampleRate,
2432 int format,
2433 int channelCount,
2434 int frameCount)
Eric Laurent9d91ad52009-07-17 12:17:14 -07002435 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2436 mActive(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002437{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002438
2439 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440 mCblk->out = 1;
2441 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2442 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2443 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002444 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2445
2446 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2447 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2448
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449}
2450
Eric Laurent9d91ad52009-07-17 12:17:14 -07002451AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452{
2453 stop();
2454}
2455
Eric Laurent9d91ad52009-07-17 12:17:14 -07002456status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457{
2458 status_t status = Track::start();
Eric Laurent9d91ad52009-07-17 12:17:14 -07002459 if (status != NO_ERROR) {
2460 return status;
2461 }
2462
2463 mActive = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464 mRetryCount = 127;
2465 return status;
2466}
2467
Eric Laurent9d91ad52009-07-17 12:17:14 -07002468void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469{
2470 Track::stop();
2471 clearBufferQueue();
2472 mOutBuffer.frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002473 mActive = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474}
2475
Eric Laurent9d91ad52009-07-17 12:17:14 -07002476bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477{
2478 Buffer *pInBuffer;
2479 Buffer inBuffer;
2480 uint32_t channels = mCblk->channels;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002481 bool outputBufferFull = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 inBuffer.frameCount = frames;
2483 inBuffer.i16 = data;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002484
2485 uint32_t waitTimeLeftMs = mWaitTimeMs;
2486
2487 if (!mActive) {
2488 start();
2489 sp<ThreadBase> thread = mThread.promote();
2490 if (thread != 0) {
2491 MixerThread *mixerThread = (MixerThread *)thread.get();
2492 if (mCblk->frameCount > frames){
2493 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2494 uint32_t startFrames = (mCblk->frameCount - frames);
2495 pInBuffer = new Buffer;
2496 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2497 pInBuffer->frameCount = startFrames;
2498 pInBuffer->i16 = pInBuffer->mBuffer;
2499 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2500 mBufferQueue.add(pInBuffer);
2501 } else {
2502 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2503 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506 }
2507
Eric Laurent9d91ad52009-07-17 12:17:14 -07002508 while (waitTimeLeftMs) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 // First write pending buffers, then new data
2510 if (mBufferQueue.size()) {
2511 pInBuffer = mBufferQueue.itemAt(0);
2512 } else {
2513 pInBuffer = &inBuffer;
2514 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 if (pInBuffer->frameCount == 0) {
2517 break;
2518 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 if (mOutBuffer.frameCount == 0) {
2521 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002522 nsecs_t startTime = systemTime();
2523 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2524 LOGV ("OutputTrack::write() %p no more output buffers", this);
2525 outputBufferFull = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 break;
2527 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002528 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2529// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2530 if (waitTimeLeftMs >= waitTimeMs) {
2531 waitTimeLeftMs -= waitTimeMs;
2532 } else {
2533 waitTimeLeftMs = 0;
2534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002536
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2538 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2539 mCblk->stepUser(outFrames);
2540 pInBuffer->frameCount -= outFrames;
2541 pInBuffer->i16 += outFrames * channels;
2542 mOutBuffer.frameCount -= outFrames;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002543 mOutBuffer.i16 += outFrames * channels;
2544
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 if (pInBuffer->frameCount == 0) {
2546 if (mBufferQueue.size()) {
2547 mBufferQueue.removeAt(0);
2548 delete [] pInBuffer->mBuffer;
2549 delete pInBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002550 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002551 } else {
2552 break;
2553 }
2554 }
2555 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002556
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 // If we could not write all frames, allocate a buffer and queue it for next time.
2558 if (inBuffer.frameCount) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002559 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560 pInBuffer = new Buffer;
2561 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2562 pInBuffer->frameCount = inBuffer.frameCount;
2563 pInBuffer->i16 = pInBuffer->mBuffer;
2564 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2565 mBufferQueue.add(pInBuffer);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002566 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002568 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 }
2570 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002571
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurent9d91ad52009-07-17 12:17:14 -07002573 // 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 -08002574 // by output mixer.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002575 if (frames == 0 && mBufferQueue.size() == 0) {
2576 if (mCblk->user < mCblk->frameCount) {
2577 frames = mCblk->frameCount - mCblk->user;
2578 pInBuffer = new Buffer;
2579 pInBuffer->mBuffer = new int16_t[frames * channels];
2580 pInBuffer->frameCount = frames;
2581 pInBuffer->i16 = pInBuffer->mBuffer;
2582 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2583 mBufferQueue.add(pInBuffer);
2584 } else {
2585 stop();
2586 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002587 }
2588
Eric Laurent9d91ad52009-07-17 12:17:14 -07002589 return outputBufferFull;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590}
2591
Eric Laurent9d91ad52009-07-17 12:17:14 -07002592status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593{
2594 int active;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 status_t result;
2596 audio_track_cblk_t* cblk = mCblk;
2597 uint32_t framesReq = buffer->frameCount;
2598
Eric Laurent9d91ad52009-07-17 12:17:14 -07002599// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 buffer->frameCount = 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002601
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002602 uint32_t framesAvail = cblk->framesAvailable();
2603
Eric Laurent9d91ad52009-07-17 12:17:14 -07002604
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 if (framesAvail == 0) {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002606 Mutex::Autolock _l(cblk->lock);
2607 goto start_loop_here;
2608 while (framesAvail == 0) {
2609 active = mActive;
2610 if (UNLIKELY(!active)) {
2611 LOGV("Not active and NO_MORE_BUFFERS");
2612 return AudioTrack::NO_MORE_BUFFERS;
2613 }
2614 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2615 if (result != NO_ERROR) {
2616 return AudioTrack::NO_MORE_BUFFERS;
2617 }
2618 // read the server count again
2619 start_loop_here:
2620 framesAvail = cblk->framesAvailable_l();
2621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 }
2623
Eric Laurent9d91ad52009-07-17 12:17:14 -07002624// if (framesAvail < framesReq) {
2625// return AudioTrack::NO_MORE_BUFFERS;
2626// }
2627
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 if (framesReq > framesAvail) {
2629 framesReq = framesAvail;
2630 }
2631
2632 uint32_t u = cblk->user;
2633 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2634
2635 if (u + framesReq > bufferEnd) {
2636 framesReq = bufferEnd - u;
2637 }
2638
2639 buffer->frameCount = framesReq;
2640 buffer->raw = (void *)cblk->buffer(u);
2641 return NO_ERROR;
2642}
2643
2644
Eric Laurent9d91ad52009-07-17 12:17:14 -07002645void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646{
2647 size_t size = mBufferQueue.size();
2648 Buffer *pBuffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002649
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650 for (size_t i = 0; i < size; i++) {
2651 pBuffer = mBufferQueue.itemAt(i);
2652 delete [] pBuffer->mBuffer;
2653 delete pBuffer;
2654 }
2655 mBufferQueue.clear();
2656}
2657
2658// ----------------------------------------------------------------------------
2659
2660AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2661 : RefBase(),
2662 mAudioFlinger(audioFlinger),
2663 mMemoryDealer(new MemoryDealer(1024*1024)),
2664 mPid(pid)
2665{
2666 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2667}
2668
2669AudioFlinger::Client::~Client()
2670{
2671 mAudioFlinger->removeClient(mPid);
2672}
2673
2674const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2675{
2676 return mMemoryDealer;
2677}
2678
2679// ----------------------------------------------------------------------------
2680
Eric Laurent9d91ad52009-07-17 12:17:14 -07002681AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002682 : BnAudioTrack(),
2683 mTrack(track)
2684{
2685}
2686
2687AudioFlinger::TrackHandle::~TrackHandle() {
2688 // just stop the track on deletion, associated resources
2689 // will be freed from the main thread once all pending buffers have
2690 // been played. Unless it's not in the active track list, in which
2691 // case we free everything now...
2692 mTrack->destroy();
2693}
2694
2695status_t AudioFlinger::TrackHandle::start() {
2696 return mTrack->start();
2697}
2698
2699void AudioFlinger::TrackHandle::stop() {
2700 mTrack->stop();
2701}
2702
2703void AudioFlinger::TrackHandle::flush() {
2704 mTrack->flush();
2705}
2706
2707void AudioFlinger::TrackHandle::mute(bool e) {
2708 mTrack->mute(e);
2709}
2710
2711void AudioFlinger::TrackHandle::pause() {
2712 mTrack->pause();
2713}
2714
2715void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2716 mTrack->setVolume(left, right);
2717}
2718
2719sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2720 return mTrack->getCblk();
2721}
2722
2723status_t AudioFlinger::TrackHandle::onTransact(
2724 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2725{
2726 return BnAudioTrack::onTransact(code, data, reply, flags);
2727}
2728
2729// ----------------------------------------------------------------------------
2730
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002731sp<IAudioRecord> AudioFlinger::openRecord(
2732 pid_t pid,
Eric Laurente0e9ecc2009-07-28 08:44:33 -07002733 int input,
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002734 uint32_t sampleRate,
2735 int format,
2736 int channelCount,
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002737 int frameCount,
2738 uint32_t flags,
2739 status_t *status)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002740{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002741 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002742 sp<RecordHandle> recordHandle;
2743 sp<Client> client;
2744 wp<Client> wclient;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002745 status_t lStatus;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002746 RecordThread *thread;
2747 size_t inFrameCount;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002748
2749 // check calling permissions
2750 if (!recordingAllowed()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002751 lStatus = PERMISSION_DENIED;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002752 goto Exit;
2753 }
2754
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002755 // add client to list
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002756 { // scope for mLock
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002757 Mutex::Autolock _l(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002758 thread = checkRecordThread_l(input);
2759 if (thread == NULL) {
2760 lStatus = BAD_VALUE;
2761 goto Exit;
2762 }
2763
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002764 wclient = mClients.valueFor(pid);
2765 if (wclient != NULL) {
2766 client = wclient.promote();
2767 } else {
2768 client = new Client(this, pid);
2769 mClients.add(pid, client);
2770 }
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002771
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002772 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurent9d91ad52009-07-17 12:17:14 -07002773 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Project22f8def2009-03-09 11:52:12 -07002774 format, channelCount, frameCount, flags);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002775 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 if (recordTrack->getCblk() == NULL) {
2777 recordTrack.clear();
2778 lStatus = NO_MEMORY;
2779 goto Exit;
2780 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002781
2782 // return to handle to client
2783 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002784 lStatus = NO_ERROR;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002785
2786Exit:
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002787 if (status) {
2788 *status = lStatus;
2789 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002790 return recordHandle;
2791}
2792
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002793// ----------------------------------------------------------------------------
2794
Eric Laurent9d91ad52009-07-17 12:17:14 -07002795AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002796 : BnAudioRecord(),
2797 mRecordTrack(recordTrack)
2798{
2799}
2800
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002801AudioFlinger::RecordHandle::~RecordHandle() {
2802 stop();
2803}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002804
2805status_t AudioFlinger::RecordHandle::start() {
2806 LOGV("RecordHandle::start()");
2807 return mRecordTrack->start();
2808}
2809
2810void AudioFlinger::RecordHandle::stop() {
2811 LOGV("RecordHandle::stop()");
2812 mRecordTrack->stop();
2813}
2814
2815sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2816 return mRecordTrack->getCblk();
2817}
2818
2819status_t AudioFlinger::RecordHandle::onTransact(
2820 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2821{
2822 return BnAudioRecord::onTransact(code, data, reply, flags);
2823}
2824
2825// ----------------------------------------------------------------------------
2826
Eric Laurent9d91ad52009-07-17 12:17:14 -07002827AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2828 ThreadBase(audioFlinger),
2829 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002830{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002831 mReqChannelCount = AudioSystem::popCount(channels);
2832 mReqSampleRate = sampleRate;
2833 readInputParameters();
2834 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002835}
2836
Eric Laurent9d91ad52009-07-17 12:17:14 -07002837
2838AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002839{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002840 mAudioFlinger->mAudioHardware->closeInputStream(mInput);
2841 delete[] mRsmpInBuffer;
2842 if (mResampler != 0) {
2843 delete mResampler;
2844 delete[] mRsmpOutBuffer;
2845 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002846}
2847
Eric Laurent9d91ad52009-07-17 12:17:14 -07002848void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002849{
Eric Laurent9d91ad52009-07-17 12:17:14 -07002850 const size_t SIZE = 256;
2851 char buffer[SIZE];
2852
2853 snprintf(buffer, SIZE, "Record Thread %p", this);
2854
2855 run(buffer, PRIORITY_URGENT_AUDIO);
2856}
2857bool AudioFlinger::RecordThread::threadLoop()
2858{
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002859 AudioBufferProvider::Buffer buffer;
Eric Laurent9d91ad52009-07-17 12:17:14 -07002860 sp<RecordTrack> activeTrack;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002861
2862 // start recording
2863 while (!exitPending()) {
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002864
Eric Laurent9d91ad52009-07-17 12:17:14 -07002865 processConfigEvents();
2866
2867 { // scope for mLock
2868 Mutex::Autolock _l(mLock);
2869 checkForNewParameters_l();
2870 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2871 if (!mStandby) {
2872 mInput->standby();
2873 mStandby = true;
2874 }
2875
2876 if (exitPending()) break;
2877
2878 LOGV("RecordThread: loop stopping");
2879 // go to sleep
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002880 mWaitWorkCV.wait(mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07002881 LOGV("RecordThread: loop starting");
2882 continue;
2883 }
2884 if (mActiveTrack != 0) {
2885 if (mActiveTrack->mState == TrackBase::PAUSING) {
2886 mActiveTrack.clear();
2887 mStartStopCond.broadcast();
2888 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2889 mRsmpInIndex = mFrameCount;
2890 if (mReqChannelCount != mActiveTrack->channelCount()) {
2891 mActiveTrack.clear();
2892 } else {
2893 mActiveTrack->mState == TrackBase::ACTIVE;
2894 }
2895 mStartStopCond.broadcast();
2896 }
2897 mStandby = false;
2898 }
2899 }
2900
2901 if (mActiveTrack != 0) {
2902 buffer.frameCount = mFrameCount;
2903 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2904 size_t framesOut = buffer.frameCount;
2905 if (mResampler == 0) {
2906 // no resampling
2907 while (framesOut) {
2908 size_t framesIn = mFrameCount - mRsmpInIndex;
2909 if (framesIn) {
2910 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2911 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2912 if (framesIn > framesOut)
2913 framesIn = framesOut;
2914 mRsmpInIndex += framesIn;
2915 framesOut -= framesIn;
2916 if (mChannelCount == mReqChannelCount ||
2917 mFormat != AudioSystem::PCM_16_BIT) {
2918 memcpy(dst, src, framesIn * mFrameSize);
2919 } else {
2920 int16_t *src16 = (int16_t *)src;
2921 int16_t *dst16 = (int16_t *)dst;
2922 if (mChannelCount == 1) {
2923 while (framesIn--) {
2924 *dst16++ = *src16;
2925 *dst16++ = *src16++;
2926 }
2927 } else {
2928 while (framesIn--) {
2929 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2930 src16 += 2;
2931 }
2932 }
2933 }
2934 }
2935 if (framesOut && mFrameCount == mRsmpInIndex) {
2936 ssize_t bytesRead;
2937 if (framesOut == mFrameCount &&
2938 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2939 bytesRead = mInput->read(buffer.raw, mInputBytes);
2940 framesOut = 0;
2941 } else {
2942 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2943 mRsmpInIndex = 0;
2944 }
2945 if (bytesRead < 0) {
2946 LOGE("Error reading audio input");
2947 sleep(1);
2948 mRsmpInIndex = mFrameCount;
2949 framesOut = 0;
2950 buffer.frameCount = 0;
2951 }
2952 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002953 }
2954 } else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002955 // resampling
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002956
Eric Laurent9d91ad52009-07-17 12:17:14 -07002957 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
2958 // alter output frame count as if we were expecting stereo samples
2959 if (mChannelCount == 1 && mReqChannelCount == 1) {
2960 framesOut >>= 1;
2961 }
2962 mResampler->resample(mRsmpOutBuffer, framesOut, this);
2963 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
2964 // are 32 bit aligned which should be always true.
2965 if (mChannelCount == 2 && mReqChannelCount == 1) {
2966 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
2967 // the resampler always outputs stereo samples: do post stereo to mono conversion
2968 int16_t *src = (int16_t *)mRsmpOutBuffer;
2969 int16_t *dst = buffer.i16;
2970 while (framesOut--) {
2971 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
2972 src += 2;
2973 }
2974 } else {
2975 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
2976 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002977
Eric Laurent9d91ad52009-07-17 12:17:14 -07002978 }
2979 mActiveTrack->releaseBuffer(&buffer);
2980 mActiveTrack->overflow();
2981 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002982 // client isn't retrieving buffers fast enough
2983 else {
Eric Laurent9d91ad52009-07-17 12:17:14 -07002984 if (!mActiveTrack->setOverflow())
2985 LOGW("RecordThread: buffer overflow");
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002986 // Release the processor for a while before asking for a new buffer.
2987 // This will give the application more chance to read from the buffer and
2988 // clear the overflow.
2989 usleep(5000);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002990 }
2991 }
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002992 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07002993
Eric Laurent9d91ad52009-07-17 12:17:14 -07002994 if (!mStandby) {
2995 mInput->standby();
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08002996 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07002997 mActiveTrack.clear();
2998
2999 sendConfigEvent(AudioSystem::INPUT_CLOSED);
3000 processConfigEvents();
3001
3002 LOGV("RecordThread %p exiting", this);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003003 return false;
3004}
3005
Eric Laurent9d91ad52009-07-17 12:17:14 -07003006status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003007{
Eric Laurent9d91ad52009-07-17 12:17:14 -07003008 LOGV("RecordThread::start");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003009 AutoMutex lock(&mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003010
Eric Laurent9d91ad52009-07-17 12:17:14 -07003011 if (mActiveTrack != 0) {
3012 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projecte09fd9e2008-12-17 18:05:43 -08003013
Eric Laurent9d91ad52009-07-17 12:17:14 -07003014 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003015
Eric Laurent9d91ad52009-07-17 12:17:14 -07003016 return NO_ERROR;
3017 }
3018
3019 mActiveTrack = recordTrack;
3020 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003021 // signal thread to start
3022 LOGV("Signal record thread");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003023 mWaitWorkCV.signal();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003024 mStartStopCond.wait(mLock);
3025 if (mActiveTrack != 0) {
3026 LOGV("Record started OK");
3027 return NO_ERROR;
3028 } else {
3029 LOGV("Record failed to start");
3030 return BAD_VALUE;
3031 }
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003032}
3033
Eric Laurent9d91ad52009-07-17 12:17:14 -07003034void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3035 LOGV("RecordThread::stop");
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003036 AutoMutex lock(&mLock);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003037 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3038 mActiveTrack->mState = TrackBase::PAUSING;
3039 mStartStopCond.wait(mLock);
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003040 }
3041}
3042
Eric Laurent9d91ad52009-07-17 12:17:14 -07003043status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044{
3045 const size_t SIZE = 256;
3046 char buffer[SIZE];
3047 String8 result;
3048 pid_t pid = 0;
3049
Eric Laurent9d91ad52009-07-17 12:17:14 -07003050 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3051 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 result.append(buffer);
3053 } else {
3054 result.append("No record client\n");
3055 }
3056 write(fd, result.string(), result.size());
3057 return NO_ERROR;
3058}
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003059
Eric Laurent9d91ad52009-07-17 12:17:14 -07003060status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3061{
3062 size_t framesReq = buffer->frameCount;
3063 size_t framesReady = mFrameCount - mRsmpInIndex;
3064 int channelCount;
3065
3066 if (framesReady == 0) {
3067 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3068 if (bytesRead < 0) {
3069 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3070 sleep(1);
3071 buffer->raw = 0;
3072 buffer->frameCount = 0;
3073 return NOT_ENOUGH_DATA;
3074 }
3075 mRsmpInIndex = 0;
3076 framesReady = mFrameCount;
3077 }
3078
3079 if (framesReq > framesReady) {
3080 framesReq = framesReady;
3081 }
3082
3083 if (mChannelCount == 1 && mReqChannelCount == 2) {
3084 channelCount = 1;
3085 } else {
3086 channelCount = 2;
3087 }
3088 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3089 buffer->frameCount = framesReq;
3090 return NO_ERROR;
3091}
3092
3093void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3094{
3095 mRsmpInIndex += buffer->frameCount;
3096 buffer->frameCount = 0;
3097}
3098
3099bool AudioFlinger::RecordThread::checkForNewParameters_l()
3100{
3101 bool reconfig = false;
3102
3103 if (mNewParameters != "") {
3104 status_t status = NO_ERROR;
3105 AudioParameter param = AudioParameter(mNewParameters);
3106 int value;
3107 int reqFormat = mFormat;
3108 int reqSamplingRate = mReqSampleRate;
3109 int reqChannelCount = mReqChannelCount;
3110 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3111 reqSamplingRate = value;
3112 reconfig = true;
3113 }
3114 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3115 reqFormat = value;
3116 reconfig = true;
3117 }
3118 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3119 reqChannelCount = AudioSystem::popCount(value);
3120 reconfig = true;
3121 }
3122 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3123 // do not accept frame count changes if tracks are open as the track buffer
3124 // size depends on frame count and correct behavior would not be garantied
3125 // if frame count is changed after track creation
3126 if (mActiveTrack != 0) {
3127 status = INVALID_OPERATION;
3128 } else {
3129 reconfig = true;
3130 }
3131 }
3132 if (status == NO_ERROR) {
3133 status = mInput->setParameters(mNewParameters);
3134 if (status == INVALID_OPERATION) {
3135 mInput->standby();
3136 status = mInput->setParameters(mNewParameters);
3137 }
3138 if (reconfig) {
3139 if (status == BAD_VALUE &&
3140 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3141 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3142 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3143 status = NO_ERROR;
3144 }
3145 if (status == NO_ERROR) {
3146 readInputParameters();
3147 sendConfigEvent(AudioSystem::INPUT_CONFIG_CHANGED);
3148 }
3149 }
3150 }
3151 mNewParameters = "";
3152 mParamStatus = status;
3153 mParamCond.signal();
3154 }
3155 return reconfig;
3156}
3157
3158String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3159{
3160 return mInput->getParameters(keys);
3161}
3162
3163void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3164 AudioSystem::OutputDescriptor desc;
3165 void *param2 = 0;
3166
3167 switch (event) {
3168 case AudioSystem::INPUT_OPENED:
3169 case AudioSystem::INPUT_CONFIG_CHANGED:
3170 desc.channels = mChannelCount;
3171 desc.samplingRate = mSampleRate;
3172 desc.format = mFormat;
3173 desc.frameCount = mFrameCount;
3174 desc.latency = 0;
3175 param2 = &desc;
3176 break;
3177
3178 case AudioSystem::INPUT_CLOSED:
3179 default:
3180 break;
3181 }
3182 mAudioFlinger->audioConfigChanged(event, this, param2);
3183}
3184
3185void AudioFlinger::RecordThread::readInputParameters()
3186{
3187 if (mRsmpInBuffer) delete mRsmpInBuffer;
3188 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3189 if (mResampler) delete mResampler;
3190 mResampler = 0;
3191
3192 mSampleRate = mInput->sampleRate();
3193 mChannelCount = AudioSystem::popCount(mInput->channels());
3194 mFormat = mInput->format();
3195 mFrameSize = mInput->frameSize();
3196 mInputBytes = mInput->bufferSize();
3197 mFrameCount = mInputBytes / mFrameSize;
3198 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3199
3200 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3201 {
3202 int channelCount;
3203 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3204 // stereo to mono post process as the resampler always outputs stereo.
3205 if (mChannelCount == 1 && mReqChannelCount == 2) {
3206 channelCount = 1;
3207 } else {
3208 channelCount = 2;
3209 }
3210 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3211 mResampler->setSampleRate(mSampleRate);
3212 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3213 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3214
3215 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3216 if (mChannelCount == 1 && mReqChannelCount == 1) {
3217 mFrameCount >>= 1;
3218 }
3219
3220 }
3221 mRsmpInIndex = mFrameCount;
3222}
3223
3224// ----------------------------------------------------------------------------
3225
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003226int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003227 uint32_t *pSamplingRate,
3228 uint32_t *pFormat,
3229 uint32_t *pChannels,
3230 uint32_t *pLatencyMs,
3231 uint32_t flags)
3232{
3233 status_t status;
3234 PlaybackThread *thread = NULL;
3235 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3236 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3237 uint32_t format = pFormat ? *pFormat : 0;
3238 uint32_t channels = pChannels ? *pChannels : 0;
3239 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3240
3241 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3242 pDevices ? *pDevices : 0,
3243 samplingRate,
3244 format,
3245 channels,
3246 flags);
3247
3248 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003249 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003250 }
3251 Mutex::Autolock _l(mLock);
3252
3253 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3254 (int *)&format,
3255 &channels,
3256 &samplingRate,
3257 &status);
3258 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3259 output,
3260 samplingRate,
3261 format,
3262 channels,
3263 status);
3264
3265 mHardwareStatus = AUDIO_HW_IDLE;
3266 if (output != 0) {
3267 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3268 (format != AudioSystem::PCM_16_BIT) ||
3269 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3270 thread = new DirectOutputThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003271 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003272 } else {
3273 thread = new MixerThread(this, output);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003274 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003275 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003276 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003277
3278 if (pSamplingRate) *pSamplingRate = samplingRate;
3279 if (pFormat) *pFormat = format;
3280 if (pChannels) *pChannels = channels;
3281 if (pLatencyMs) *pLatencyMs = thread->latency();
3282 }
3283
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003284 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003285}
3286
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003287int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003288{
3289 Mutex::Autolock _l(mLock);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003290 MixerThread *thread1 = checkMixerThread_l(output1);
3291 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003292
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003293 if (thread1 == NULL || thread2 == NULL) {
3294 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3295 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003296 }
3297
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003298
3299 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3300 thread->addOutputTrack(thread2);
3301 mPlaybackThreads.add(++mNextThreadId, thread);
3302 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003303}
3304
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003305status_t AudioFlinger::closeOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003306{
3307 PlaybackThread *thread;
3308 {
3309 Mutex::Autolock _l(mLock);
3310 thread = checkPlaybackThread_l(output);
3311 if (thread == NULL) {
3312 return BAD_VALUE;
3313 }
3314
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003315 LOGV("closeOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003316
3317 if (thread->type() == PlaybackThread::MIXER) {
3318 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003319 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3320 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003321 dupThread->removeOutputTrack((MixerThread *)thread);
3322 }
3323 }
3324 }
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003325 mPlaybackThreads.removeItem(output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003326 }
3327 thread->exit();
3328
3329 return NO_ERROR;
3330}
3331
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003332status_t AudioFlinger::suspendOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003333{
3334 Mutex::Autolock _l(mLock);
3335 PlaybackThread *thread = checkPlaybackThread_l(output);
3336
3337 if (thread == NULL) {
3338 return BAD_VALUE;
3339 }
3340
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003341 LOGV("suspendOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003342 thread->suspend();
3343
3344 return NO_ERROR;
3345}
3346
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003347status_t AudioFlinger::restoreOutput(int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003348{
3349 Mutex::Autolock _l(mLock);
3350 PlaybackThread *thread = checkPlaybackThread_l(output);
3351
3352 if (thread == NULL) {
3353 return BAD_VALUE;
3354 }
3355
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003356 LOGV("restoreOutput() %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003357
3358 thread->restore();
3359
3360 return NO_ERROR;
3361}
3362
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003363int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurent9d91ad52009-07-17 12:17:14 -07003364 uint32_t *pSamplingRate,
3365 uint32_t *pFormat,
3366 uint32_t *pChannels,
3367 uint32_t acoustics)
3368{
3369 status_t status;
3370 RecordThread *thread = NULL;
3371 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3372 uint32_t format = pFormat ? *pFormat : 0;
3373 uint32_t channels = pChannels ? *pChannels : 0;
3374 uint32_t reqSamplingRate = samplingRate;
3375 uint32_t reqFormat = format;
3376 uint32_t reqChannels = channels;
3377
3378 if (pDevices == NULL || *pDevices == 0) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003379 return 0;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003380 }
3381 Mutex::Autolock _l(mLock);
3382
3383 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3384 (int *)&format,
3385 &channels,
3386 &samplingRate,
3387 &status,
3388 (AudioSystem::audio_in_acoustics)acoustics);
3389 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3390 input,
3391 samplingRate,
3392 format,
3393 channels,
3394 acoustics,
3395 status);
3396
3397 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3398 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3399 // or stereo to mono conversions on 16 bit PCM inputs.
3400 if (input == 0 && status == BAD_VALUE &&
3401 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3402 (samplingRate <= 2 * reqSamplingRate) &&
3403 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3404 LOGV("openInput() reopening with proposed sampling rate and channels");
3405 input = mAudioHardware->openInputStream(*pDevices,
3406 (int *)&format,
3407 &channels,
3408 &samplingRate,
3409 &status,
3410 (AudioSystem::audio_in_acoustics)acoustics);
3411 }
3412
3413 if (input != 0) {
3414 // Start record thread
3415 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003416 mRecordThreads.add(++mNextThreadId, thread);
3417 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003418 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3419 if (pFormat) *pFormat = format;
3420 if (pChannels) *pChannels = reqChannels;
3421
3422 input->standby();
3423 }
3424
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003425 return mNextThreadId;
Eric Laurent9d91ad52009-07-17 12:17:14 -07003426}
3427
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003428status_t AudioFlinger::closeInput(int input)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003429{
3430 RecordThread *thread;
3431 {
3432 Mutex::Autolock _l(mLock);
3433 thread = checkRecordThread_l(input);
3434 if (thread == NULL) {
3435 return BAD_VALUE;
3436 }
3437
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003438 LOGV("closeInput() %d", input);
3439 mRecordThreads.removeItem(input);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003440 }
3441 thread->exit();
3442
3443 return NO_ERROR;
3444}
3445
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003446status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurent9d91ad52009-07-17 12:17:14 -07003447{
3448 Mutex::Autolock _l(mLock);
3449 MixerThread *dstThread = checkMixerThread_l(output);
3450 if (dstThread == NULL) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003451 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003452 return BAD_VALUE;
3453 }
3454
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003455 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003456
3457 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003458 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003459 if (thread != dstThread &&
3460 thread->type() != PlaybackThread::DIRECT) {
3461 MixerThread *srcThread = (MixerThread *)thread;
3462 SortedVector < sp<MixerThread::Track> > tracks;
3463 SortedVector < wp<MixerThread::Track> > activeTracks;
3464 srcThread->getTracks(tracks, activeTracks, stream);
3465 if (tracks.size()) {
3466 dstThread->putTracks(tracks, activeTracks);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003467 }
Eric Laurentd55d1792009-07-28 06:11:55 -07003468 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
Eric Laurent9d91ad52009-07-17 12:17:14 -07003469 }
3470 }
3471
3472 return NO_ERROR;
3473}
3474
3475// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003476AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003477{
3478 PlaybackThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003479 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3480 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003481 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003482 return thread;
3483}
3484
3485// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003486AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003487{
3488 PlaybackThread *thread = checkPlaybackThread_l(output);
3489 if (thread != NULL) {
3490 if (thread->type() == PlaybackThread::DIRECT) {
3491 thread = NULL;
3492 }
3493 }
3494 return (MixerThread *)thread;
3495}
3496
3497// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003498AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurent9d91ad52009-07-17 12:17:14 -07003499{
3500 RecordThread *thread = NULL;
Eric Laurente0e9ecc2009-07-28 08:44:33 -07003501 if (mRecordThreads.indexOfKey(input) >= 0) {
3502 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurent9d91ad52009-07-17 12:17:14 -07003503 }
Eric Laurent9d91ad52009-07-17 12:17:14 -07003504 return thread;
3505}
3506
3507// ----------------------------------------------------------------------------
3508
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003509status_t AudioFlinger::onTransact(
3510 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3511{
3512 return BnAudioFlinger::onTransact(code, data, reply, flags);
3513}
3514
3515// ----------------------------------------------------------------------------
Eric Laurent9d91ad52009-07-17 12:17:14 -07003516
The Android Open Source Project7c1b96a2008-10-21 07:00:00 -07003517void AudioFlinger::instantiate() {
3518 defaultServiceManager()->addService(
3519 String16("media.audio_flinger"), new AudioFlinger());
3520}
3521
3522}; // namespace android