2 * Copyright (C) 2016 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define LOG_TAG "AAudioServiceStreamBase"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
25 #include "binding/IAAudioService.h"
26 #include "binding/AAudioServiceMessage.h"
27 #include "utility/AudioClock.h"
29 #include "AAudioEndpointManager.h"
30 #include "AAudioService.h"
31 #include "AAudioServiceEndpoint.h"
32 #include "AAudioServiceStreamBase.h"
33 #include "TimestampScheduler.h"
35 using namespace android; // TODO just import names needed
36 using namespace aaudio; // TODO just import names needed
39 * Base class for streams in the service.
43 AAudioServiceStreamBase::AAudioServiceStreamBase(AAudioService &audioService)
44 : mUpMessageQueue(nullptr)
47 , mAudioService(audioService) {
48 mMmapClient.clientUid = -1;
49 mMmapClient.clientPid = -1;
50 mMmapClient.packageName = String16("");
53 AAudioServiceStreamBase::~AAudioServiceStreamBase() {
54 ALOGD("AAudioServiceStreamBase::~AAudioServiceStreamBase() destroying %p", this);
55 // If the stream is deleted when OPEN or in use then audio resources will leak.
56 // This would indicate an internal error. So we want to find this ASAP.
57 LOG_ALWAYS_FATAL_IF(!(getState() == AAUDIO_STREAM_STATE_CLOSED
58 || getState() == AAUDIO_STREAM_STATE_UNINITIALIZED
59 || getState() == AAUDIO_STREAM_STATE_DISCONNECTED),
60 "service stream still open, state = %d", getState());
63 std::string AAudioServiceStreamBase::dumpHeader() {
64 return std::string(" T Handle UId Run State Format Burst Chan Capacity");
67 std::string AAudioServiceStreamBase::dump() const {
68 std::stringstream result;
70 result << " 0x" << std::setfill('0') << std::setw(8) << std::hex << mHandle
71 << std::dec << std::setfill(' ') ;
72 result << std::setw(6) << mMmapClient.clientUid;
73 result << std::setw(4) << (isRunning() ? "yes" : " no");
74 result << std::setw(6) << getState();
75 result << std::setw(7) << getFormat();
76 result << std::setw(6) << mFramesPerBurst;
77 result << std::setw(5) << getSamplesPerFrame();
78 result << std::setw(9) << getBufferCapacity();
83 aaudio_result_t AAudioServiceStreamBase::open(const aaudio::AAudioStreamRequest &request,
84 aaudio_sharing_mode_t sharingMode) {
85 AAudioEndpointManager &mEndpointManager = AAudioEndpointManager::getInstance();
86 aaudio_result_t result = AAUDIO_OK;
88 mMmapClient.clientUid = request.getUserId();
89 mMmapClient.clientPid = request.getProcessId();
90 mMmapClient.packageName.setTo(String16("")); // TODO What should we do here?
92 // Limit scope of lock to avoid recursive lock in close().
94 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
95 if (mUpMessageQueue != nullptr) {
96 ALOGE("AAudioServiceStreamBase::open() called twice");
97 return AAUDIO_ERROR_INVALID_STATE;
100 mUpMessageQueue = new SharedRingBuffer();
101 result = mUpMessageQueue->allocate(sizeof(AAudioServiceMessage),
102 QUEUE_UP_CAPACITY_COMMANDS);
103 if (result != AAUDIO_OK) {
107 // This is not protected by a lock because the stream cannot be
108 // referenced until the service returns a handle to the client.
109 // So only one thread can open a stream.
110 mServiceEndpoint = mEndpointManager.openEndpoint(mAudioService,
113 if (mServiceEndpoint == nullptr) {
114 ALOGE("AAudioServiceStreamBase::open() openEndpoint() failed");
115 result = AAUDIO_ERROR_UNAVAILABLE;
118 // Save a weak pointer that we will use to access the endpoint.
119 mServiceEndpointWeak = mServiceEndpoint;
121 mFramesPerBurst = mServiceEndpoint->getFramesPerBurst();
122 copyFrom(*mServiceEndpoint);
131 aaudio_result_t AAudioServiceStreamBase::close() {
132 aaudio_result_t result = AAUDIO_OK;
133 if (getState() == AAUDIO_STREAM_STATE_CLOSED) {
139 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
140 if (endpoint == nullptr) {
141 result = AAUDIO_ERROR_INVALID_STATE;
143 endpoint->unregisterStream(this);
144 AAudioEndpointManager &endpointManager = AAudioEndpointManager::getInstance();
145 endpointManager.closeEndpoint(endpoint);
147 // AAudioService::closeStream() prevents two threads from closing at the same time.
148 mServiceEndpoint.clear(); // endpoint will hold the pointer until this method returns.
153 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
154 stopTimestampThread();
155 delete mUpMessageQueue;
156 mUpMessageQueue = nullptr;
159 setState(AAUDIO_STREAM_STATE_CLOSED);
163 aaudio_result_t AAudioServiceStreamBase::startDevice() {
164 mClientHandle = AUDIO_PORT_HANDLE_NONE;
165 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
166 if (endpoint == nullptr) {
167 ALOGE("%s() has no endpoint", __func__);
168 return AAUDIO_ERROR_INVALID_STATE;
170 return endpoint->startStream(this, &mClientHandle);
174 * Start the flow of audio data.
176 * An AAUDIO_SERVICE_EVENT_STARTED will be sent to the client when complete.
178 aaudio_result_t AAudioServiceStreamBase::start() {
179 aaudio_result_t result = AAUDIO_OK;
185 // Start with fresh presentation timestamps.
186 mAtomicTimestamp.clear();
188 mClientHandle = AUDIO_PORT_HANDLE_NONE;
189 result = startDevice();
190 if (result != AAUDIO_OK) goto error;
192 // This should happen at the end of the start.
193 sendServiceEvent(AAUDIO_SERVICE_EVENT_STARTED);
194 setState(AAUDIO_STREAM_STATE_STARTED);
195 mThreadEnabled.store(true);
196 result = mTimestampThread.start(this);
197 if (result != AAUDIO_OK) goto error;
206 aaudio_result_t AAudioServiceStreamBase::pause() {
207 aaudio_result_t result = AAUDIO_OK;
212 // Send it now because the timestamp gets rounded up when stopStream() is called below.
213 // Also we don't need the timestamps while we are shutting down.
214 sendCurrentTimestamp();
216 result = stopTimestampThread();
217 if (result != AAUDIO_OK) {
222 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
223 if (endpoint == nullptr) {
224 ALOGE("%s() has no endpoint", __func__);
225 return AAUDIO_ERROR_INVALID_STATE;
227 result = endpoint->stopStream(this, mClientHandle);
228 if (result != AAUDIO_OK) {
229 ALOGE("AAudioServiceStreamShared::pause() mServiceEndpoint returned %d", result);
230 disconnect(); // TODO should we return or pause Base first?
233 sendServiceEvent(AAUDIO_SERVICE_EVENT_PAUSED);
234 setState(AAUDIO_STREAM_STATE_PAUSED);
238 aaudio_result_t AAudioServiceStreamBase::stop() {
239 aaudio_result_t result = AAUDIO_OK;
244 // Send it now because the timestamp gets rounded up when stopStream() is called below.
245 // Also we don't need the timestamps while we are shutting down.
246 sendCurrentTimestamp(); // warning - this calls a virtual function
247 result = stopTimestampThread();
248 if (result != AAUDIO_OK) {
253 sp<AAudioServiceEndpoint> endpoint = mServiceEndpointWeak.promote();
254 if (endpoint == nullptr) {
255 ALOGE("%s() has no endpoint", __func__);
256 return AAUDIO_ERROR_INVALID_STATE;
258 // TODO wait for data to be played out
259 result = endpoint->stopStream(this, mClientHandle);
260 if (result != AAUDIO_OK) {
261 ALOGE("AAudioServiceStreamShared::stop() mServiceEndpoint returned %d", result);
263 // TODO what to do with result here?
266 sendServiceEvent(AAUDIO_SERVICE_EVENT_STOPPED);
267 setState(AAUDIO_STREAM_STATE_STOPPED);
271 aaudio_result_t AAudioServiceStreamBase::stopTimestampThread() {
272 aaudio_result_t result = AAUDIO_OK;
273 // clear flag that tells thread to loop
274 if (mThreadEnabled.exchange(false)) {
275 result = mTimestampThread.stop();
280 aaudio_result_t AAudioServiceStreamBase::flush() {
281 if (getState() != AAUDIO_STREAM_STATE_PAUSED) {
282 ALOGE("AAudioServiceStreamBase::flush() stream not paused, state = %s",
283 AAudio_convertStreamStateToText(mState));
284 return AAUDIO_ERROR_INVALID_STATE;
286 // Data will get flushed when the client receives the FLUSHED event.
287 sendServiceEvent(AAUDIO_SERVICE_EVENT_FLUSHED);
288 setState(AAUDIO_STREAM_STATE_FLUSHED);
292 // implement Runnable, periodically send timestamps to client
293 void AAudioServiceStreamBase::run() {
294 ALOGD("AAudioServiceStreamBase::run() entering ----------------");
295 TimestampScheduler timestampScheduler;
296 timestampScheduler.setBurstPeriod(mFramesPerBurst, getSampleRate());
297 timestampScheduler.start(AudioClock::getNanoseconds());
298 int64_t nextTime = timestampScheduler.nextAbsoluteTime();
299 while(mThreadEnabled.load()) {
300 if (AudioClock::getNanoseconds() >= nextTime) {
301 aaudio_result_t result = sendCurrentTimestamp();
302 if (result != AAUDIO_OK) {
305 nextTime = timestampScheduler.nextAbsoluteTime();
307 // Sleep until it is time to send the next timestamp.
308 // TODO Wait for a signal with a timeout so that we can stop more quickly.
309 AudioClock::sleepUntilNanoTime(nextTime);
312 ALOGD("AAudioServiceStreamBase::run() exiting ----------------");
315 void AAudioServiceStreamBase::disconnect() {
316 if (getState() != AAUDIO_STREAM_STATE_DISCONNECTED) {
317 sendServiceEvent(AAUDIO_SERVICE_EVENT_DISCONNECTED);
318 setState(AAUDIO_STREAM_STATE_DISCONNECTED);
322 aaudio_result_t AAudioServiceStreamBase::sendServiceEvent(aaudio_service_event_t event,
325 AAudioServiceMessage command;
326 command.what = AAudioServiceMessage::code::EVENT;
327 command.event.event = event;
328 command.event.dataDouble = dataDouble;
329 command.event.dataLong = dataLong;
330 return writeUpMessageQueue(&command);
333 aaudio_result_t AAudioServiceStreamBase::writeUpMessageQueue(AAudioServiceMessage *command) {
334 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
335 if (mUpMessageQueue == nullptr) {
336 ALOGE("writeUpMessageQueue(): mUpMessageQueue null! - stream not open");
337 return AAUDIO_ERROR_NULL;
339 int32_t count = mUpMessageQueue->getFifoBuffer()->write(command, 1);
341 ALOGE("writeUpMessageQueue(): Queue full. Did client die?");
342 return AAUDIO_ERROR_WOULD_BLOCK;
348 aaudio_result_t AAudioServiceStreamBase::sendCurrentTimestamp() {
349 AAudioServiceMessage command;
350 // Send a timestamp for the clock model.
351 aaudio_result_t result = getFreeRunningPosition(&command.timestamp.position,
352 &command.timestamp.timestamp);
353 if (result == AAUDIO_OK) {
354 ALOGV("sendCurrentTimestamp() SERVICE %8lld at %lld",
355 (long long) command.timestamp.position,
356 (long long) command.timestamp.timestamp);
357 command.what = AAudioServiceMessage::code::TIMESTAMP_SERVICE;
358 result = writeUpMessageQueue(&command);
360 if (result == AAUDIO_OK) {
361 // Send a hardware timestamp for presentation time.
362 result = getHardwareTimestamp(&command.timestamp.position,
363 &command.timestamp.timestamp);
364 if (result == AAUDIO_OK) {
365 ALOGV("sendCurrentTimestamp() HARDWARE %8lld at %lld",
366 (long long) command.timestamp.position,
367 (long long) command.timestamp.timestamp);
368 command.what = AAudioServiceMessage::code::TIMESTAMP_HARDWARE;
369 result = writeUpMessageQueue(&command);
374 if (result == AAUDIO_ERROR_UNAVAILABLE) { // TODO review best error code
375 result = AAUDIO_OK; // just not available yet, try again later
381 * Get an immutable description of the in-memory queues
382 * used to communicate with the underlying HAL or Service.
384 aaudio_result_t AAudioServiceStreamBase::getDescription(AudioEndpointParcelable &parcelable) {
386 std::lock_guard<std::mutex> lock(mUpMessageQueueLock);
387 if (mUpMessageQueue == nullptr) {
388 ALOGE("getDescription(): mUpMessageQueue null! - stream not open");
389 return AAUDIO_ERROR_NULL;
391 // Gather information on the message queue.
392 mUpMessageQueue->fillParcelable(parcelable,
393 parcelable.mUpMessageQueueParcelable);
395 return getAudioDataDescription(parcelable);
398 void AAudioServiceStreamBase::onVolumeChanged(float volume) {
399 sendServiceEvent(AAUDIO_SERVICE_EVENT_VOLUME, volume);