blob: 2e947d6b7d23ced5a6396ec9febdcba1f1093c7e [file] [log] [blame]
The Android Open Source Project54b6cfa2008-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 Agopian07952722009-05-19 19:08:10 -070027#include <binder/IServiceManager.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070028#include <utils/Log.h>
Mathias Agopian07952722009-05-19 19:08:10 -070029#include <binder/Parcel.h>
30#include <binder/IPCThreadState.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070031#include <utils/String16.h>
32#include <utils/threads.h>
33
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080034#include <cutils/properties.h>
35
The Android Open Source Project54b6cfa2008-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 Project9266c552009-01-15 16:12:10 -080041#include <hardware_legacy/AudioHardwareInterface.h>
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -070042
43#include "AudioMixer.h"
44#include "AudioFlinger.h"
45
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -080046#ifdef WITH_A2DP
47#include "A2dpAudioInterface.h"
48#endif
49
The Android Open Source Project9066cfe2009-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 Project54b6cfa2008-10-21 07:00:00 -070059namespace android {
60
The Android Open Source Project10592532009-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 Projectf013e1a2008-12-17 18:05:43 -080064//static const nsecs_t kStandbyTimeInNsecs = seconds(3);
The Android Open Source Project54b6cfa2008-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 Projectb2a3dd82009-03-09 11:52:12 -070074static const int kDumpLockRetries = 50;
75static const int kDumpLockSleep = 20000;
76
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077
The Android Open Source Project54b6cfa2008-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 Project9066cfe2009-03-03 19:31:44 -0800117 : BnAudioFlinger(),
Eric Laurentddb78e72009-07-28 08:44:33 -0700118 mAudioHardware(0), mMasterVolume(1.0f), mMasterMute(false), mNextThreadId(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700119{
120 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700121
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700122 mAudioHardware = AudioHardwareInterface::create();
Eric Laurenta553c252009-07-17 12:17:14 -0700123
The Android Open Source Project54b6cfa2008-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 Laurenta553c252009-07-17 12:17:14 -0700127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 setMode(AudioSystem::MODE_NORMAL);
129
130 setMasterVolume(1.0f);
131 setMasterMute(false);
Eric Laurenta553c252009-07-17 12:17:14 -0700132 } else {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700133 LOGE("Couldn't even initialize the stubbed audio hardware!");
134 }
135}
136
137AudioFlinger::~AudioFlinger()
138{
Eric Laurenta553c252009-07-17 12:17:14 -0700139 mRecordThreads.clear();
140 mPlaybackThreads.clear();
The Android Open Source Projectb7986892009-01-09 17:51:23 -0800141}
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800142
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700143
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700144
The Android Open Source Project54b6cfa2008-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 Project54b6cfa2008-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 Projectb2a3dd82009-03-09 11:52:12 -0700172 int hardwareStatus = mHardwareStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700173
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700174 snprintf(buffer, SIZE, "Hardware status: %d\n", hardwareStatus);
The Android Open Source Project54b6cfa2008-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 Project10592532009-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 Project54b6cfa2008-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 Project10592532009-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 Projectb2a3dd82009-03-09 11:52:12 -0700227 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700228
229 dumpClients(fd, args);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700230 dumpInternals(fd, args);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Eric Laurenta553c252009-07-17 12:17:14 -0700232 // dump playback threads
233 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700234 mPlaybackThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700235 }
236
237 // dump record threads
Eric Laurent102313a2009-07-23 13:35:01 -0700238 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700239 mRecordThreads.valueAt(i)->dump(fd, args);
Eric Laurenta553c252009-07-17 12:17:14 -0700240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700242 if (mAudioHardware) {
243 mAudioHardware->dumpState(fd, args);
244 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700245 if (locked) mLock.unlock();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700246 }
247 return NO_ERROR;
248}
249
Eric Laurenta553c252009-07-17 12:17:14 -0700250
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700251// IAudioFlinger interface
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
253
The Android Open Source Project54b6cfa2008-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 Projectf013e1a2008-12-17 18:05:43 -0800260 int frameCount,
261 uint32_t flags,
262 const sp<IMemory>& sharedBuffer,
Eric Laurentddb78e72009-07-28 08:44:33 -0700263 int output,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800264 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700265{
Eric Laurenta553c252009-07-17 12:17:14 -0700266 sp<PlaybackThread::Track> track;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700267 sp<TrackHandle> trackHandle;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700268 sp<Client> client;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800269 wp<Client> wclient;
270 status_t lStatus;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 if (streamType >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800273 LOGE("invalid stream type");
274 lStatus = BAD_VALUE;
275 goto Exit;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700276 }
277
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800278 {
279 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-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 Projectf013e1a2008-12-17 18:05:43 -0800286
The Android Open Source Projectf013e1a2008-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 Laurenta553c252009-07-17 12:17:14 -0700295 track = thread->createTrack_l(client, streamType, sampleRate, format,
296 channelCount, frameCount, sharedBuffer, &lStatus);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700297 }
298 if (lStatus == NO_ERROR) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800299 trackHandle = new TrackHandle(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700300 } else {
301 track.clear();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800302 }
303
304Exit:
305 if(status) {
306 *status = lStatus;
307 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700308 return trackHandle;
309}
310
Eric Laurentddb78e72009-07-28 08:44:33 -0700311uint32_t AudioFlinger::sampleRate(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700312{
Eric Laurenta553c252009-07-17 12:17:14 -0700313 Mutex::Autolock _l(mLock);
314 PlaybackThread *thread = checkPlaybackThread_l(output);
315 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700316 LOGW("sampleRate() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700317 return 0;
318 }
319 return thread->sampleRate();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700320}
321
Eric Laurentddb78e72009-07-28 08:44:33 -0700322int AudioFlinger::channelCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700323{
Eric Laurenta553c252009-07-17 12:17:14 -0700324 Mutex::Autolock _l(mLock);
325 PlaybackThread *thread = checkPlaybackThread_l(output);
326 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700327 LOGW("channelCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700328 return 0;
329 }
330 return thread->channelCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700331}
332
Eric Laurentddb78e72009-07-28 08:44:33 -0700333int AudioFlinger::format(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700334{
Eric Laurenta553c252009-07-17 12:17:14 -0700335 Mutex::Autolock _l(mLock);
336 PlaybackThread *thread = checkPlaybackThread_l(output);
337 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700338 LOGW("format() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700339 return 0;
340 }
341 return thread->format();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700342}
343
Eric Laurentddb78e72009-07-28 08:44:33 -0700344size_t AudioFlinger::frameCount(int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700345{
Eric Laurenta553c252009-07-17 12:17:14 -0700346 Mutex::Autolock _l(mLock);
347 PlaybackThread *thread = checkPlaybackThread_l(output);
348 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700349 LOGW("frameCount() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700350 return 0;
351 }
352 return thread->frameCount();
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700353}
354
Eric Laurentddb78e72009-07-28 08:44:33 -0700355uint32_t AudioFlinger::latency(int output) const
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800356{
Eric Laurenta553c252009-07-17 12:17:14 -0700357 Mutex::Autolock _l(mLock);
358 PlaybackThread *thread = checkPlaybackThread_l(output);
359 if (thread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700360 LOGW("latency() unknown thread %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -0700361 return 0;
362 }
363 return thread->latency();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800364}
365
The Android Open Source Project54b6cfa2008-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 Project9066cfe2009-03-03 19:31:44 -0800377 value = 1.0f;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700378 }
379 mHardwareStatus = AUDIO_HW_IDLE;
Eric Laurenta553c252009-07-17 12:17:14 -0700380
381 mMasterVolume = value;
382 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700383 mPlaybackThreads.valueAt(i)->setMasterVolume(value);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700384
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700385 return NO_ERROR;
386}
387
The Android Open Source Project54b6cfa2008-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 Project54b6cfa2008-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 Laurenta553c252009-07-17 12:17:14 -0700435
436 mMasterMute = muted;
437 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700438 mPlaybackThreads.valueAt(i)->setMasterMute(muted);
Eric Laurenta553c252009-07-17 12:17:14 -0700439
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700440 return NO_ERROR;
441}
442
443float AudioFlinger::masterVolume() const
444{
Eric Laurenta553c252009-07-17 12:17:14 -0700445 return mMasterVolume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700446}
447
448bool AudioFlinger::masterMute() const
449{
Eric Laurenta553c252009-07-17 12:17:14 -0700450 return mMasterMute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700451}
452
Eric Laurentddb78e72009-07-28 08:44:33 -0700453status_t AudioFlinger::setStreamVolume(int stream, float value, int output)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700454{
455 // check calling permissions
456 if (!settingsAllowed()) {
457 return PERMISSION_DENIED;
458 }
459
Eric Laurenta553c252009-07-17 12:17:14 -0700460 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700461 return BAD_VALUE;
462 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -0800463
Eric Laurenta553c252009-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 Project54b6cfa2008-10-21 07:00:00 -0700473 status_t ret = NO_ERROR;
Eric Laurenta553c252009-07-17 12:17:14 -0700474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 if (stream == AudioSystem::VOICE_CALL ||
476 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurentef028272009-04-21 07:56:33 -0700477 float hwValue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 if (stream == AudioSystem::VOICE_CALL) {
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700479 hwValue = (float)AudioSystem::logToLinear(value)/100.0f;
Eric Laurentef028272009-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 Project9066cfe2009-03-03 19:31:44 -0800483 } else { // (type == AudioSystem::BLUETOOTH_SCO)
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700484 hwValue = 1.0f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 }
486
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700487 AutoMutex lock(mHardwareLock);
488 mHardwareStatus = AUDIO_SET_VOICE_VOLUME;
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700489 ret = mAudioHardware->setVoiceVolume(hwValue);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700490 mHardwareStatus = AUDIO_HW_IDLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491
Eric Laurenta553c252009-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 Laurentddb78e72009-07-28 08:44:33 -0700498 mPlaybackThreads.valueAt(i)->setStreamVolume(stream, value);
Eric Laurenta553c252009-07-17 12:17:14 -0700499
500 } else {
501 thread->setStreamVolume(stream, value);
502 }
Eric Laurentef028272009-04-21 07:56:33 -0700503
The Android Open Source Project54b6cfa2008-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 Laurenta553c252009-07-17 12:17:14 -0700514 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES ||
Eric Laurenteeea9222009-03-26 01:57:59 -0700515 uint32_t(stream) == AudioSystem::ENFORCED_AUDIBLE) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700516 return BAD_VALUE;
517 }
The Android Open Source Project10592532009-03-18 17:39:46 -0700518
Eric Laurenta553c252009-07-17 12:17:14 -0700519 mStreamTypes[stream].mute = muted;
520 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++)
Eric Laurentddb78e72009-07-28 08:44:33 -0700521 mPlaybackThreads.valueAt(i)->setStreamMute(stream, muted);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700523 return NO_ERROR;
524}
525
Eric Laurentddb78e72009-07-28 08:44:33 -0700526float AudioFlinger::streamVolume(int stream, int output) const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700527{
Eric Laurenta553c252009-07-17 12:17:14 -0700528 if (stream < 0 || uint32_t(stream) >= AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700529 return 0.0f;
530 }
Eric Laurenta553c252009-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 Laurentef028272009-04-21 07:56:33 -0700544 // remove correction applied by setStreamVolume()
Jean-Baptiste Queru2a73de72009-03-18 11:33:14 -0700545 if (stream == AudioSystem::VOICE_CALL) {
Eric Laurentef028272009-04-21 07:56:33 -0700546 volume = (volume - 0.01) / 0.99 ;
James E. Blair90329a62009-01-17 13:30:20 -0800547 }
Eric Laurenta553c252009-07-17 12:17:14 -0700548
Eric Laurentef028272009-04-21 07:56:33 -0700549 return volume;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700550}
551
552bool AudioFlinger::streamMute(int stream) const
553{
Eric Laurenta553c252009-07-17 12:17:14 -0700554 if (stream < 0 || stream >= (int)AudioSystem::NUM_STREAM_TYPES) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700555 return true;
556 }
Eric Laurenta553c252009-07-17 12:17:14 -0700557
558 return mStreamTypes[stream].mute;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700559}
560
561bool AudioFlinger::isMusicActive() const
562{
Eric Laurent4e646332009-07-09 03:20:57 -0700563 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700564 for (uint32_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700565 if (mPlaybackThreads.valueAt(i)->isMusicActive()) {
Eric Laurenta553c252009-07-17 12:17:14 -0700566 return true;
567 }
568 }
569 return false;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700570}
571
Eric Laurentddb78e72009-07-28 08:44:33 -0700572status_t AudioFlinger::setParameters(int ioHandle, const String8& keyValuePairs)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700573{
Eric Laurenta553c252009-07-17 12:17:14 -0700574 status_t result;
575
Eric Laurentddb78e72009-07-28 08:44:33 -0700576 LOGV("setParameters(): io %d, keyvalue %s, tid %d, calling tid %d",
Eric Laurenta553c252009-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 Project9266c552009-01-15 16:12:10 -0800581 }
Eric Laurenta553c252009-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 Laurentddb78e72009-07-28 08:44:33 -0700607String8 AudioFlinger::getParameters(int ioHandle, const String8& keys)
Eric Laurenta553c252009-07-17 12:17:14 -0700608{
Eric Laurentddb78e72009-07-28 08:44:33 -0700609// LOGV("getParameters() io %d, keys %s, tid %d, calling tid %d",
Eric Laurenta553c252009-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 Project54b6cfa2008-10-21 07:00:00 -0700624}
625
The Android Open Source Project9066cfe2009-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 Laurenta553c252009-07-17 12:17:14 -0700633
The Android Open Source Project9066cfe2009-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 Laurenta553c252009-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 Laurentddb78e72009-07-28 08:44:33 -0700647 mPlaybackThreads.valueAt(i)->sendConfigEvent(AudioSystem::OUTPUT_OPENED);
Eric Laurenta553c252009-07-17 12:17:14 -0700648 }
649
650 for (size_t i = 0; i < mRecordThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -0700651 mRecordThreads.valueAt(i)->sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 }
653}
654
655void AudioFlinger::binderDied(const wp<IBinder>& who) {
Eric Laurenta553c252009-07-17 12:17:14 -0700656
The Android Open Source Project9066cfe2009-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 Laurentddb78e72009-07-28 08:44:33 -0700671void AudioFlinger::audioConfigChanged(int event, const sp<ThreadBase>& thread, void *param2) {
Eric Laurenta553c252009-07-17 12:17:14 -0700672 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-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 Laurenta553c252009-07-17 12:17:14 -0700698 }
699}
700
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700701void AudioFlinger::removeClient(pid_t pid)
702{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 LOGV("removeClient() pid %d, tid %d, calling tid %d", pid, gettid(), IPCThreadState::self()->getCallingPid());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700704 Mutex::Autolock _l(mLock);
705 mClients.removeItem(pid);
706}
707
Eric Laurenta553c252009-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),
Eric Laurent8fce46a2009-08-04 09:45:33 -0700713 mFormat(0), mFrameSize(1), mStandby(false)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -0700714{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715}
716
Eric Laurenta553c252009-07-17 12:17:14 -0700717AudioFlinger::ThreadBase::~ThreadBase()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700719 mParamCond.broadcast();
720 mNewParameters.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721}
722
Eric Laurenta553c252009-07-17 12:17:14 -0700723void AudioFlinger::ThreadBase::exit()
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700724{
Eric Laurenta553c252009-07-17 12:17:14 -0700725 // keep a strong ref on ourself so that we want get
726 // destroyed in the middle of requestExitAndWait()
727 sp <ThreadBase> strongMe = this;
728
729 LOGV("ThreadBase::exit");
730 {
731 AutoMutex lock(&mLock);
732 requestExit();
733 mWaitWorkCV.signal();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700734 }
Eric Laurenta553c252009-07-17 12:17:14 -0700735 requestExitAndWait();
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -0700736}
Eric Laurenta553c252009-07-17 12:17:14 -0700737
738uint32_t AudioFlinger::ThreadBase::sampleRate() const
739{
740 return mSampleRate;
741}
742
743int AudioFlinger::ThreadBase::channelCount() const
744{
745 return mChannelCount;
746}
747
748int AudioFlinger::ThreadBase::format() const
749{
750 return mFormat;
751}
752
753size_t AudioFlinger::ThreadBase::frameCount() const
754{
755 return mFrameCount;
756}
757
758status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
759{
Eric Laurent8fce46a2009-08-04 09:45:33 -0700760 status_t status;
Eric Laurenta553c252009-07-17 12:17:14 -0700761
Eric Laurent8fce46a2009-08-04 09:45:33 -0700762 LOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
Eric Laurenta553c252009-07-17 12:17:14 -0700763 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -0700764
Eric Laurent8fce46a2009-08-04 09:45:33 -0700765 mNewParameters.add(keyValuePairs);
Eric Laurenta553c252009-07-17 12:17:14 -0700766 mWaitWorkCV.signal();
767 mParamCond.wait(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700768 status = mParamStatus;
769 mWaitWorkCV.signal();
770 return status;
Eric Laurenta553c252009-07-17 12:17:14 -0700771}
772
773void AudioFlinger::ThreadBase::sendConfigEvent(int event, int param)
774{
775 Mutex::Autolock _l(mLock);
Eric Laurent8fce46a2009-08-04 09:45:33 -0700776 sendConfigEvent_l(event, param);
777}
778
779// sendConfigEvent_l() must be called with ThreadBase::mLock held
780void AudioFlinger::ThreadBase::sendConfigEvent_l(int event, int param)
781{
Eric Laurenta553c252009-07-17 12:17:14 -0700782 ConfigEvent *configEvent = new ConfigEvent();
783 configEvent->mEvent = event;
784 configEvent->mParam = param;
785 mConfigEvents.add(configEvent);
786 LOGV("sendConfigEvent() num events %d event %d, param %d", mConfigEvents.size(), event, param);
787 mWaitWorkCV.signal();
788}
789
790void AudioFlinger::ThreadBase::processConfigEvents()
791{
792 mLock.lock();
793 while(!mConfigEvents.isEmpty()) {
794 LOGV("processConfigEvents() remaining events %d", mConfigEvents.size());
795 ConfigEvent *configEvent = mConfigEvents[0];
796 mConfigEvents.removeAt(0);
797 // release mLock because audioConfigChanged() will call
798 // Audioflinger::audioConfigChanged() which locks AudioFlinger mLock thus creating
799 // potential cross deadlock between AudioFlinger::mLock and mLock
800 mLock.unlock();
801 audioConfigChanged(configEvent->mEvent, configEvent->mParam);
802 delete configEvent;
803 mLock.lock();
804 }
805 mLock.unlock();
806}
807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808
809// ----------------------------------------------------------------------------
810
Eric Laurenta553c252009-07-17 12:17:14 -0700811AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
812 : ThreadBase(audioFlinger),
Eric Laurentd5603c12009-08-06 08:49:39 -0700813 mMixBuffer(0), mSuspended(0), mBytesWritten(0), mOutput(output),
Eric Laurent2c817f52009-07-23 13:17:39 -0700814 mLastWriteTime(0), mNumWrites(0), mNumDelayedWrites(0), mInWrite(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815{
Eric Laurenta553c252009-07-17 12:17:14 -0700816 readOutputParameters();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817
Eric Laurenta553c252009-07-17 12:17:14 -0700818 mMasterVolume = mAudioFlinger->masterVolume();
819 mMasterMute = mAudioFlinger->masterMute();
820
821 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
822 mStreamTypes[stream].volume = mAudioFlinger->streamVolumeInternal(stream);
823 mStreamTypes[stream].mute = mAudioFlinger->streamMute(stream);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 }
Eric Laurenta553c252009-07-17 12:17:14 -0700825 // notify client processes that a new input has been opened
826 sendConfigEvent(AudioSystem::OUTPUT_OPENED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827}
828
Eric Laurenta553c252009-07-17 12:17:14 -0700829AudioFlinger::PlaybackThread::~PlaybackThread()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830{
831 delete [] mMixBuffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832}
833
Eric Laurenta553c252009-07-17 12:17:14 -0700834status_t AudioFlinger::PlaybackThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835{
836 dumpInternals(fd, args);
837 dumpTracks(fd, args);
838 return NO_ERROR;
839}
840
Eric Laurenta553c252009-07-17 12:17:14 -0700841status_t AudioFlinger::PlaybackThread::dumpTracks(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842{
843 const size_t SIZE = 256;
844 char buffer[SIZE];
845 String8 result;
846
Eric Laurenta553c252009-07-17 12:17:14 -0700847 snprintf(buffer, SIZE, "Output thread %p tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 result.append(buffer);
849 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
850 for (size_t i = 0; i < mTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -0700851 sp<Track> track = mTracks[i];
852 if (track != 0) {
853 track->dump(buffer, SIZE);
854 result.append(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 }
857
Eric Laurenta553c252009-07-17 12:17:14 -0700858 snprintf(buffer, SIZE, "Output thread %p active tracks\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 result.append(buffer);
860 result.append(" Name Clien Typ Fmt Chn Buf S M F SRate LeftV RighV Serv User\n");
861 for (size_t i = 0; i < mActiveTracks.size(); ++i) {
Eric Laurentd3b4d0c2009-03-31 14:34:35 -0700862 wp<Track> wTrack = mActiveTracks[i];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 if (wTrack != 0) {
864 sp<Track> track = wTrack.promote();
865 if (track != 0) {
866 track->dump(buffer, SIZE);
867 result.append(buffer);
868 }
869 }
870 }
871 write(fd, result.string(), result.size());
872 return NO_ERROR;
873}
874
Eric Laurenta553c252009-07-17 12:17:14 -0700875status_t AudioFlinger::PlaybackThread::dumpInternals(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876{
877 const size_t SIZE = 256;
878 char buffer[SIZE];
879 String8 result;
880
Eric Laurenta553c252009-07-17 12:17:14 -0700881 snprintf(buffer, SIZE, "Output thread %p internals\n", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 result.append(buffer);
883 snprintf(buffer, SIZE, "last write occurred (msecs): %llu\n", ns2ms(systemTime() - mLastWriteTime));
884 result.append(buffer);
885 snprintf(buffer, SIZE, "total writes: %d\n", mNumWrites);
886 result.append(buffer);
887 snprintf(buffer, SIZE, "delayed writes: %d\n", mNumDelayedWrites);
888 result.append(buffer);
889 snprintf(buffer, SIZE, "blocked in write: %d\n", mInWrite);
890 result.append(buffer);
891 snprintf(buffer, SIZE, "standby: %d\n", mStandby);
892 result.append(buffer);
893 write(fd, result.string(), result.size());
894 return NO_ERROR;
895}
896
897// Thread virtuals
Eric Laurenta553c252009-07-17 12:17:14 -0700898status_t AudioFlinger::PlaybackThread::readyToRun()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899{
900 if (mSampleRate == 0) {
901 LOGE("No working audio driver found.");
902 return NO_INIT;
903 }
Eric Laurenta553c252009-07-17 12:17:14 -0700904 LOGI("AudioFlinger's thread %p ready to run", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 return NO_ERROR;
906}
907
Eric Laurenta553c252009-07-17 12:17:14 -0700908void AudioFlinger::PlaybackThread::onFirstRef()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909{
910 const size_t SIZE = 256;
911 char buffer[SIZE];
912
Eric Laurenta553c252009-07-17 12:17:14 -0700913 snprintf(buffer, SIZE, "Playback Thread %p", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914
915 run(buffer, ANDROID_PRIORITY_URGENT_AUDIO);
916}
917
Eric Laurenta553c252009-07-17 12:17:14 -0700918// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
919sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 const sp<AudioFlinger::Client>& client,
921 int streamType,
922 uint32_t sampleRate,
923 int format,
924 int channelCount,
925 int frameCount,
926 const sp<IMemory>& sharedBuffer,
927 status_t *status)
928{
929 sp<Track> track;
930 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -0700931
932 if (mType == DIRECT) {
933 if (sampleRate != mSampleRate || format != mFormat || channelCount != mChannelCount) {
934 LOGE("createTrack_l() Bad parameter: sampleRate %d format %d, channelCount %d for output %p",
935 sampleRate, format, channelCount, mOutput);
936 lStatus = BAD_VALUE;
937 goto Exit;
938 }
939 } else {
940 // Resampler implementation limits input sampling rate to 2 x output sampling rate.
941 if (sampleRate > mSampleRate*2) {
942 LOGE("Sample rate out of range: %d mSampleRate %d", sampleRate, mSampleRate);
943 lStatus = BAD_VALUE;
944 goto Exit;
945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
947
Eric Laurenta553c252009-07-17 12:17:14 -0700948 if (mOutput == 0) {
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700949 LOGE("Audio driver not initialized.");
950 lStatus = NO_INIT;
951 goto Exit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
953
Eric Laurenta553c252009-07-17 12:17:14 -0700954 { // scope for mLock
955 Mutex::Autolock _l(mLock);
956 track = new Track(this, client, streamType, sampleRate, format,
957 channelCount, frameCount, sharedBuffer);
958 if (track->getCblk() == NULL) {
959 lStatus = NO_MEMORY;
960 goto Exit;
961 }
962 mTracks.add(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700963 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -0700964 lStatus = NO_ERROR;
965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966Exit:
967 if(status) {
968 *status = lStatus;
969 }
970 return track;
971}
972
Eric Laurenta553c252009-07-17 12:17:14 -0700973uint32_t AudioFlinger::PlaybackThread::latency() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974{
975 if (mOutput) {
976 return mOutput->latency();
977 }
978 else {
979 return 0;
980 }
981}
982
Eric Laurenta553c252009-07-17 12:17:14 -0700983status_t AudioFlinger::PlaybackThread::setMasterVolume(float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984{
985 mMasterVolume = value;
986 return NO_ERROR;
987}
988
Eric Laurenta553c252009-07-17 12:17:14 -0700989status_t AudioFlinger::PlaybackThread::setMasterMute(bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990{
991 mMasterMute = muted;
992 return NO_ERROR;
993}
994
Eric Laurenta553c252009-07-17 12:17:14 -0700995float AudioFlinger::PlaybackThread::masterVolume() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996{
997 return mMasterVolume;
998}
999
Eric Laurenta553c252009-07-17 12:17:14 -07001000bool AudioFlinger::PlaybackThread::masterMute() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001{
1002 return mMasterMute;
1003}
1004
Eric Laurenta553c252009-07-17 12:17:14 -07001005status_t AudioFlinger::PlaybackThread::setStreamVolume(int stream, float value)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006{
1007 mStreamTypes[stream].volume = value;
1008 return NO_ERROR;
1009}
1010
Eric Laurenta553c252009-07-17 12:17:14 -07001011status_t AudioFlinger::PlaybackThread::setStreamMute(int stream, bool muted)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012{
1013 mStreamTypes[stream].mute = muted;
1014 return NO_ERROR;
1015}
1016
Eric Laurenta553c252009-07-17 12:17:14 -07001017float AudioFlinger::PlaybackThread::streamVolume(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018{
1019 return mStreamTypes[stream].volume;
1020}
1021
Eric Laurenta553c252009-07-17 12:17:14 -07001022bool AudioFlinger::PlaybackThread::streamMute(int stream) const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023{
1024 return mStreamTypes[stream].mute;
1025}
1026
Eric Laurenta553c252009-07-17 12:17:14 -07001027bool AudioFlinger::PlaybackThread::isMusicActive() const
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028{
Eric Laurenta553c252009-07-17 12:17:14 -07001029 Mutex::Autolock _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 size_t count = mActiveTracks.size();
1031 for (size_t i = 0 ; i < count ; ++i) {
1032 sp<Track> t = mActiveTracks[i].promote();
1033 if (t == 0) continue;
1034 Track* const track = t.get();
Eric Laurent2c817f52009-07-23 13:17:39 -07001035 if (t->type() == AudioSystem::MUSIC)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 return true;
1037 }
1038 return false;
1039}
1040
Eric Laurenta553c252009-07-17 12:17:14 -07001041// addTrack_l() must be called with ThreadBase::mLock held
1042status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043{
1044 status_t status = ALREADY_EXISTS;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001045
1046 // here the track could be either new, or restarted
1047 // in both cases "unstop" the track
1048 if (track->isPaused()) {
1049 track->mState = TrackBase::RESUMING;
1050 LOGV("PAUSED => RESUMING (%d)", track->name());
1051 } else {
1052 track->mState = TrackBase::ACTIVE;
1053 LOGV("? => ACTIVE (%d)", track->name());
1054 }
1055 // set retry count for buffer fill
1056 track->mRetryCount = kMaxTrackStartupRetries;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001057 if (mActiveTracks.indexOf(track) < 0) {
1058 // the track is newly added, make sure it fills up all its
1059 // buffers before playing. This is to ensure the client will
1060 // effectively get the latency it requested.
1061 track->mFillingUpStatus = Track::FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001062 track->mResetDone = false;
Eric Laurenta553c252009-07-17 12:17:14 -07001063 mActiveTracks.add(track);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 status = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001065 }
Eric Laurenta553c252009-07-17 12:17:14 -07001066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 LOGV("mWaitWorkCV.broadcast");
Eric Laurenta553c252009-07-17 12:17:14 -07001068 mWaitWorkCV.broadcast();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069
1070 return status;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001071}
1072
Eric Laurenta553c252009-07-17 12:17:14 -07001073// destroyTrack_l() must be called with ThreadBase::mLock held
1074void AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001075{
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001076 track->mState = TrackBase::TERMINATED;
1077 if (mActiveTracks.indexOf(track) < 0) {
1078 LOGV("remove track (%d) and delete from mixer", track->name());
1079 mTracks.remove(track);
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001080 deleteTrackName_l(track->name());
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001081 }
1082}
1083
Eric Laurenta553c252009-07-17 12:17:14 -07001084String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001085{
Eric Laurenta553c252009-07-17 12:17:14 -07001086 return mOutput->getParameters(keys);
1087}
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001088
Eric Laurenta553c252009-07-17 12:17:14 -07001089void AudioFlinger::PlaybackThread::audioConfigChanged(int event, int param) {
1090 AudioSystem::OutputDescriptor desc;
1091 void *param2 = 0;
1092
1093 LOGV("PlaybackThread::audioConfigChanged, thread %p, event %d, param %d", this, event, param);
1094
1095 switch (event) {
1096 case AudioSystem::OUTPUT_OPENED:
1097 case AudioSystem::OUTPUT_CONFIG_CHANGED:
1098 desc.channels = mChannelCount;
1099 desc.samplingRate = mSampleRate;
1100 desc.format = mFormat;
1101 desc.frameCount = mFrameCount;
1102 desc.latency = latency();
1103 param2 = &desc;
1104 break;
1105
1106 case AudioSystem::STREAM_CONFIG_CHANGED:
1107 param2 = &param;
1108 case AudioSystem::OUTPUT_CLOSED:
1109 default:
1110 break;
1111 }
1112 mAudioFlinger->audioConfigChanged(event, this, param2);
1113}
1114
1115void AudioFlinger::PlaybackThread::readOutputParameters()
1116{
1117 mSampleRate = mOutput->sampleRate();
1118 mChannelCount = AudioSystem::popCount(mOutput->channels());
1119
1120 mFormat = mOutput->format();
1121 mFrameSize = mOutput->frameSize();
1122 mFrameCount = mOutput->bufferSize() / mFrameSize;
1123
1124 mMinBytesToWrite = (mOutput->latency() * mSampleRate * mFrameSize) / 1000;
1125 // FIXME - Current mixer implementation only supports stereo output: Always
1126 // Allocate a stereo buffer even if HW output is mono.
1127 if (mMixBuffer != NULL) delete mMixBuffer;
1128 mMixBuffer = new int16_t[mFrameCount * 2];
1129 memset(mMixBuffer, 0, mFrameCount * 2 * sizeof(int16_t));
1130}
1131
1132// ----------------------------------------------------------------------------
1133
1134AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1135 : PlaybackThread(audioFlinger, output),
1136 mAudioMixer(0)
1137{
1138 mType = PlaybackThread::MIXER;
1139 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1140
1141 // FIXME - Current mixer implementation only supports stereo output
1142 if (mChannelCount == 1) {
1143 LOGE("Invalid audio hardware channel count");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001145}
1146
Eric Laurenta553c252009-07-17 12:17:14 -07001147AudioFlinger::MixerThread::~MixerThread()
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001148{
Eric Laurenta553c252009-07-17 12:17:14 -07001149 delete mAudioMixer;
1150}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151
Eric Laurenta553c252009-07-17 12:17:14 -07001152bool AudioFlinger::MixerThread::threadLoop()
1153{
1154 unsigned long sleepTime = kBufferRecoveryInUsecs;
1155 int16_t* curBuf = mMixBuffer;
1156 Vector< sp<Track> > tracksToRemove;
1157 size_t enabledTracks = 0;
1158 nsecs_t standbyTime = systemTime();
1159 size_t mixBufferSize = mFrameCount * mFrameSize;
1160 nsecs_t maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161
Eric Laurenta553c252009-07-17 12:17:14 -07001162 while (!exitPending())
1163 {
1164 processConfigEvents();
1165
1166 enabledTracks = 0;
1167 { // scope for mLock
1168
1169 Mutex::Autolock _l(mLock);
1170
1171 if (checkForNewParameters_l()) {
1172 mixBufferSize = mFrameCount * mFrameSize;
1173 maxPeriod = seconds(mFrameCount) / mSampleRate * 2;
1174 }
1175
1176 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1177
1178 // put audio hardware into standby after short delay
1179 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1180 mSuspended) {
1181 if (!mStandby) {
1182 LOGV("Audio hardware entering standby, mixer %p, mSuspended %d\n", this, mSuspended);
1183 mOutput->standby();
1184 mStandby = true;
1185 mBytesWritten = 0;
1186 }
1187
1188 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1189 // we're about to wait, flush the binder command buffer
1190 IPCThreadState::self()->flushCommands();
1191
1192 if (exitPending()) break;
1193
1194 // wait until we have something to do...
1195 LOGV("MixerThread %p TID %d going to sleep\n", this, gettid());
1196 mWaitWorkCV.wait(mLock);
1197 LOGV("MixerThread %p TID %d waking up\n", this, gettid());
1198
1199 if (mMasterMute == false) {
1200 char value[PROPERTY_VALUE_MAX];
1201 property_get("ro.audio.silent", value, "0");
1202 if (atoi(value)) {
1203 LOGD("Silence is golden");
1204 setMasterMute(true);
1205 }
1206 }
1207
1208 standbyTime = systemTime() + kStandbyTimeInNsecs;
1209 continue;
1210 }
1211 }
1212
1213 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1214 }
1215
1216 if (LIKELY(enabledTracks)) {
1217 // mix buffers...
1218 mAudioMixer->process(curBuf);
1219
1220 // output audio to hardware
1221 if (mSuspended) {
1222 usleep(kMaxBufferRecoveryInUsecs);
1223 } else {
1224 mLastWriteTime = systemTime();
1225 mInWrite = true;
1226 int bytesWritten = (int)mOutput->write(curBuf, mixBufferSize);
1227 if (bytesWritten > 0) mBytesWritten += bytesWritten;
1228 mNumWrites++;
1229 mInWrite = false;
1230 mStandby = false;
1231 nsecs_t temp = systemTime();
1232 standbyTime = temp + kStandbyTimeInNsecs;
1233 nsecs_t delta = temp - mLastWriteTime;
1234 if (delta > maxPeriod) {
1235 LOGW("write blocked for %llu msecs", ns2ms(delta));
1236 mNumDelayedWrites++;
1237 }
1238 sleepTime = kBufferRecoveryInUsecs;
1239 }
1240 } else {
1241 // There was nothing to mix this round, which means all
1242 // active tracks were late. Sleep a little bit to give
1243 // them another chance. If we're too late, the audio
1244 // hardware will zero-fill for us.
1245 // LOGV("thread %p no buffers - usleep(%lu)", this, sleepTime);
1246 usleep(sleepTime);
1247 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1248 sleepTime += kBufferRecoveryInUsecs;
1249 }
1250 }
1251
1252 // finally let go of all our tracks, without the lock held
1253 // since we can't guarantee the destructors won't acquire that
1254 // same lock.
1255 tracksToRemove.clear();
1256 }
1257
1258 if (!mStandby) {
1259 mOutput->standby();
1260 }
1261 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1262 processConfigEvents();
1263
1264 LOGV("MixerThread %p exiting", this);
1265 return false;
1266}
1267
1268// prepareTracks_l() must be called with ThreadBase::mLock held
1269size_t AudioFlinger::MixerThread::prepareTracks_l(const SortedVector< wp<Track> >& activeTracks, Vector< sp<Track> > *tracksToRemove)
1270{
1271
1272 size_t enabledTracks = 0;
1273 // find out which tracks need to be processed
1274 size_t count = activeTracks.size();
1275 for (size_t i=0 ; i<count ; i++) {
1276 sp<Track> t = activeTracks[i].promote();
1277 if (t == 0) continue;
1278
1279 Track* const track = t.get();
1280 audio_track_cblk_t* cblk = track->cblk();
1281
1282 // The first time a track is added we wait
1283 // for all its buffers to be filled before processing it
1284 mAudioMixer->setActiveTrack(track->name());
1285 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1286 !track->isPaused())
1287 {
1288 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1289
1290 // compute volume for this track
1291 int16_t left, right;
1292 if (track->isMuted() || mMasterMute || track->isPausing() ||
1293 mStreamTypes[track->type()].mute) {
1294 left = right = 0;
1295 if (track->isPausing()) {
1296 track->setPaused();
1297 }
1298 } else {
1299 float typeVolume = mStreamTypes[track->type()].volume;
1300 float v = mMasterVolume * typeVolume;
1301 float v_clamped = v * cblk->volume[0];
1302 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1303 left = int16_t(v_clamped);
1304 v_clamped = v * cblk->volume[1];
1305 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1306 right = int16_t(v_clamped);
1307 }
1308
1309 // XXX: these things DON'T need to be done each time
1310 mAudioMixer->setBufferProvider(track);
1311 mAudioMixer->enable(AudioMixer::MIXING);
1312
1313 int param;
1314 if ( track->mFillingUpStatus == Track::FS_FILLED) {
1315 // no ramp for the first volume setting
1316 track->mFillingUpStatus = Track::FS_ACTIVE;
1317 if (track->mState == TrackBase::RESUMING) {
1318 track->mState = TrackBase::ACTIVE;
1319 param = AudioMixer::RAMP_VOLUME;
1320 } else {
1321 param = AudioMixer::VOLUME;
1322 }
1323 } else {
1324 param = AudioMixer::RAMP_VOLUME;
1325 }
1326 mAudioMixer->setParameter(param, AudioMixer::VOLUME0, left);
1327 mAudioMixer->setParameter(param, AudioMixer::VOLUME1, right);
1328 mAudioMixer->setParameter(
1329 AudioMixer::TRACK,
1330 AudioMixer::FORMAT, track->format());
1331 mAudioMixer->setParameter(
1332 AudioMixer::TRACK,
1333 AudioMixer::CHANNEL_COUNT, track->channelCount());
1334 mAudioMixer->setParameter(
1335 AudioMixer::RESAMPLE,
1336 AudioMixer::SAMPLE_RATE,
1337 int(cblk->sampleRate));
1338
1339 // reset retry count
1340 track->mRetryCount = kMaxTrackRetries;
1341 enabledTracks++;
1342 } else {
1343 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1344 if (track->isStopped()) {
1345 track->reset();
1346 }
1347 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1348 // We have consumed all the buffers of this track.
1349 // Remove it from the list of active tracks.
1350 tracksToRemove->add(track);
1351 mAudioMixer->disable(AudioMixer::MIXING);
1352 } else {
1353 // No buffers for this track. Give it a few chances to
1354 // fill a buffer, then remove it from active list.
1355 if (--(track->mRetryCount) <= 0) {
1356 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1357 tracksToRemove->add(track);
1358 }
1359 // For tracks using static shared memry buffer, make sure that we have
1360 // written enough data to audio hardware before disabling the track
1361 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1362 // don't care about code removing track from active list above.
1363 if ((track->mSharedBuffer == 0) || (mBytesWritten >= mMinBytesToWrite)) {
1364 mAudioMixer->disable(AudioMixer::MIXING);
1365 } else {
1366 enabledTracks++;
1367 }
1368 }
1369 }
1370 }
1371
1372 // remove all the tracks that need to be...
1373 count = tracksToRemove->size();
1374 if (UNLIKELY(count)) {
1375 for (size_t i=0 ; i<count ; i++) {
1376 const sp<Track>& track = tracksToRemove->itemAt(i);
1377 mActiveTracks.remove(track);
1378 if (track->isTerminated()) {
1379 mTracks.remove(track);
1380 deleteTrackName_l(track->mName);
1381 }
1382 }
1383 }
1384
1385 return enabledTracks;
1386}
1387
1388void AudioFlinger::MixerThread::getTracks(
1389 SortedVector < sp<Track> >& tracks,
1390 SortedVector < wp<Track> >& activeTracks,
1391 int streamType)
1392{
1393 LOGV ("MixerThread::getTracks() mixer %p, mTracks.size %d, mActiveTracks.size %d", this, mTracks.size(), mActiveTracks.size());
1394 Mutex::Autolock _l(mLock);
1395 size_t size = mTracks.size();
1396 for (size_t i = 0; i < size; i++) {
1397 sp<Track> t = mTracks[i];
1398 if (t->type() == streamType) {
1399 tracks.add(t);
1400 int j = mActiveTracks.indexOf(t);
1401 if (j >= 0) {
1402 t = mActiveTracks[j].promote();
1403 if (t != NULL) {
1404 activeTracks.add(t);
1405 }
1406 }
1407 }
1408 }
1409
1410 size = activeTracks.size();
1411 for (size_t i = 0; i < size; i++) {
1412 mActiveTracks.remove(activeTracks[i]);
1413 }
1414
1415 size = tracks.size();
1416 for (size_t i = 0; i < size; i++) {
1417 sp<Track> t = tracks[i];
1418 mTracks.remove(t);
1419 deleteTrackName_l(t->name());
1420 }
1421}
1422
1423void AudioFlinger::MixerThread::putTracks(
1424 SortedVector < sp<Track> >& tracks,
1425 SortedVector < wp<Track> >& activeTracks)
1426{
1427 LOGV ("MixerThread::putTracks() mixer %p, tracks.size %d, activeTracks.size %d", this, tracks.size(), activeTracks.size());
1428 Mutex::Autolock _l(mLock);
1429 size_t size = tracks.size();
1430 for (size_t i = 0; i < size ; i++) {
1431 sp<Track> t = tracks[i];
1432 int name = getTrackName_l();
1433
1434 if (name < 0) return;
1435
1436 t->mName = name;
1437 t->mThread = this;
1438 mTracks.add(t);
1439
1440 int j = activeTracks.indexOf(t);
1441 if (j >= 0) {
1442 mActiveTracks.add(t);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
1444 }
1445}
1446
Eric Laurenta553c252009-07-17 12:17:14 -07001447// getTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001448int AudioFlinger::MixerThread::getTrackName_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449{
1450 return mAudioMixer->getTrackName();
1451}
1452
Eric Laurenta553c252009-07-17 12:17:14 -07001453// deleteTrackName_l() must be called with ThreadBase::mLock held
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001454void AudioFlinger::MixerThread::deleteTrackName_l(int name)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455{
1456 mAudioMixer->deleteTrackName(name);
1457}
1458
Eric Laurenta553c252009-07-17 12:17:14 -07001459// checkForNewParameters_l() must be called with ThreadBase::mLock held
1460bool AudioFlinger::MixerThread::checkForNewParameters_l()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461{
Eric Laurenta553c252009-07-17 12:17:14 -07001462 bool reconfig = false;
1463
Eric Laurent8fce46a2009-08-04 09:45:33 -07001464 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001465 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001466 String8 keyValuePair = mNewParameters[0];
1467 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001468 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001469
1470 mNewParameters.removeAt(0);
1471
Eric Laurenta553c252009-07-17 12:17:14 -07001472 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
1473 reconfig = true;
1474 }
1475 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
1476 if (value != AudioSystem::PCM_16_BIT) {
1477 status = BAD_VALUE;
1478 } else {
1479 reconfig = true;
1480 }
1481 }
1482 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
1483 if (value != AudioSystem::CHANNEL_OUT_STEREO) {
1484 status = BAD_VALUE;
1485 } else {
1486 reconfig = true;
1487 }
1488 }
1489 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1490 // do not accept frame count changes if tracks are open as the track buffer
1491 // size depends on frame count and correct behavior would not be garantied
1492 // if frame count is changed after track creation
1493 if (!mTracks.isEmpty()) {
1494 status = INVALID_OPERATION;
1495 } else {
1496 reconfig = true;
1497 }
1498 }
1499 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001500 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001501 if (!mStandby && status == INVALID_OPERATION) {
1502 mOutput->standby();
1503 mStandby = true;
1504 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001505 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001506 }
1507 if (status == NO_ERROR && reconfig) {
1508 delete mAudioMixer;
1509 readOutputParameters();
1510 mAudioMixer = new AudioMixer(mFrameCount, mSampleRate);
1511 for (size_t i = 0; i < mTracks.size() ; i++) {
1512 int name = getTrackName_l();
1513 if (name < 0) break;
1514 mTracks[i]->mName = name;
Eric Laurent6f7e0972009-08-10 08:15:12 -07001515 // limit track sample rate to 2 x new output sample rate
1516 if (mTracks[i]->mCblk->sampleRate > 2 * sampleRate()) {
1517 mTracks[i]->mCblk->sampleRate = 2 * sampleRate();
1518 }
Eric Laurenta553c252009-07-17 12:17:14 -07001519 }
Eric Laurent8fce46a2009-08-04 09:45:33 -07001520 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001521 }
1522 }
1523 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001524 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001525 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001526 }
1527 return reconfig;
1528}
1529
1530status_t AudioFlinger::MixerThread::dumpInternals(int fd, const Vector<String16>& args)
1531{
1532 const size_t SIZE = 256;
1533 char buffer[SIZE];
1534 String8 result;
1535
1536 PlaybackThread::dumpInternals(fd, args);
1537
1538 snprintf(buffer, SIZE, "AudioMixer tracks: %08x\n", mAudioMixer->trackNames());
1539 result.append(buffer);
1540 write(fd, result.string(), result.size());
1541 return NO_ERROR;
1542}
1543
1544// ----------------------------------------------------------------------------
1545AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output)
1546 : PlaybackThread(audioFlinger, output),
1547 mLeftVolume (1.0), mRightVolume(1.0)
1548{
1549 mType = PlaybackThread::DIRECT;
1550}
1551
1552AudioFlinger::DirectOutputThread::~DirectOutputThread()
1553{
1554}
1555
1556
1557bool AudioFlinger::DirectOutputThread::threadLoop()
1558{
1559 unsigned long sleepTime = kBufferRecoveryInUsecs;
1560 sp<Track> trackToRemove;
1561 sp<Track> activeTrack;
1562 nsecs_t standbyTime = systemTime();
1563 int8_t *curBuf;
1564 size_t mixBufferSize = mFrameCount*mFrameSize;
1565
1566 while (!exitPending())
1567 {
1568 processConfigEvents();
1569
1570 { // scope for the mLock
1571
1572 Mutex::Autolock _l(mLock);
1573
1574 if (checkForNewParameters_l()) {
1575 mixBufferSize = mFrameCount*mFrameSize;
1576 }
1577
1578 // put audio hardware into standby after short delay
1579 if UNLIKELY((!mActiveTracks.size() && systemTime() > standbyTime) ||
1580 mSuspended) {
1581 // wait until we have something to do...
1582 if (!mStandby) {
1583 LOGV("Audio hardware entering standby, mixer %p\n", this);
1584 mOutput->standby();
1585 mStandby = true;
1586 mBytesWritten = 0;
1587 }
1588
1589 if (!mActiveTracks.size() && mConfigEvents.isEmpty()) {
1590 // we're about to wait, flush the binder command buffer
1591 IPCThreadState::self()->flushCommands();
1592
1593 if (exitPending()) break;
1594
1595 LOGV("DirectOutputThread %p TID %d going to sleep\n", this, gettid());
1596 mWaitWorkCV.wait(mLock);
1597 LOGV("DirectOutputThread %p TID %d waking up in active mode\n", this, gettid());
1598
1599 if (mMasterMute == false) {
1600 char value[PROPERTY_VALUE_MAX];
1601 property_get("ro.audio.silent", value, "0");
1602 if (atoi(value)) {
1603 LOGD("Silence is golden");
1604 setMasterMute(true);
1605 }
1606 }
1607
1608 standbyTime = systemTime() + kStandbyTimeInNsecs;
1609 continue;
1610 }
1611 }
1612
1613 // find out which tracks need to be processed
1614 if (mActiveTracks.size() != 0) {
1615 sp<Track> t = mActiveTracks[0].promote();
1616 if (t == 0) continue;
1617
1618 Track* const track = t.get();
1619 audio_track_cblk_t* cblk = track->cblk();
1620
1621 // The first time a track is added we wait
1622 // for all its buffers to be filled before processing it
1623 if (cblk->framesReady() && (track->isReady() || track->isStopped()) &&
1624 !track->isPaused())
1625 {
1626 //LOGV("track %d u=%08x, s=%08x [OK]", track->name(), cblk->user, cblk->server);
1627
1628 // compute volume for this track
1629 float left, right;
1630 if (track->isMuted() || mMasterMute || track->isPausing() ||
1631 mStreamTypes[track->type()].mute) {
1632 left = right = 0;
1633 if (track->isPausing()) {
1634 track->setPaused();
1635 }
1636 } else {
1637 float typeVolume = mStreamTypes[track->type()].volume;
1638 float v = mMasterVolume * typeVolume;
1639 float v_clamped = v * cblk->volume[0];
1640 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1641 left = v_clamped/MAX_GAIN;
1642 v_clamped = v * cblk->volume[1];
1643 if (v_clamped > MAX_GAIN) v_clamped = MAX_GAIN;
1644 right = v_clamped/MAX_GAIN;
1645 }
1646
1647 if (left != mLeftVolume || right != mRightVolume) {
1648 mOutput->setVolume(left, right);
1649 left = mLeftVolume;
1650 right = mRightVolume;
1651 }
1652
1653 if (track->mFillingUpStatus == Track::FS_FILLED) {
1654 track->mFillingUpStatus = Track::FS_ACTIVE;
1655 if (track->mState == TrackBase::RESUMING) {
1656 track->mState = TrackBase::ACTIVE;
1657 }
1658 }
1659
1660 // reset retry count
1661 track->mRetryCount = kMaxTrackRetries;
1662 activeTrack = t;
1663 } else {
1664 //LOGV("track %d u=%08x, s=%08x [NOT READY]", track->name(), cblk->user, cblk->server);
1665 if (track->isStopped()) {
1666 track->reset();
1667 }
1668 if (track->isTerminated() || track->isStopped() || track->isPaused()) {
1669 // We have consumed all the buffers of this track.
1670 // Remove it from the list of active tracks.
1671 trackToRemove = track;
1672 } else {
1673 // No buffers for this track. Give it a few chances to
1674 // fill a buffer, then remove it from active list.
1675 if (--(track->mRetryCount) <= 0) {
1676 LOGV("BUFFER TIMEOUT: remove(%d) from active list", track->name());
1677 trackToRemove = track;
1678 }
1679
1680 // For tracks using static shared memry buffer, make sure that we have
1681 // written enough data to audio hardware before disabling the track
1682 // NOTE: this condition with arrive before track->mRetryCount <= 0 so we
1683 // don't care about code removing track from active list above.
1684 if ((track->mSharedBuffer != 0) && (mBytesWritten < mMinBytesToWrite)) {
1685 activeTrack = t;
1686 }
1687 }
1688 }
1689 }
1690
1691 // remove all the tracks that need to be...
1692 if (UNLIKELY(trackToRemove != 0)) {
1693 mActiveTracks.remove(trackToRemove);
1694 if (trackToRemove->isTerminated()) {
1695 mTracks.remove(trackToRemove);
1696 deleteTrackName_l(trackToRemove->mName);
1697 }
1698 }
1699 }
1700
1701 if (activeTrack != 0) {
1702 AudioBufferProvider::Buffer buffer;
1703 size_t frameCount = mFrameCount;
1704 curBuf = (int8_t *)mMixBuffer;
1705 // output audio to hardware
1706 mLastWriteTime = systemTime();
1707 mInWrite = true;
1708 while(frameCount) {
1709 buffer.frameCount = frameCount;
1710 activeTrack->getNextBuffer(&buffer);
1711 if (UNLIKELY(buffer.raw == 0)) {
1712 memset(curBuf, 0, frameCount * mFrameSize);
1713 break;
1714 }
1715 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
1716 frameCount -= buffer.frameCount;
1717 curBuf += buffer.frameCount * mFrameSize;
1718 activeTrack->releaseBuffer(&buffer);
1719 }
1720 if (mSuspended) {
1721 usleep(kMaxBufferRecoveryInUsecs);
1722 } else {
1723 int bytesWritten = (int)mOutput->write(mMixBuffer, mixBufferSize);
1724 if (bytesWritten) mBytesWritten += bytesWritten;
1725 mNumWrites++;
1726 mInWrite = false;
1727 mStandby = false;
1728 nsecs_t temp = systemTime();
1729 standbyTime = temp + kStandbyTimeInNsecs;
1730 sleepTime = kBufferRecoveryInUsecs;
1731 }
1732 } else {
1733 // There was nothing to mix this round, which means all
1734 // active tracks were late. Sleep a little bit to give
1735 // them another chance. If we're too late, the audio
1736 // hardware will zero-fill for us.
1737 //LOGV("no buffers - usleep(%lu)", sleepTime);
1738 usleep(sleepTime);
1739 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1740 sleepTime += kBufferRecoveryInUsecs;
1741 }
1742 }
1743
1744 // finally let go of removed track, without the lock held
1745 // since we can't guarantee the destructors won't acquire that
1746 // same lock.
1747 trackToRemove.clear();
1748 activeTrack.clear();
1749 }
1750
1751 if (!mStandby) {
1752 mOutput->standby();
1753 }
1754 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1755 processConfigEvents();
1756
1757 LOGV("DirectOutputThread %p exiting", this);
1758 return false;
1759}
1760
1761// getTrackName_l() must be called with ThreadBase::mLock held
1762int AudioFlinger::DirectOutputThread::getTrackName_l()
1763{
1764 return 0;
1765}
1766
1767// deleteTrackName_l() must be called with ThreadBase::mLock held
1768void AudioFlinger::DirectOutputThread::deleteTrackName_l(int name)
1769{
1770}
1771
1772// checkForNewParameters_l() must be called with ThreadBase::mLock held
1773bool AudioFlinger::DirectOutputThread::checkForNewParameters_l()
1774{
1775 bool reconfig = false;
1776
Eric Laurent8fce46a2009-08-04 09:45:33 -07001777 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07001778 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001779 String8 keyValuePair = mNewParameters[0];
1780 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001781 int value;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001782
1783 mNewParameters.removeAt(0);
1784
Eric Laurenta553c252009-07-17 12:17:14 -07001785 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
1786 // do not accept frame count changes if tracks are open as the track buffer
1787 // size depends on frame count and correct behavior would not be garantied
1788 // if frame count is changed after track creation
1789 if (!mTracks.isEmpty()) {
1790 status = INVALID_OPERATION;
1791 } else {
1792 reconfig = true;
1793 }
1794 }
1795 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07001796 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001797 if (!mStandby && status == INVALID_OPERATION) {
1798 mOutput->standby();
1799 mStandby = true;
1800 mBytesWritten = 0;
Eric Laurent8fce46a2009-08-04 09:45:33 -07001801 status = mOutput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07001802 }
1803 if (status == NO_ERROR && reconfig) {
1804 readOutputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001805 sendConfigEvent_l(AudioSystem::OUTPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07001806 }
1807 }
1808 mParamStatus = status;
Eric Laurenta553c252009-07-17 12:17:14 -07001809 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07001810 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07001811 }
1812 return reconfig;
The Android Open Source Projectf1e484a2009-01-22 00:13:42 -08001813}
1814
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001815// ----------------------------------------------------------------------------
1816
Eric Laurenta553c252009-07-17 12:17:14 -07001817AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger, AudioFlinger::MixerThread* mainThread)
1818 : MixerThread(audioFlinger, mainThread->getOutput())
1819{
1820 mType = PlaybackThread::DUPLICATING;
1821 addOutputTrack(mainThread);
1822}
1823
1824AudioFlinger::DuplicatingThread::~DuplicatingThread()
1825{
1826 mOutputTracks.clear();
1827}
1828
1829bool AudioFlinger::DuplicatingThread::threadLoop()
1830{
1831 unsigned long sleepTime = kBufferRecoveryInUsecs;
1832 int16_t* curBuf = mMixBuffer;
1833 Vector< sp<Track> > tracksToRemove;
1834 size_t enabledTracks = 0;
1835 nsecs_t standbyTime = systemTime();
1836 size_t mixBufferSize = mFrameCount*mFrameSize;
1837 SortedVector< sp<OutputTrack> > outputTracks;
1838
1839 while (!exitPending())
1840 {
1841 processConfigEvents();
1842
1843 enabledTracks = 0;
1844 { // scope for the mLock
1845
1846 Mutex::Autolock _l(mLock);
1847
1848 if (checkForNewParameters_l()) {
1849 mixBufferSize = mFrameCount*mFrameSize;
1850 }
1851
1852 const SortedVector< wp<Track> >& activeTracks = mActiveTracks;
1853
1854 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1855 outputTracks.add(mOutputTracks[i]);
1856 }
1857
1858 // put audio hardware into standby after short delay
1859 if UNLIKELY((!activeTracks.size() && systemTime() > standbyTime) ||
1860 mSuspended) {
1861 if (!mStandby) {
1862 for (size_t i = 0; i < outputTracks.size(); i++) {
1863 mLock.unlock();
1864 outputTracks[i]->stop();
1865 mLock.lock();
1866 }
1867 mStandby = true;
1868 mBytesWritten = 0;
1869 }
1870
1871 if (!activeTracks.size() && mConfigEvents.isEmpty()) {
1872 // we're about to wait, flush the binder command buffer
1873 IPCThreadState::self()->flushCommands();
1874 outputTracks.clear();
1875
1876 if (exitPending()) break;
1877
1878 LOGV("DuplicatingThread %p TID %d going to sleep\n", this, gettid());
1879 mWaitWorkCV.wait(mLock);
1880 LOGV("DuplicatingThread %p TID %d waking up\n", this, gettid());
1881 if (mMasterMute == false) {
1882 char value[PROPERTY_VALUE_MAX];
1883 property_get("ro.audio.silent", value, "0");
1884 if (atoi(value)) {
1885 LOGD("Silence is golden");
1886 setMasterMute(true);
1887 }
1888 }
1889
1890 standbyTime = systemTime() + kStandbyTimeInNsecs;
1891 sleepTime = kBufferRecoveryInUsecs;
1892 continue;
1893 }
1894 }
1895
1896 enabledTracks = prepareTracks_l(activeTracks, &tracksToRemove);
1897 }
1898
1899 bool mustSleep = true;
1900 if (LIKELY(enabledTracks)) {
1901 // mix buffers...
1902 mAudioMixer->process(curBuf);
1903 if (!mSuspended) {
1904 for (size_t i = 0; i < outputTracks.size(); i++) {
1905 outputTracks[i]->write(curBuf, mFrameCount);
1906 }
1907 mStandby = false;
1908 mustSleep = false;
1909 mBytesWritten += mixBufferSize;
1910 }
1911 } else {
1912 // flush remaining overflow buffers in output tracks
1913 for (size_t i = 0; i < outputTracks.size(); i++) {
1914 if (outputTracks[i]->isActive()) {
1915 outputTracks[i]->write(curBuf, 0);
1916 standbyTime = systemTime() + kStandbyTimeInNsecs;
1917 mustSleep = false;
1918 }
1919 }
1920 }
1921 if (mustSleep) {
1922// LOGV("threadLoop() sleeping %d", sleepTime);
1923 usleep(sleepTime);
1924 if (sleepTime < kMaxBufferRecoveryInUsecs) {
1925 sleepTime += kBufferRecoveryInUsecs;
1926 }
1927 } else {
1928 sleepTime = kBufferRecoveryInUsecs;
1929 }
1930
1931 // finally let go of all our tracks, without the lock held
1932 // since we can't guarantee the destructors won't acquire that
1933 // same lock.
1934 tracksToRemove.clear();
1935 outputTracks.clear();
1936 }
1937
1938 if (!mStandby) {
1939 for (size_t i = 0; i < outputTracks.size(); i++) {
1940 mLock.unlock();
1941 outputTracks[i]->stop();
1942 mLock.lock();
1943 }
1944 }
1945
1946 sendConfigEvent(AudioSystem::OUTPUT_CLOSED);
1947 processConfigEvents();
1948
1949 return false;
1950}
1951
1952void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
1953{
1954 int frameCount = (3 * mFrameCount * mSampleRate) / thread->sampleRate();
1955 OutputTrack *outputTrack = new OutputTrack((ThreadBase *)thread,
1956 mSampleRate,
1957 mFormat,
1958 mChannelCount,
1959 frameCount);
1960 thread->setStreamVolume(AudioSystem::NUM_STREAM_TYPES, 1.0f);
1961 mOutputTracks.add(outputTrack);
1962 LOGV("addOutputTrack() track %p, on thread %p", outputTrack, thread);
1963}
1964
1965void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
1966{
1967 Mutex::Autolock _l(mLock);
1968 for (size_t i = 0; i < mOutputTracks.size(); i++) {
1969 if (mOutputTracks[i]->thread() == (ThreadBase *)thread) {
1970 mOutputTracks.removeAt(i);
1971 return;
1972 }
1973 }
1974 LOGV("removeOutputTrack(): unkonwn thread: %p", thread);
1975}
1976
1977
1978// ----------------------------------------------------------------------------
1979
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07001980// TrackBase constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07001981AudioFlinger::ThreadBase::TrackBase::TrackBase(
1982 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001983 const sp<Client>& client,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001984 uint32_t sampleRate,
1985 int format,
1986 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001987 int frameCount,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 uint32_t flags,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001989 const sp<IMemory>& sharedBuffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001990 : RefBase(),
Eric Laurenta553c252009-07-17 12:17:14 -07001991 mThread(thread),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001992 mClient(client),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001993 mFrameCount(0),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001994 mState(IDLE),
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001995 mClientTid(-1),
1996 mFormat(format),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 mFlags(flags & ~SYSTEM_FLAGS_MASK)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07001998{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08001999 LOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), sharedBuffer->size());
2000
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002001 // LOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002002 size_t size = sizeof(audio_track_cblk_t);
2003 size_t bufferSize = frameCount*channelCount*sizeof(int16_t);
2004 if (sharedBuffer == 0) {
2005 size += bufferSize;
2006 }
2007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 if (client != NULL) {
2009 mCblkMemory = client->heap()->allocate(size);
2010 if (mCblkMemory != 0) {
2011 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
2012 if (mCblk) { // construct the shared structure in-place.
2013 new(mCblk) audio_track_cblk_t();
2014 // clear all buffers
2015 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002016 mCblk->sampleRate = sampleRate;
2017 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 if (sharedBuffer == 0) {
2019 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2020 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2021 // Force underrun condition to avoid false underrun callback until first data is
2022 // written to buffer
2023 mCblk->flowControlFlag = 1;
2024 } else {
2025 mBuffer = sharedBuffer->pointer();
2026 }
2027 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 } else {
2030 LOGE("not enough memory for AudioTrack size=%u", size);
2031 client->heap()->dump("AudioTrack");
2032 return;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 } else {
2035 mCblk = (audio_track_cblk_t *)(new uint8_t[size]);
2036 if (mCblk) { // construct the shared structure in-place.
2037 new(mCblk) audio_track_cblk_t();
2038 // clear all buffers
2039 mCblk->frameCount = frameCount;
Eric Laurent88e209d2009-07-07 07:10:45 -07002040 mCblk->sampleRate = sampleRate;
2041 mCblk->channels = (uint8_t)channelCount;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
2043 memset(mBuffer, 0, frameCount*channelCount*sizeof(int16_t));
2044 // Force underrun condition to avoid false underrun callback until first data is
2045 // written to buffer
2046 mCblk->flowControlFlag = 1;
2047 mBufferEnd = (uint8_t *)mBuffer + bufferSize;
2048 }
2049 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002050}
2051
Eric Laurenta553c252009-07-17 12:17:14 -07002052AudioFlinger::PlaybackThread::TrackBase::~TrackBase()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002053{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 if (mCblk) {
Eric Laurenta553c252009-07-17 12:17:14 -07002055 mCblk->~audio_track_cblk_t(); // destroy our shared-structure.
2056 if (mClient == NULL) {
2057 delete mCblk;
2058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002060 mCblkMemory.clear(); // and free the shared memory
2061 mClient.clear();
2062}
2063
Eric Laurenta553c252009-07-17 12:17:14 -07002064void AudioFlinger::PlaybackThread::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002065{
2066 buffer->raw = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002067 mFrameCount = buffer->frameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002068 step();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002069 buffer->frameCount = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002070}
2071
Eric Laurenta553c252009-07-17 12:17:14 -07002072bool AudioFlinger::PlaybackThread::TrackBase::step() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002073 bool result;
2074 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002075
2076 result = cblk->stepServer(mFrameCount);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002077 if (!result) {
2078 LOGV("stepServer failed acquiring cblk mutex");
2079 mFlags |= STEPSERVER_FAILED;
2080 }
2081 return result;
2082}
2083
Eric Laurenta553c252009-07-17 12:17:14 -07002084void AudioFlinger::PlaybackThread::TrackBase::reset() {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002085 audio_track_cblk_t* cblk = this->cblk();
2086
2087 cblk->user = 0;
2088 cblk->server = 0;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002089 cblk->userBase = 0;
2090 cblk->serverBase = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 mFlags &= (uint32_t)(~SYSTEM_FLAGS_MASK);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002092 LOGV("TrackBase::reset");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002093}
2094
Eric Laurenta553c252009-07-17 12:17:14 -07002095sp<IMemory> AudioFlinger::PlaybackThread::TrackBase::getCblk() const
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002096{
2097 return mCblkMemory;
2098}
2099
Eric Laurenta553c252009-07-17 12:17:14 -07002100int AudioFlinger::PlaybackThread::TrackBase::sampleRate() const {
The Android Open Source Project10592532009-03-18 17:39:46 -07002101 return (int)mCblk->sampleRate;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002102}
2103
Eric Laurenta553c252009-07-17 12:17:14 -07002104int AudioFlinger::PlaybackThread::TrackBase::channelCount() const {
Eric Laurent88e209d2009-07-07 07:10:45 -07002105 return (int)mCblk->channels;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002106}
2107
Eric Laurenta553c252009-07-17 12:17:14 -07002108void* AudioFlinger::PlaybackThread::TrackBase::getBuffer(uint32_t offset, uint32_t frames) const {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002109 audio_track_cblk_t* cblk = this->cblk();
Eric Laurenta553c252009-07-17 12:17:14 -07002110 int8_t *bufferStart = (int8_t *)mBuffer + (offset-cblk->serverBase)*cblk->frameSize;
2111 int8_t *bufferEnd = bufferStart + frames * cblk->frameSize;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002112
2113 // Check validity of returned pointer in case the track control block would have been corrupted.
Eric Laurenta553c252009-07-17 12:17:14 -07002114 if (bufferStart < mBuffer || bufferStart > bufferEnd || bufferEnd > mBufferEnd ||
2115 ((unsigned long)bufferStart & (unsigned long)(cblk->frameSize - 1))) {
The Android Open Source Project10592532009-03-18 17:39:46 -07002116 LOGE("TrackBase::getBuffer buffer out of range:\n start: %p, end %p , mBuffer %p mBufferEnd %p\n \
2117 server %d, serverBase %d, user %d, userBase %d, channels %d",
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002118 bufferStart, bufferEnd, mBuffer, mBufferEnd,
The Android Open Source Project10592532009-03-18 17:39:46 -07002119 cblk->server, cblk->serverBase, cblk->user, cblk->userBase, cblk->channels);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002120 return 0;
2121 }
2122
2123 return bufferStart;
2124}
2125
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002126// ----------------------------------------------------------------------------
2127
Eric Laurenta553c252009-07-17 12:17:14 -07002128// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
2129AudioFlinger::PlaybackThread::Track::Track(
2130 const wp<ThreadBase>& thread,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002131 const sp<Client>& client,
2132 int streamType,
2133 uint32_t sampleRate,
2134 int format,
2135 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002136 int frameCount,
2137 const sp<IMemory>& sharedBuffer)
Eric Laurenta553c252009-07-17 12:17:14 -07002138 : TrackBase(thread, client, sampleRate, format, channelCount, frameCount, 0, sharedBuffer),
2139 mMute(false), mSharedBuffer(sharedBuffer), mName(-1)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002140{
Eric Laurenta553c252009-07-17 12:17:14 -07002141 sp<ThreadBase> baseThread = thread.promote();
2142 if (baseThread != 0) {
2143 PlaybackThread *playbackThread = (PlaybackThread *)baseThread.get();
2144 mName = playbackThread->getTrackName_l();
2145 }
2146 LOGV("Track constructor name %d, calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2147 if (mName < 0) {
2148 LOGE("no more track names available");
2149 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002150 mVolume[0] = 1.0f;
2151 mVolume[1] = 1.0f;
Eric Laurent4bc035a2009-05-22 09:18:15 -07002152 mStreamType = streamType;
Eric Laurenta553c252009-07-17 12:17:14 -07002153 // NOTE: audio_track_cblk_t::frameSize for 8 bit PCM data is based on a sample size of
2154 // 16 bit because data is converted to 16 bit before being stored in buffer by AudioTrack
2155 mCblk->frameSize = AudioSystem::isLinearPCM(format) ? channelCount * sizeof(int16_t) : sizeof(int8_t);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002156}
2157
Eric Laurenta553c252009-07-17 12:17:14 -07002158AudioFlinger::PlaybackThread::Track::~Track()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002159{
Eric Laurenta553c252009-07-17 12:17:14 -07002160 LOGV("PlaybackThread::Track destructor");
2161 sp<ThreadBase> thread = mThread.promote();
2162 if (thread != 0) {
2163 Mutex::Autolock _l(thread->mLock);
2164 mState = TERMINATED;
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002165 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002166}
2167
Eric Laurenta553c252009-07-17 12:17:14 -07002168void AudioFlinger::PlaybackThread::Track::destroy()
2169{
2170 // NOTE: destroyTrack_l() can remove a strong reference to this Track
2171 // by removing it from mTracks vector, so there is a risk that this Tracks's
2172 // desctructor is called. As the destructor needs to lock mLock,
2173 // we must acquire a strong reference on this Track before locking mLock
2174 // here so that the destructor is called only when exiting this function.
2175 // On the other hand, as long as Track::destroy() is only called by
2176 // TrackHandle destructor, the TrackHandle still holds a strong ref on
2177 // this Track with its member mTrack.
2178 sp<Track> keep(this);
2179 { // scope for mLock
2180 sp<ThreadBase> thread = mThread.promote();
2181 if (thread != 0) {
2182 Mutex::Autolock _l(thread->mLock);
2183 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2184 playbackThread->destroyTrack_l(this);
2185 }
2186 }
2187}
2188
2189void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002190{
2191 snprintf(buffer, size, " %5d %5d %3u %3u %3u %3u %1d %1d %1d %5u %5u %5u %04x %04x\n",
2192 mName - AudioMixer::TRACK0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 (mClient == NULL) ? getpid() : mClient->pid(),
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002194 mStreamType,
2195 mFormat,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002196 mCblk->channels,
2197 mFrameCount,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002198 mState,
2199 mMute,
2200 mFillingUpStatus,
2201 mCblk->sampleRate,
2202 mCblk->volume[0],
2203 mCblk->volume[1],
2204 mCblk->server,
2205 mCblk->user);
2206}
2207
Eric Laurenta553c252009-07-17 12:17:14 -07002208status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002209{
2210 audio_track_cblk_t* cblk = this->cblk();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002211 uint32_t framesReady;
2212 uint32_t framesReq = buffer->frameCount;
2213
2214 // Check if last stepServer failed, try to step now
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002215 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2216 if (!step()) goto getNextBuffer_exit;
2217 LOGV("stepServer recovered");
2218 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2219 }
2220
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002221 framesReady = cblk->framesReady();
2222
2223 if (LIKELY(framesReady)) {
2224 uint32_t s = cblk->server;
2225 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2226
2227 bufferEnd = (cblk->loopEnd < bufferEnd) ? cblk->loopEnd : bufferEnd;
2228 if (framesReq > framesReady) {
2229 framesReq = framesReady;
2230 }
2231 if (s + framesReq > bufferEnd) {
2232 framesReq = bufferEnd - s;
2233 }
2234
2235 buffer->raw = getBuffer(s, framesReq);
2236 if (buffer->raw == 0) goto getNextBuffer_exit;
2237
2238 buffer->frameCount = framesReq;
2239 return NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002240 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002241
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002242getNextBuffer_exit:
2243 buffer->raw = 0;
2244 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002245 LOGV("getNextBuffer() no more data");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002246 return NOT_ENOUGH_DATA;
2247}
2248
Eric Laurenta553c252009-07-17 12:17:14 -07002249bool AudioFlinger::PlaybackThread::Track::isReady() const {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002250 if (mFillingUpStatus != FS_FILLING) return true;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002251
2252 if (mCblk->framesReady() >= mCblk->frameCount ||
2253 mCblk->forceReady) {
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002254 mFillingUpStatus = FS_FILLED;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002255 mCblk->forceReady = 0;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002256 return true;
2257 }
2258 return false;
2259}
2260
Eric Laurenta553c252009-07-17 12:17:14 -07002261status_t AudioFlinger::PlaybackThread::Track::start()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002262{
Eric Laurenta553c252009-07-17 12:17:14 -07002263 LOGV("start(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2264 sp<ThreadBase> thread = mThread.promote();
2265 if (thread != 0) {
2266 Mutex::Autolock _l(thread->mLock);
2267 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2268 playbackThread->addTrack_l(this);
2269 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002270 return NO_ERROR;
2271}
2272
Eric Laurenta553c252009-07-17 12:17:14 -07002273void AudioFlinger::PlaybackThread::Track::stop()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002274{
Eric Laurenta553c252009-07-17 12:17:14 -07002275 LOGV("stop(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
2276 sp<ThreadBase> thread = mThread.promote();
2277 if (thread != 0) {
2278 Mutex::Autolock _l(thread->mLock);
2279 if (mState > STOPPED) {
2280 mState = STOPPED;
2281 // If the track is not active (PAUSED and buffers full), flush buffers
2282 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
2283 if (playbackThread->mActiveTracks.indexOf(this) < 0) {
2284 reset();
2285 }
2286 LOGV("(> STOPPED) => STOPPED (%d)", mName);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002287 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002288 }
2289}
2290
Eric Laurenta553c252009-07-17 12:17:14 -07002291void AudioFlinger::PlaybackThread::Track::pause()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002292{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 LOGV("pause(%d), calling thread %d", mName, IPCThreadState::self()->getCallingPid());
Eric Laurenta553c252009-07-17 12:17:14 -07002294 sp<ThreadBase> thread = mThread.promote();
2295 if (thread != 0) {
2296 Mutex::Autolock _l(thread->mLock);
2297 if (mState == ACTIVE || mState == RESUMING) {
2298 mState = PAUSING;
2299 LOGV("ACTIVE/RESUMING => PAUSING (%d)", mName);
2300 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002301 }
2302}
2303
Eric Laurenta553c252009-07-17 12:17:14 -07002304void AudioFlinger::PlaybackThread::Track::flush()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002305{
2306 LOGV("flush(%d)", mName);
Eric Laurenta553c252009-07-17 12:17:14 -07002307 sp<ThreadBase> thread = mThread.promote();
2308 if (thread != 0) {
2309 Mutex::Autolock _l(thread->mLock);
2310 if (mState != STOPPED && mState != PAUSED && mState != PAUSING) {
2311 return;
2312 }
2313 // No point remaining in PAUSED state after a flush => go to
2314 // STOPPED state
2315 mState = STOPPED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002316
Eric Laurenta553c252009-07-17 12:17:14 -07002317 mCblk->lock.lock();
2318 // NOTE: reset() will reset cblk->user and cblk->server with
2319 // the risk that at the same time, the AudioMixer is trying to read
2320 // data. In this case, getNextBuffer() would return a NULL pointer
2321 // as audio buffer => the AudioMixer code MUST always test that pointer
2322 // returned by getNextBuffer() is not NULL!
2323 reset();
2324 mCblk->lock.unlock();
2325 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002326}
2327
Eric Laurenta553c252009-07-17 12:17:14 -07002328void AudioFlinger::PlaybackThread::Track::reset()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002329{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002330 // Do not reset twice to avoid discarding data written just after a flush and before
2331 // the audioflinger thread detects the track is stopped.
2332 if (!mResetDone) {
2333 TrackBase::reset();
2334 // Force underrun condition to avoid false underrun callback until first data is
2335 // written to buffer
2336 mCblk->flowControlFlag = 1;
2337 mCblk->forceReady = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002338 mFillingUpStatus = FS_FILLING;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002339 mResetDone = true;
2340 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002341}
2342
Eric Laurenta553c252009-07-17 12:17:14 -07002343void AudioFlinger::PlaybackThread::Track::mute(bool muted)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002344{
2345 mMute = muted;
2346}
2347
Eric Laurenta553c252009-07-17 12:17:14 -07002348void AudioFlinger::PlaybackThread::Track::setVolume(float left, float right)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002349{
2350 mVolume[0] = left;
2351 mVolume[1] = right;
2352}
2353
2354// ----------------------------------------------------------------------------
2355
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002356// RecordTrack constructor must be called with AudioFlinger::mLock held
Eric Laurenta553c252009-07-17 12:17:14 -07002357AudioFlinger::RecordThread::RecordTrack::RecordTrack(
2358 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 const sp<Client>& client,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 uint32_t sampleRate,
2361 int format,
2362 int channelCount,
2363 int frameCount,
2364 uint32_t flags)
Eric Laurenta553c252009-07-17 12:17:14 -07002365 : TrackBase(thread, client, sampleRate, format,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 channelCount, frameCount, flags, 0),
Eric Laurenta553c252009-07-17 12:17:14 -07002367 mOverflow(false)
2368{
2369 LOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
2370 if (format == AudioSystem::PCM_16_BIT) {
2371 mCblk->frameSize = channelCount * sizeof(int16_t);
2372 } else if (format == AudioSystem::PCM_8_BIT) {
2373 mCblk->frameSize = channelCount * sizeof(int8_t);
2374 } else {
2375 mCblk->frameSize = sizeof(int8_t);
2376 }
2377}
2378
2379AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380{
2381}
2382
Eric Laurenta553c252009-07-17 12:17:14 -07002383status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384{
2385 audio_track_cblk_t* cblk = this->cblk();
2386 uint32_t framesAvail;
2387 uint32_t framesReq = buffer->frameCount;
2388
2389 // Check if last stepServer failed, try to step now
2390 if (mFlags & TrackBase::STEPSERVER_FAILED) {
2391 if (!step()) goto getNextBuffer_exit;
2392 LOGV("stepServer recovered");
2393 mFlags &= ~TrackBase::STEPSERVER_FAILED;
2394 }
2395
2396 framesAvail = cblk->framesAvailable_l();
2397
2398 if (LIKELY(framesAvail)) {
2399 uint32_t s = cblk->server;
2400 uint32_t bufferEnd = cblk->serverBase + cblk->frameCount;
2401
2402 if (framesReq > framesAvail) {
2403 framesReq = framesAvail;
2404 }
2405 if (s + framesReq > bufferEnd) {
2406 framesReq = bufferEnd - s;
2407 }
2408
2409 buffer->raw = getBuffer(s, framesReq);
2410 if (buffer->raw == 0) goto getNextBuffer_exit;
2411
2412 buffer->frameCount = framesReq;
2413 return NO_ERROR;
2414 }
2415
2416getNextBuffer_exit:
2417 buffer->raw = 0;
2418 buffer->frameCount = 0;
2419 return NOT_ENOUGH_DATA;
2420}
2421
Eric Laurenta553c252009-07-17 12:17:14 -07002422status_t AudioFlinger::RecordThread::RecordTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423{
Eric Laurenta553c252009-07-17 12:17:14 -07002424 sp<ThreadBase> thread = mThread.promote();
2425 if (thread != 0) {
2426 RecordThread *recordThread = (RecordThread *)thread.get();
2427 return recordThread->start(this);
2428 }
2429 return NO_INIT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430}
2431
Eric Laurenta553c252009-07-17 12:17:14 -07002432void AudioFlinger::RecordThread::RecordTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433{
Eric Laurenta553c252009-07-17 12:17:14 -07002434 sp<ThreadBase> thread = mThread.promote();
2435 if (thread != 0) {
2436 RecordThread *recordThread = (RecordThread *)thread.get();
2437 recordThread->stop(this);
2438 TrackBase::reset();
2439 // Force overerrun condition to avoid false overrun callback until first data is
2440 // read from buffer
2441 mCblk->flowControlFlag = 1;
2442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443}
2444
2445
2446// ----------------------------------------------------------------------------
2447
Eric Laurenta553c252009-07-17 12:17:14 -07002448AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
2449 const wp<ThreadBase>& thread,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 uint32_t sampleRate,
2451 int format,
2452 int channelCount,
2453 int frameCount)
Eric Laurenta553c252009-07-17 12:17:14 -07002454 : Track(thread, NULL, AudioSystem::NUM_STREAM_TYPES, sampleRate, format, channelCount, frameCount, NULL),
2455 mActive(false)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456{
Eric Laurenta553c252009-07-17 12:17:14 -07002457
2458 PlaybackThread *playbackThread = (PlaybackThread *)thread.unsafe_get();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 mCblk->out = 1;
2460 mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
2461 mCblk->volume[0] = mCblk->volume[1] = 0x1000;
2462 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002463 mWaitTimeMs = (playbackThread->frameCount() * 2 * 1000) / playbackThread->sampleRate();
2464
2465 LOGV("OutputTrack constructor mCblk %p, mBuffer %p, mCblk->buffers %p, mCblk->frameCount %d, mCblk->sampleRate %d, mCblk->channels %d mBufferEnd %p mWaitTimeMs %d",
2466 mCblk, mBuffer, mCblk->buffers, mCblk->frameCount, mCblk->sampleRate, mCblk->channels, mBufferEnd, mWaitTimeMs);
2467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468}
2469
Eric Laurenta553c252009-07-17 12:17:14 -07002470AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471{
2472 stop();
2473}
2474
Eric Laurenta553c252009-07-17 12:17:14 -07002475status_t AudioFlinger::PlaybackThread::OutputTrack::start()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476{
2477 status_t status = Track::start();
Eric Laurenta553c252009-07-17 12:17:14 -07002478 if (status != NO_ERROR) {
2479 return status;
2480 }
2481
2482 mActive = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 mRetryCount = 127;
2484 return status;
2485}
2486
Eric Laurenta553c252009-07-17 12:17:14 -07002487void AudioFlinger::PlaybackThread::OutputTrack::stop()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488{
2489 Track::stop();
2490 clearBufferQueue();
2491 mOutBuffer.frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002492 mActive = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493}
2494
Eric Laurenta553c252009-07-17 12:17:14 -07002495bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496{
2497 Buffer *pInBuffer;
2498 Buffer inBuffer;
2499 uint32_t channels = mCblk->channels;
Eric Laurenta553c252009-07-17 12:17:14 -07002500 bool outputBufferFull = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 inBuffer.frameCount = frames;
2502 inBuffer.i16 = data;
Eric Laurenta553c252009-07-17 12:17:14 -07002503
2504 uint32_t waitTimeLeftMs = mWaitTimeMs;
2505
2506 if (!mActive) {
2507 start();
2508 sp<ThreadBase> thread = mThread.promote();
2509 if (thread != 0) {
2510 MixerThread *mixerThread = (MixerThread *)thread.get();
2511 if (mCblk->frameCount > frames){
2512 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
2513 uint32_t startFrames = (mCblk->frameCount - frames);
2514 pInBuffer = new Buffer;
2515 pInBuffer->mBuffer = new int16_t[startFrames * channels];
2516 pInBuffer->frameCount = startFrames;
2517 pInBuffer->i16 = pInBuffer->mBuffer;
2518 memset(pInBuffer->raw, 0, startFrames * channels * sizeof(int16_t));
2519 mBufferQueue.add(pInBuffer);
2520 } else {
2521 LOGW ("OutputTrack::write() %p no more buffers in queue", this);
2522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
Eric Laurenta553c252009-07-17 12:17:14 -07002524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 }
2526
Eric Laurenta553c252009-07-17 12:17:14 -07002527 while (waitTimeLeftMs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 // First write pending buffers, then new data
2529 if (mBufferQueue.size()) {
2530 pInBuffer = mBufferQueue.itemAt(0);
2531 } else {
2532 pInBuffer = &inBuffer;
2533 }
Eric Laurenta553c252009-07-17 12:17:14 -07002534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 if (pInBuffer->frameCount == 0) {
2536 break;
2537 }
Eric Laurenta553c252009-07-17 12:17:14 -07002538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 if (mOutBuffer.frameCount == 0) {
2540 mOutBuffer.frameCount = pInBuffer->frameCount;
Eric Laurenta553c252009-07-17 12:17:14 -07002541 nsecs_t startTime = systemTime();
2542 if (obtainBuffer(&mOutBuffer, waitTimeLeftMs) == (status_t)AudioTrack::NO_MORE_BUFFERS) {
2543 LOGV ("OutputTrack::write() %p no more output buffers", this);
2544 outputBufferFull = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 break;
2546 }
Eric Laurenta553c252009-07-17 12:17:14 -07002547 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
2548// LOGV("OutputTrack::write() waitTimeMs %d waitTimeLeftMs %d", waitTimeMs, waitTimeLeftMs)
2549 if (waitTimeLeftMs >= waitTimeMs) {
2550 waitTimeLeftMs -= waitTimeMs;
2551 } else {
2552 waitTimeLeftMs = 0;
2553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
Eric Laurenta553c252009-07-17 12:17:14 -07002555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : pInBuffer->frameCount;
2557 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channels * sizeof(int16_t));
2558 mCblk->stepUser(outFrames);
2559 pInBuffer->frameCount -= outFrames;
2560 pInBuffer->i16 += outFrames * channels;
2561 mOutBuffer.frameCount -= outFrames;
Eric Laurenta553c252009-07-17 12:17:14 -07002562 mOutBuffer.i16 += outFrames * channels;
2563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 if (pInBuffer->frameCount == 0) {
2565 if (mBufferQueue.size()) {
2566 mBufferQueue.removeAt(0);
2567 delete [] pInBuffer->mBuffer;
2568 delete pInBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07002569 LOGV("OutputTrack::write() %p released overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 } else {
2571 break;
2572 }
2573 }
2574 }
Eric Laurenta553c252009-07-17 12:17:14 -07002575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 // If we could not write all frames, allocate a buffer and queue it for next time.
2577 if (inBuffer.frameCount) {
Eric Laurenta553c252009-07-17 12:17:14 -07002578 if (mBufferQueue.size() < kMaxOverFlowBuffers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 pInBuffer = new Buffer;
2580 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channels];
2581 pInBuffer->frameCount = inBuffer.frameCount;
2582 pInBuffer->i16 = pInBuffer->mBuffer;
2583 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channels * sizeof(int16_t));
2584 mBufferQueue.add(pInBuffer);
Eric Laurenta553c252009-07-17 12:17:14 -07002585 LOGV("OutputTrack::write() %p adding overflow buffer %d", this, mBufferQueue.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07002587 LOGW("OutputTrack::write() %p no more overflow buffers", this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589 }
Eric Laurenta553c252009-07-17 12:17:14 -07002590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 // Calling write() with a 0 length buffer, means that no more data will be written:
Eric Laurenta553c252009-07-17 12:17:14 -07002592 // If no more buffers are pending, fill output track buffer to make sure it is started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 // by output mixer.
Eric Laurenta553c252009-07-17 12:17:14 -07002594 if (frames == 0 && mBufferQueue.size() == 0) {
2595 if (mCblk->user < mCblk->frameCount) {
2596 frames = mCblk->frameCount - mCblk->user;
2597 pInBuffer = new Buffer;
2598 pInBuffer->mBuffer = new int16_t[frames * channels];
2599 pInBuffer->frameCount = frames;
2600 pInBuffer->i16 = pInBuffer->mBuffer;
2601 memset(pInBuffer->raw, 0, frames * channels * sizeof(int16_t));
2602 mBufferQueue.add(pInBuffer);
2603 } else {
2604 stop();
2605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 }
2607
Eric Laurenta553c252009-07-17 12:17:14 -07002608 return outputBufferFull;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609}
2610
Eric Laurenta553c252009-07-17 12:17:14 -07002611status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612{
2613 int active;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 status_t result;
2615 audio_track_cblk_t* cblk = mCblk;
2616 uint32_t framesReq = buffer->frameCount;
2617
Eric Laurenta553c252009-07-17 12:17:14 -07002618// LOGV("OutputTrack::obtainBuffer user %d, server %d", cblk->user, cblk->server);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 buffer->frameCount = 0;
Eric Laurenta553c252009-07-17 12:17:14 -07002620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 uint32_t framesAvail = cblk->framesAvailable();
2622
Eric Laurenta553c252009-07-17 12:17:14 -07002623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 if (framesAvail == 0) {
Eric Laurenta553c252009-07-17 12:17:14 -07002625 Mutex::Autolock _l(cblk->lock);
2626 goto start_loop_here;
2627 while (framesAvail == 0) {
2628 active = mActive;
2629 if (UNLIKELY(!active)) {
2630 LOGV("Not active and NO_MORE_BUFFERS");
2631 return AudioTrack::NO_MORE_BUFFERS;
2632 }
2633 result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
2634 if (result != NO_ERROR) {
2635 return AudioTrack::NO_MORE_BUFFERS;
2636 }
2637 // read the server count again
2638 start_loop_here:
2639 framesAvail = cblk->framesAvailable_l();
2640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 }
2642
Eric Laurenta553c252009-07-17 12:17:14 -07002643// if (framesAvail < framesReq) {
2644// return AudioTrack::NO_MORE_BUFFERS;
2645// }
2646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 if (framesReq > framesAvail) {
2648 framesReq = framesAvail;
2649 }
2650
2651 uint32_t u = cblk->user;
2652 uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
2653
2654 if (u + framesReq > bufferEnd) {
2655 framesReq = bufferEnd - u;
2656 }
2657
2658 buffer->frameCount = framesReq;
2659 buffer->raw = (void *)cblk->buffer(u);
2660 return NO_ERROR;
2661}
2662
2663
Eric Laurenta553c252009-07-17 12:17:14 -07002664void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665{
2666 size_t size = mBufferQueue.size();
2667 Buffer *pBuffer;
Eric Laurenta553c252009-07-17 12:17:14 -07002668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 for (size_t i = 0; i < size; i++) {
2670 pBuffer = mBufferQueue.itemAt(i);
2671 delete [] pBuffer->mBuffer;
2672 delete pBuffer;
2673 }
2674 mBufferQueue.clear();
2675}
2676
2677// ----------------------------------------------------------------------------
2678
2679AudioFlinger::Client::Client(const sp<AudioFlinger>& audioFlinger, pid_t pid)
2680 : RefBase(),
2681 mAudioFlinger(audioFlinger),
2682 mMemoryDealer(new MemoryDealer(1024*1024)),
2683 mPid(pid)
2684{
2685 // 1 MB of address space is good for 32 tracks, 8 buffers each, 4 KB/buffer
2686}
2687
2688AudioFlinger::Client::~Client()
2689{
2690 mAudioFlinger->removeClient(mPid);
2691}
2692
2693const sp<MemoryDealer>& AudioFlinger::Client::heap() const
2694{
2695 return mMemoryDealer;
2696}
2697
2698// ----------------------------------------------------------------------------
2699
Eric Laurenta553c252009-07-17 12:17:14 -07002700AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002701 : BnAudioTrack(),
2702 mTrack(track)
2703{
2704}
2705
2706AudioFlinger::TrackHandle::~TrackHandle() {
2707 // just stop the track on deletion, associated resources
2708 // will be freed from the main thread once all pending buffers have
2709 // been played. Unless it's not in the active track list, in which
2710 // case we free everything now...
2711 mTrack->destroy();
2712}
2713
2714status_t AudioFlinger::TrackHandle::start() {
2715 return mTrack->start();
2716}
2717
2718void AudioFlinger::TrackHandle::stop() {
2719 mTrack->stop();
2720}
2721
2722void AudioFlinger::TrackHandle::flush() {
2723 mTrack->flush();
2724}
2725
2726void AudioFlinger::TrackHandle::mute(bool e) {
2727 mTrack->mute(e);
2728}
2729
2730void AudioFlinger::TrackHandle::pause() {
2731 mTrack->pause();
2732}
2733
2734void AudioFlinger::TrackHandle::setVolume(float left, float right) {
2735 mTrack->setVolume(left, right);
2736}
2737
2738sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
2739 return mTrack->getCblk();
2740}
2741
2742status_t AudioFlinger::TrackHandle::onTransact(
2743 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2744{
2745 return BnAudioTrack::onTransact(code, data, reply, flags);
2746}
2747
2748// ----------------------------------------------------------------------------
2749
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002750sp<IAudioRecord> AudioFlinger::openRecord(
2751 pid_t pid,
Eric Laurentddb78e72009-07-28 08:44:33 -07002752 int input,
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002753 uint32_t sampleRate,
2754 int format,
2755 int channelCount,
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002756 int frameCount,
2757 uint32_t flags,
2758 status_t *status)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002759{
Eric Laurenta553c252009-07-17 12:17:14 -07002760 sp<RecordThread::RecordTrack> recordTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002761 sp<RecordHandle> recordHandle;
2762 sp<Client> client;
2763 wp<Client> wclient;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002764 status_t lStatus;
Eric Laurenta553c252009-07-17 12:17:14 -07002765 RecordThread *thread;
2766 size_t inFrameCount;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002767
2768 // check calling permissions
2769 if (!recordingAllowed()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002770 lStatus = PERMISSION_DENIED;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002771 goto Exit;
2772 }
2773
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002774 // add client to list
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002775 { // scope for mLock
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002776 Mutex::Autolock _l(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002777 thread = checkRecordThread_l(input);
2778 if (thread == NULL) {
2779 lStatus = BAD_VALUE;
2780 goto Exit;
2781 }
2782
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002783 wclient = mClients.valueFor(pid);
2784 if (wclient != NULL) {
2785 client = wclient.promote();
2786 } else {
2787 client = new Client(this, pid);
2788 mClients.add(pid, client);
2789 }
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002790
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002791 // create new record track. The record track uses one track in mHardwareMixerThread by convention.
Eric Laurenta553c252009-07-17 12:17:14 -07002792 recordTrack = new RecordThread::RecordTrack(thread, client, sampleRate,
The Android Open Source Projectb2a3dd82009-03-09 11:52:12 -07002793 format, channelCount, frameCount, flags);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 if (recordTrack->getCblk() == NULL) {
2796 recordTrack.clear();
2797 lStatus = NO_MEMORY;
2798 goto Exit;
2799 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002800
2801 // return to handle to client
2802 recordHandle = new RecordHandle(recordTrack);
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002803 lStatus = NO_ERROR;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002804
2805Exit:
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002806 if (status) {
2807 *status = lStatus;
2808 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002809 return recordHandle;
2810}
2811
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002812// ----------------------------------------------------------------------------
2813
Eric Laurenta553c252009-07-17 12:17:14 -07002814AudioFlinger::RecordHandle::RecordHandle(const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002815 : BnAudioRecord(),
2816 mRecordTrack(recordTrack)
2817{
2818}
2819
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002820AudioFlinger::RecordHandle::~RecordHandle() {
2821 stop();
2822}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002823
2824status_t AudioFlinger::RecordHandle::start() {
2825 LOGV("RecordHandle::start()");
2826 return mRecordTrack->start();
2827}
2828
2829void AudioFlinger::RecordHandle::stop() {
2830 LOGV("RecordHandle::stop()");
2831 mRecordTrack->stop();
2832}
2833
2834sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
2835 return mRecordTrack->getCblk();
2836}
2837
2838status_t AudioFlinger::RecordHandle::onTransact(
2839 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2840{
2841 return BnAudioRecord::onTransact(code, data, reply, flags);
2842}
2843
2844// ----------------------------------------------------------------------------
2845
Eric Laurenta553c252009-07-17 12:17:14 -07002846AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger, AudioStreamIn *input, uint32_t sampleRate, uint32_t channels) :
2847 ThreadBase(audioFlinger),
2848 mInput(input), mResampler(0), mRsmpOutBuffer(0), mRsmpInBuffer(0)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002849{
Eric Laurenta553c252009-07-17 12:17:14 -07002850 mReqChannelCount = AudioSystem::popCount(channels);
2851 mReqSampleRate = sampleRate;
2852 readInputParameters();
2853 sendConfigEvent(AudioSystem::INPUT_OPENED);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002854}
2855
Eric Laurenta553c252009-07-17 12:17:14 -07002856
2857AudioFlinger::RecordThread::~RecordThread()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002858{
Eric Laurenta553c252009-07-17 12:17:14 -07002859 delete[] mRsmpInBuffer;
2860 if (mResampler != 0) {
2861 delete mResampler;
2862 delete[] mRsmpOutBuffer;
2863 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002864}
2865
Eric Laurenta553c252009-07-17 12:17:14 -07002866void AudioFlinger::RecordThread::onFirstRef()
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002867{
Eric Laurenta553c252009-07-17 12:17:14 -07002868 const size_t SIZE = 256;
2869 char buffer[SIZE];
2870
2871 snprintf(buffer, SIZE, "Record Thread %p", this);
2872
2873 run(buffer, PRIORITY_URGENT_AUDIO);
2874}
2875bool AudioFlinger::RecordThread::threadLoop()
2876{
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002877 AudioBufferProvider::Buffer buffer;
Eric Laurenta553c252009-07-17 12:17:14 -07002878 sp<RecordTrack> activeTrack;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002879
2880 // start recording
2881 while (!exitPending()) {
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002882
Eric Laurenta553c252009-07-17 12:17:14 -07002883 processConfigEvents();
2884
2885 { // scope for mLock
2886 Mutex::Autolock _l(mLock);
2887 checkForNewParameters_l();
2888 if (mActiveTrack == 0 && mConfigEvents.isEmpty()) {
2889 if (!mStandby) {
2890 mInput->standby();
2891 mStandby = true;
2892 }
2893
2894 if (exitPending()) break;
2895
2896 LOGV("RecordThread: loop stopping");
2897 // go to sleep
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002898 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07002899 LOGV("RecordThread: loop starting");
2900 continue;
2901 }
2902 if (mActiveTrack != 0) {
2903 if (mActiveTrack->mState == TrackBase::PAUSING) {
2904 mActiveTrack.clear();
2905 mStartStopCond.broadcast();
2906 } else if (mActiveTrack->mState == TrackBase::RESUMING) {
2907 mRsmpInIndex = mFrameCount;
2908 if (mReqChannelCount != mActiveTrack->channelCount()) {
2909 mActiveTrack.clear();
2910 } else {
2911 mActiveTrack->mState == TrackBase::ACTIVE;
2912 }
2913 mStartStopCond.broadcast();
2914 }
2915 mStandby = false;
2916 }
2917 }
2918
2919 if (mActiveTrack != 0) {
2920 buffer.frameCount = mFrameCount;
2921 if (LIKELY(mActiveTrack->getNextBuffer(&buffer) == NO_ERROR)) {
2922 size_t framesOut = buffer.frameCount;
2923 if (mResampler == 0) {
2924 // no resampling
2925 while (framesOut) {
2926 size_t framesIn = mFrameCount - mRsmpInIndex;
2927 if (framesIn) {
2928 int8_t *src = (int8_t *)mRsmpInBuffer + mRsmpInIndex * mFrameSize;
2929 int8_t *dst = buffer.i8 + (buffer.frameCount - framesOut) * mActiveTrack->mCblk->frameSize;
2930 if (framesIn > framesOut)
2931 framesIn = framesOut;
2932 mRsmpInIndex += framesIn;
2933 framesOut -= framesIn;
2934 if (mChannelCount == mReqChannelCount ||
2935 mFormat != AudioSystem::PCM_16_BIT) {
2936 memcpy(dst, src, framesIn * mFrameSize);
2937 } else {
2938 int16_t *src16 = (int16_t *)src;
2939 int16_t *dst16 = (int16_t *)dst;
2940 if (mChannelCount == 1) {
2941 while (framesIn--) {
2942 *dst16++ = *src16;
2943 *dst16++ = *src16++;
2944 }
2945 } else {
2946 while (framesIn--) {
2947 *dst16++ = (int16_t)(((int32_t)*src16 + (int32_t)*(src16 + 1)) >> 1);
2948 src16 += 2;
2949 }
2950 }
2951 }
2952 }
2953 if (framesOut && mFrameCount == mRsmpInIndex) {
2954 ssize_t bytesRead;
2955 if (framesOut == mFrameCount &&
2956 (mChannelCount == mReqChannelCount || mFormat != AudioSystem::PCM_16_BIT)) {
2957 bytesRead = mInput->read(buffer.raw, mInputBytes);
2958 framesOut = 0;
2959 } else {
2960 bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
2961 mRsmpInIndex = 0;
2962 }
2963 if (bytesRead < 0) {
2964 LOGE("Error reading audio input");
2965 sleep(1);
2966 mRsmpInIndex = mFrameCount;
2967 framesOut = 0;
2968 buffer.frameCount = 0;
2969 }
2970 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08002971 }
2972 } else {
Eric Laurenta553c252009-07-17 12:17:14 -07002973 // resampling
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002974
Eric Laurenta553c252009-07-17 12:17:14 -07002975 memset(mRsmpOutBuffer, 0, framesOut * 2 * sizeof(int32_t));
2976 // alter output frame count as if we were expecting stereo samples
2977 if (mChannelCount == 1 && mReqChannelCount == 1) {
2978 framesOut >>= 1;
2979 }
2980 mResampler->resample(mRsmpOutBuffer, framesOut, this);
2981 // ditherAndClamp() works as long as all buffers returned by mActiveTrack->getNextBuffer()
2982 // are 32 bit aligned which should be always true.
2983 if (mChannelCount == 2 && mReqChannelCount == 1) {
2984 AudioMixer::ditherAndClamp(mRsmpOutBuffer, mRsmpOutBuffer, framesOut);
2985 // the resampler always outputs stereo samples: do post stereo to mono conversion
2986 int16_t *src = (int16_t *)mRsmpOutBuffer;
2987 int16_t *dst = buffer.i16;
2988 while (framesOut--) {
2989 *dst++ = (int16_t)(((int32_t)*src + (int32_t)*(src + 1)) >> 1);
2990 src += 2;
2991 }
2992 } else {
2993 AudioMixer::ditherAndClamp((int32_t *)buffer.raw, mRsmpOutBuffer, framesOut);
2994 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07002995
Eric Laurenta553c252009-07-17 12:17:14 -07002996 }
2997 mActiveTrack->releaseBuffer(&buffer);
2998 mActiveTrack->overflow();
2999 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003000 // client isn't retrieving buffers fast enough
3001 else {
Eric Laurenta553c252009-07-17 12:17:14 -07003002 if (!mActiveTrack->setOverflow())
3003 LOGW("RecordThread: buffer overflow");
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003004 // Release the processor for a while before asking for a new buffer.
3005 // This will give the application more chance to read from the buffer and
3006 // clear the overflow.
3007 usleep(5000);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003008 }
3009 }
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003010 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003011
Eric Laurenta553c252009-07-17 12:17:14 -07003012 if (!mStandby) {
3013 mInput->standby();
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003014 }
Eric Laurenta553c252009-07-17 12:17:14 -07003015 mActiveTrack.clear();
3016
3017 sendConfigEvent(AudioSystem::INPUT_CLOSED);
3018 processConfigEvents();
3019
3020 LOGV("RecordThread %p exiting", this);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003021 return false;
3022}
3023
Eric Laurenta553c252009-07-17 12:17:14 -07003024status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack)
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003025{
Eric Laurenta553c252009-07-17 12:17:14 -07003026 LOGV("RecordThread::start");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003027 AutoMutex lock(&mLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003028
Eric Laurenta553c252009-07-17 12:17:14 -07003029 if (mActiveTrack != 0) {
3030 if (recordTrack != mActiveTrack.get()) return -EBUSY;
The Android Open Source Projectf013e1a2008-12-17 18:05:43 -08003031
Eric Laurenta553c252009-07-17 12:17:14 -07003032 if (mActiveTrack->mState == TrackBase::PAUSING) mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003033
Eric Laurenta553c252009-07-17 12:17:14 -07003034 return NO_ERROR;
3035 }
3036
3037 mActiveTrack = recordTrack;
3038 mActiveTrack->mState = TrackBase::RESUMING;
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003039 // signal thread to start
3040 LOGV("Signal record thread");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003041 mWaitWorkCV.signal();
Eric Laurenta553c252009-07-17 12:17:14 -07003042 mStartStopCond.wait(mLock);
3043 if (mActiveTrack != 0) {
3044 LOGV("Record started OK");
3045 return NO_ERROR;
3046 } else {
3047 LOGV("Record failed to start");
3048 return BAD_VALUE;
3049 }
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003050}
3051
Eric Laurenta553c252009-07-17 12:17:14 -07003052void AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
3053 LOGV("RecordThread::stop");
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003054 AutoMutex lock(&mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003055 if (mActiveTrack != 0 && recordTrack == mActiveTrack.get()) {
3056 mActiveTrack->mState = TrackBase::PAUSING;
3057 mStartStopCond.wait(mLock);
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003058 }
3059}
3060
Eric Laurenta553c252009-07-17 12:17:14 -07003061status_t AudioFlinger::RecordThread::dump(int fd, const Vector<String16>& args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062{
3063 const size_t SIZE = 256;
3064 char buffer[SIZE];
3065 String8 result;
3066 pid_t pid = 0;
3067
Eric Laurenta553c252009-07-17 12:17:14 -07003068 if (mActiveTrack != 0 && mActiveTrack->mClient != 0) {
3069 snprintf(buffer, SIZE, "Record client pid: %d\n", mActiveTrack->mClient->pid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 result.append(buffer);
3071 } else {
3072 result.append("No record client\n");
3073 }
3074 write(fd, result.string(), result.size());
3075 return NO_ERROR;
3076}
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003077
Eric Laurenta553c252009-07-17 12:17:14 -07003078status_t AudioFlinger::RecordThread::getNextBuffer(AudioBufferProvider::Buffer* buffer)
3079{
3080 size_t framesReq = buffer->frameCount;
3081 size_t framesReady = mFrameCount - mRsmpInIndex;
3082 int channelCount;
3083
3084 if (framesReady == 0) {
3085 ssize_t bytesRead = mInput->read(mRsmpInBuffer, mInputBytes);
3086 if (bytesRead < 0) {
3087 LOGE("RecordThread::getNextBuffer() Error reading audio input");
3088 sleep(1);
3089 buffer->raw = 0;
3090 buffer->frameCount = 0;
3091 return NOT_ENOUGH_DATA;
3092 }
3093 mRsmpInIndex = 0;
3094 framesReady = mFrameCount;
3095 }
3096
3097 if (framesReq > framesReady) {
3098 framesReq = framesReady;
3099 }
3100
3101 if (mChannelCount == 1 && mReqChannelCount == 2) {
3102 channelCount = 1;
3103 } else {
3104 channelCount = 2;
3105 }
3106 buffer->raw = mRsmpInBuffer + mRsmpInIndex * channelCount;
3107 buffer->frameCount = framesReq;
3108 return NO_ERROR;
3109}
3110
3111void AudioFlinger::RecordThread::releaseBuffer(AudioBufferProvider::Buffer* buffer)
3112{
3113 mRsmpInIndex += buffer->frameCount;
3114 buffer->frameCount = 0;
3115}
3116
3117bool AudioFlinger::RecordThread::checkForNewParameters_l()
3118{
3119 bool reconfig = false;
3120
Eric Laurent8fce46a2009-08-04 09:45:33 -07003121 while (!mNewParameters.isEmpty()) {
Eric Laurenta553c252009-07-17 12:17:14 -07003122 status_t status = NO_ERROR;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003123 String8 keyValuePair = mNewParameters[0];
3124 AudioParameter param = AudioParameter(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003125 int value;
3126 int reqFormat = mFormat;
3127 int reqSamplingRate = mReqSampleRate;
3128 int reqChannelCount = mReqChannelCount;
Eric Laurent8fce46a2009-08-04 09:45:33 -07003129
3130 mNewParameters.removeAt(0);
3131
Eric Laurenta553c252009-07-17 12:17:14 -07003132 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
3133 reqSamplingRate = value;
3134 reconfig = true;
3135 }
3136 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
3137 reqFormat = value;
3138 reconfig = true;
3139 }
3140 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
3141 reqChannelCount = AudioSystem::popCount(value);
3142 reconfig = true;
3143 }
3144 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
3145 // do not accept frame count changes if tracks are open as the track buffer
3146 // size depends on frame count and correct behavior would not be garantied
3147 // if frame count is changed after track creation
3148 if (mActiveTrack != 0) {
3149 status = INVALID_OPERATION;
3150 } else {
3151 reconfig = true;
3152 }
3153 }
3154 if (status == NO_ERROR) {
Eric Laurent8fce46a2009-08-04 09:45:33 -07003155 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003156 if (status == INVALID_OPERATION) {
3157 mInput->standby();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003158 status = mInput->setParameters(keyValuePair);
Eric Laurenta553c252009-07-17 12:17:14 -07003159 }
3160 if (reconfig) {
3161 if (status == BAD_VALUE &&
3162 reqFormat == mInput->format() && reqFormat == AudioSystem::PCM_16_BIT &&
3163 ((int)mInput->sampleRate() <= 2 * reqSamplingRate) &&
3164 (AudioSystem::popCount(mInput->channels()) < 3) && (reqChannelCount < 3)) {
3165 status = NO_ERROR;
3166 }
3167 if (status == NO_ERROR) {
3168 readInputParameters();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003169 sendConfigEvent_l(AudioSystem::INPUT_CONFIG_CHANGED);
Eric Laurenta553c252009-07-17 12:17:14 -07003170 }
3171 }
3172 }
Eric Laurenta553c252009-07-17 12:17:14 -07003173 mParamStatus = status;
3174 mParamCond.signal();
Eric Laurent8fce46a2009-08-04 09:45:33 -07003175 mWaitWorkCV.wait(mLock);
Eric Laurenta553c252009-07-17 12:17:14 -07003176 }
3177 return reconfig;
3178}
3179
3180String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
3181{
3182 return mInput->getParameters(keys);
3183}
3184
3185void AudioFlinger::RecordThread::audioConfigChanged(int event, int param) {
3186 AudioSystem::OutputDescriptor desc;
3187 void *param2 = 0;
3188
3189 switch (event) {
3190 case AudioSystem::INPUT_OPENED:
3191 case AudioSystem::INPUT_CONFIG_CHANGED:
3192 desc.channels = mChannelCount;
3193 desc.samplingRate = mSampleRate;
3194 desc.format = mFormat;
3195 desc.frameCount = mFrameCount;
3196 desc.latency = 0;
3197 param2 = &desc;
3198 break;
3199
3200 case AudioSystem::INPUT_CLOSED:
3201 default:
3202 break;
3203 }
3204 mAudioFlinger->audioConfigChanged(event, this, param2);
3205}
3206
3207void AudioFlinger::RecordThread::readInputParameters()
3208{
3209 if (mRsmpInBuffer) delete mRsmpInBuffer;
3210 if (mRsmpOutBuffer) delete mRsmpOutBuffer;
3211 if (mResampler) delete mResampler;
3212 mResampler = 0;
3213
3214 mSampleRate = mInput->sampleRate();
3215 mChannelCount = AudioSystem::popCount(mInput->channels());
3216 mFormat = mInput->format();
3217 mFrameSize = mInput->frameSize();
3218 mInputBytes = mInput->bufferSize();
3219 mFrameCount = mInputBytes / mFrameSize;
3220 mRsmpInBuffer = new int16_t[mFrameCount * mChannelCount];
3221
3222 if (mSampleRate != mReqSampleRate && mChannelCount < 3 && mReqChannelCount < 3)
3223 {
3224 int channelCount;
3225 // optmization: if mono to mono, use the resampler in stereo to stereo mode to avoid
3226 // stereo to mono post process as the resampler always outputs stereo.
3227 if (mChannelCount == 1 && mReqChannelCount == 2) {
3228 channelCount = 1;
3229 } else {
3230 channelCount = 2;
3231 }
3232 mResampler = AudioResampler::create(16, channelCount, mReqSampleRate);
3233 mResampler->setSampleRate(mSampleRate);
3234 mResampler->setVolume(AudioMixer::UNITY_GAIN, AudioMixer::UNITY_GAIN);
3235 mRsmpOutBuffer = new int32_t[mFrameCount * 2];
3236
3237 // optmization: if mono to mono, alter input frame count as if we were inputing stereo samples
3238 if (mChannelCount == 1 && mReqChannelCount == 1) {
3239 mFrameCount >>= 1;
3240 }
3241
3242 }
3243 mRsmpInIndex = mFrameCount;
3244}
3245
3246// ----------------------------------------------------------------------------
3247
Eric Laurentddb78e72009-07-28 08:44:33 -07003248int AudioFlinger::openOutput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07003249 uint32_t *pSamplingRate,
3250 uint32_t *pFormat,
3251 uint32_t *pChannels,
3252 uint32_t *pLatencyMs,
3253 uint32_t flags)
3254{
3255 status_t status;
3256 PlaybackThread *thread = NULL;
3257 mHardwareStatus = AUDIO_HW_OUTPUT_OPEN;
3258 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3259 uint32_t format = pFormat ? *pFormat : 0;
3260 uint32_t channels = pChannels ? *pChannels : 0;
3261 uint32_t latency = pLatencyMs ? *pLatencyMs : 0;
3262
3263 LOGV("openOutput(), Device %x, SamplingRate %d, Format %d, Channels %x, flags %x",
3264 pDevices ? *pDevices : 0,
3265 samplingRate,
3266 format,
3267 channels,
3268 flags);
3269
3270 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003271 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003272 }
3273 Mutex::Autolock _l(mLock);
3274
3275 AudioStreamOut *output = mAudioHardware->openOutputStream(*pDevices,
3276 (int *)&format,
3277 &channels,
3278 &samplingRate,
3279 &status);
3280 LOGV("openOutput() openOutputStream returned output %p, SamplingRate %d, Format %d, Channels %x, status %d",
3281 output,
3282 samplingRate,
3283 format,
3284 channels,
3285 status);
3286
3287 mHardwareStatus = AUDIO_HW_IDLE;
3288 if (output != 0) {
3289 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
3290 (format != AudioSystem::PCM_16_BIT) ||
3291 (channels != AudioSystem::CHANNEL_OUT_STEREO)) {
3292 thread = new DirectOutputThread(this, output);
Eric Laurentddb78e72009-07-28 08:44:33 -07003293 LOGV("openOutput() created direct output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003294 } else {
3295 thread = new MixerThread(this, output);
Eric Laurentddb78e72009-07-28 08:44:33 -07003296 LOGV("openOutput() created mixer output: ID %d thread %p", (mNextThreadId + 1), thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003297 }
Eric Laurentddb78e72009-07-28 08:44:33 -07003298 mPlaybackThreads.add(++mNextThreadId, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003299
3300 if (pSamplingRate) *pSamplingRate = samplingRate;
3301 if (pFormat) *pFormat = format;
3302 if (pChannels) *pChannels = channels;
3303 if (pLatencyMs) *pLatencyMs = thread->latency();
3304 }
3305
Eric Laurentddb78e72009-07-28 08:44:33 -07003306 return mNextThreadId;
Eric Laurenta553c252009-07-17 12:17:14 -07003307}
3308
Eric Laurentddb78e72009-07-28 08:44:33 -07003309int AudioFlinger::openDuplicateOutput(int output1, int output2)
Eric Laurenta553c252009-07-17 12:17:14 -07003310{
3311 Mutex::Autolock _l(mLock);
Eric Laurentddb78e72009-07-28 08:44:33 -07003312 MixerThread *thread1 = checkMixerThread_l(output1);
3313 MixerThread *thread2 = checkMixerThread_l(output2);
Eric Laurenta553c252009-07-17 12:17:14 -07003314
Eric Laurentddb78e72009-07-28 08:44:33 -07003315 if (thread1 == NULL || thread2 == NULL) {
3316 LOGW("openDuplicateOutput() wrong output mixer type for output %d or %d", output1, output2);
3317 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003318 }
3319
Eric Laurentddb78e72009-07-28 08:44:33 -07003320
3321 DuplicatingThread *thread = new DuplicatingThread(this, thread1);
3322 thread->addOutputTrack(thread2);
3323 mPlaybackThreads.add(++mNextThreadId, thread);
3324 return mNextThreadId;
Eric Laurenta553c252009-07-17 12:17:14 -07003325}
3326
Eric Laurentddb78e72009-07-28 08:44:33 -07003327status_t AudioFlinger::closeOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003328{
Eric Laurent49018a52009-08-04 08:37:05 -07003329 // keep strong reference on the playback thread so that
3330 // it is not destroyed while exit() is executed
3331 sp <PlaybackThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07003332 {
3333 Mutex::Autolock _l(mLock);
3334 thread = checkPlaybackThread_l(output);
3335 if (thread == NULL) {
3336 return BAD_VALUE;
3337 }
3338
Eric Laurentddb78e72009-07-28 08:44:33 -07003339 LOGV("closeOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003340
3341 if (thread->type() == PlaybackThread::MIXER) {
3342 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003343 if (mPlaybackThreads.valueAt(i)->type() == PlaybackThread::DUPLICATING) {
3344 DuplicatingThread *dupThread = (DuplicatingThread *)mPlaybackThreads.valueAt(i).get();
Eric Laurent49018a52009-08-04 08:37:05 -07003345 dupThread->removeOutputTrack((MixerThread *)thread.get());
Eric Laurenta553c252009-07-17 12:17:14 -07003346 }
3347 }
3348 }
Eric Laurentddb78e72009-07-28 08:44:33 -07003349 mPlaybackThreads.removeItem(output);
Eric Laurenta553c252009-07-17 12:17:14 -07003350 }
3351 thread->exit();
3352
Eric Laurent49018a52009-08-04 08:37:05 -07003353 if (thread->type() != PlaybackThread::DUPLICATING) {
3354 mAudioHardware->closeOutputStream(thread->getOutput());
3355 }
Eric Laurenta553c252009-07-17 12:17:14 -07003356 return NO_ERROR;
3357}
3358
Eric Laurentddb78e72009-07-28 08:44:33 -07003359status_t AudioFlinger::suspendOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003360{
3361 Mutex::Autolock _l(mLock);
3362 PlaybackThread *thread = checkPlaybackThread_l(output);
3363
3364 if (thread == NULL) {
3365 return BAD_VALUE;
3366 }
3367
Eric Laurentddb78e72009-07-28 08:44:33 -07003368 LOGV("suspendOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003369 thread->suspend();
3370
3371 return NO_ERROR;
3372}
3373
Eric Laurentddb78e72009-07-28 08:44:33 -07003374status_t AudioFlinger::restoreOutput(int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003375{
3376 Mutex::Autolock _l(mLock);
3377 PlaybackThread *thread = checkPlaybackThread_l(output);
3378
3379 if (thread == NULL) {
3380 return BAD_VALUE;
3381 }
3382
Eric Laurentddb78e72009-07-28 08:44:33 -07003383 LOGV("restoreOutput() %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003384
3385 thread->restore();
3386
3387 return NO_ERROR;
3388}
3389
Eric Laurentddb78e72009-07-28 08:44:33 -07003390int AudioFlinger::openInput(uint32_t *pDevices,
Eric Laurenta553c252009-07-17 12:17:14 -07003391 uint32_t *pSamplingRate,
3392 uint32_t *pFormat,
3393 uint32_t *pChannels,
3394 uint32_t acoustics)
3395{
3396 status_t status;
3397 RecordThread *thread = NULL;
3398 uint32_t samplingRate = pSamplingRate ? *pSamplingRate : 0;
3399 uint32_t format = pFormat ? *pFormat : 0;
3400 uint32_t channels = pChannels ? *pChannels : 0;
3401 uint32_t reqSamplingRate = samplingRate;
3402 uint32_t reqFormat = format;
3403 uint32_t reqChannels = channels;
3404
3405 if (pDevices == NULL || *pDevices == 0) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003406 return 0;
Eric Laurenta553c252009-07-17 12:17:14 -07003407 }
3408 Mutex::Autolock _l(mLock);
3409
3410 AudioStreamIn *input = mAudioHardware->openInputStream(*pDevices,
3411 (int *)&format,
3412 &channels,
3413 &samplingRate,
3414 &status,
3415 (AudioSystem::audio_in_acoustics)acoustics);
3416 LOGV("openInput() openInputStream returned input %p, SamplingRate %d, Format %d, Channels %x, acoustics %x, status %d",
3417 input,
3418 samplingRate,
3419 format,
3420 channels,
3421 acoustics,
3422 status);
3423
3424 // If the input could not be opened with the requested parameters and we can handle the conversion internally,
3425 // try to open again with the proposed parameters. The AudioFlinger can resample the input and do mono to stereo
3426 // or stereo to mono conversions on 16 bit PCM inputs.
3427 if (input == 0 && status == BAD_VALUE &&
3428 reqFormat == format && format == AudioSystem::PCM_16_BIT &&
3429 (samplingRate <= 2 * reqSamplingRate) &&
3430 (AudioSystem::popCount(channels) < 3) && (AudioSystem::popCount(reqChannels) < 3)) {
3431 LOGV("openInput() reopening with proposed sampling rate and channels");
3432 input = mAudioHardware->openInputStream(*pDevices,
3433 (int *)&format,
3434 &channels,
3435 &samplingRate,
3436 &status,
3437 (AudioSystem::audio_in_acoustics)acoustics);
3438 }
3439
3440 if (input != 0) {
3441 // Start record thread
3442 thread = new RecordThread(this, input, reqSamplingRate, reqChannels);
Eric Laurentddb78e72009-07-28 08:44:33 -07003443 mRecordThreads.add(++mNextThreadId, thread);
3444 LOGV("openInput() created record thread: ID %d thread %p", mNextThreadId, thread);
Eric Laurenta553c252009-07-17 12:17:14 -07003445 if (pSamplingRate) *pSamplingRate = reqSamplingRate;
3446 if (pFormat) *pFormat = format;
3447 if (pChannels) *pChannels = reqChannels;
3448
3449 input->standby();
3450 }
3451
Eric Laurentddb78e72009-07-28 08:44:33 -07003452 return mNextThreadId;
Eric Laurenta553c252009-07-17 12:17:14 -07003453}
3454
Eric Laurentddb78e72009-07-28 08:44:33 -07003455status_t AudioFlinger::closeInput(int input)
Eric Laurenta553c252009-07-17 12:17:14 -07003456{
Eric Laurent49018a52009-08-04 08:37:05 -07003457 // keep strong reference on the record thread so that
3458 // it is not destroyed while exit() is executed
3459 sp <RecordThread> thread;
Eric Laurenta553c252009-07-17 12:17:14 -07003460 {
3461 Mutex::Autolock _l(mLock);
3462 thread = checkRecordThread_l(input);
3463 if (thread == NULL) {
3464 return BAD_VALUE;
3465 }
3466
Eric Laurentddb78e72009-07-28 08:44:33 -07003467 LOGV("closeInput() %d", input);
3468 mRecordThreads.removeItem(input);
Eric Laurenta553c252009-07-17 12:17:14 -07003469 }
3470 thread->exit();
3471
Eric Laurent49018a52009-08-04 08:37:05 -07003472 mAudioHardware->closeInputStream(thread->getInput());
3473
Eric Laurenta553c252009-07-17 12:17:14 -07003474 return NO_ERROR;
3475}
3476
Eric Laurentddb78e72009-07-28 08:44:33 -07003477status_t AudioFlinger::setStreamOutput(uint32_t stream, int output)
Eric Laurenta553c252009-07-17 12:17:14 -07003478{
3479 Mutex::Autolock _l(mLock);
3480 MixerThread *dstThread = checkMixerThread_l(output);
3481 if (dstThread == NULL) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003482 LOGW("setStreamOutput() bad output id %d", output);
Eric Laurenta553c252009-07-17 12:17:14 -07003483 return BAD_VALUE;
3484 }
3485
Eric Laurentddb78e72009-07-28 08:44:33 -07003486 LOGV("setStreamOutput() stream %d to output %d", stream, output);
Eric Laurenta553c252009-07-17 12:17:14 -07003487
3488 for (size_t i = 0; i < mPlaybackThreads.size(); i++) {
Eric Laurentddb78e72009-07-28 08:44:33 -07003489 PlaybackThread *thread = mPlaybackThreads.valueAt(i).get();
Eric Laurenta553c252009-07-17 12:17:14 -07003490 if (thread != dstThread &&
3491 thread->type() != PlaybackThread::DIRECT) {
3492 MixerThread *srcThread = (MixerThread *)thread;
3493 SortedVector < sp<MixerThread::Track> > tracks;
3494 SortedVector < wp<MixerThread::Track> > activeTracks;
3495 srcThread->getTracks(tracks, activeTracks, stream);
3496 if (tracks.size()) {
3497 dstThread->putTracks(tracks, activeTracks);
Eric Laurenta553c252009-07-17 12:17:14 -07003498 }
Eric Laurentdd3fbf12009-07-28 06:11:55 -07003499 dstThread->sendConfigEvent(AudioSystem::STREAM_CONFIG_CHANGED, stream);
Eric Laurenta553c252009-07-17 12:17:14 -07003500 }
3501 }
3502
3503 return NO_ERROR;
3504}
3505
3506// checkPlaybackThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07003507AudioFlinger::PlaybackThread *AudioFlinger::checkPlaybackThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07003508{
3509 PlaybackThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07003510 if (mPlaybackThreads.indexOfKey(output) >= 0) {
3511 thread = (PlaybackThread *)mPlaybackThreads.valueFor(output).get();
Eric Laurenta553c252009-07-17 12:17:14 -07003512 }
Eric Laurenta553c252009-07-17 12:17:14 -07003513 return thread;
3514}
3515
3516// checkMixerThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07003517AudioFlinger::MixerThread *AudioFlinger::checkMixerThread_l(int output) const
Eric Laurenta553c252009-07-17 12:17:14 -07003518{
3519 PlaybackThread *thread = checkPlaybackThread_l(output);
3520 if (thread != NULL) {
3521 if (thread->type() == PlaybackThread::DIRECT) {
3522 thread = NULL;
3523 }
3524 }
3525 return (MixerThread *)thread;
3526}
3527
3528// checkRecordThread_l() must be called with AudioFlinger::mLock held
Eric Laurentddb78e72009-07-28 08:44:33 -07003529AudioFlinger::RecordThread *AudioFlinger::checkRecordThread_l(int input) const
Eric Laurenta553c252009-07-17 12:17:14 -07003530{
3531 RecordThread *thread = NULL;
Eric Laurentddb78e72009-07-28 08:44:33 -07003532 if (mRecordThreads.indexOfKey(input) >= 0) {
3533 thread = (RecordThread *)mRecordThreads.valueFor(input).get();
Eric Laurenta553c252009-07-17 12:17:14 -07003534 }
Eric Laurenta553c252009-07-17 12:17:14 -07003535 return thread;
3536}
3537
3538// ----------------------------------------------------------------------------
3539
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003540status_t AudioFlinger::onTransact(
3541 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3542{
3543 return BnAudioFlinger::onTransact(code, data, reply, flags);
3544}
3545
3546// ----------------------------------------------------------------------------
Eric Laurenta553c252009-07-17 12:17:14 -07003547
The Android Open Source Project54b6cfa2008-10-21 07:00:00 -07003548void AudioFlinger::instantiate() {
3549 defaultServiceManager()->addService(
3550 String16("media.audio_flinger"), new AudioFlinger());
3551}
3552
3553}; // namespace android