1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 
18 #define LOG_TAG "AAudioServiceEndpointShared"
19 //#define LOG_NDEBUG 0
20 #include <utils/Log.h>
21 
22 #include <iomanip>
23 #include <iostream>
24 #include <sstream>
25 
26 #include "binding/AAudioServiceMessage.h"
27 #include "client/AudioStreamInternal.h"
28 #include "client/AudioStreamInternalPlay.h"
29 #include "core/AudioStreamBuilder.h"
30 
31 #include "AAudioServiceEndpointShared.h"
32 #include "AAudioServiceStreamShared.h"
33 #include "AAudioServiceStreamMMAP.h"
34 #include "AAudioMixer.h"
35 #include "AAudioService.h"
36 
37 using namespace android;
38 using namespace aaudio;
39 
40 // This is the maximum size in frames. The effective size can be tuned smaller at runtime.
41 #define DEFAULT_BUFFER_CAPACITY   (48 * 8)
42 
dump() const43 std::string AAudioServiceEndpointShared::dump() const {
44     std::stringstream result;
45 
46     result << "  SHARED: sharing exclusive stream with handle = 0x"
47            << std::setfill('0') << std::setw(8)
48            << std::hex << mStreamInternal->getServiceHandle()
49            << std::dec << std::setfill(' ');
50     result << ", XRuns = " << mStreamInternal->getXRunCount();
51     result << "\n";
52     result << "    Running Stream Count: " << mRunningStreamCount << "\n";
53 
54     result << AAudioServiceEndpoint::dump();
55     return result.str();
56 }
57 
58 // Share an AudioStreamInternal.
open(const aaudio::AAudioStreamRequest & request)59 aaudio_result_t AAudioServiceEndpointShared::open(const aaudio::AAudioStreamRequest &request) {
60     aaudio_result_t result = AAUDIO_OK;
61     const AAudioStreamConfiguration &configuration = request.getConstantConfiguration();
62 
63     copyFrom(configuration);
64     mRequestedDeviceId = configuration.getDeviceId();
65 
66     AudioStreamBuilder builder;
67     builder.copyFrom(configuration);
68 
69     builder.setSharingMode(AAUDIO_SHARING_MODE_EXCLUSIVE);
70     // Don't fall back to SHARED because that would cause recursion.
71     builder.setSharingModeMatchRequired(true);
72 
73     builder.setBufferCapacity(DEFAULT_BUFFER_CAPACITY);
74 
75     result = mStreamInternal->open(builder);
76 
77     setSampleRate(mStreamInternal->getSampleRate());
78     setSamplesPerFrame(mStreamInternal->getSamplesPerFrame());
79     setDeviceId(mStreamInternal->getDeviceId());
80     setSessionId(mStreamInternal->getSessionId());
81     setFormat(AUDIO_FORMAT_PCM_FLOAT); // force for mixer
82     mFramesPerBurst = mStreamInternal->getFramesPerBurst();
83 
84     return result;
85 }
86 
close()87 aaudio_result_t AAudioServiceEndpointShared::close() {
88     return getStreamInternal()->releaseCloseFinal();
89 }
90 
91 // Glue between C and C++ callbacks.
aaudio_endpoint_thread_proc(void * arg)92 static void *aaudio_endpoint_thread_proc(void *arg) {
93     assert(arg != nullptr);
94 
95     // The caller passed in a smart pointer to prevent the endpoint from getting deleted
96     // while the thread was launching.
97     sp<AAudioServiceEndpointShared> *endpointForThread =
98             static_cast<sp<AAudioServiceEndpointShared> *>(arg);
99     sp<AAudioServiceEndpointShared> endpoint = *endpointForThread;
100     delete endpointForThread; // Just use scoped smart pointer. Don't need this anymore.
101     void *result = endpoint->callbackLoop();
102     // Close now so that the HW resource is freed and we can open a new device.
103     if (!endpoint->isConnected()) {
104         endpoint->close();
105     }
106 
107     return result;
108 }
109 
startSharingThread_l()110 aaudio_result_t aaudio::AAudioServiceEndpointShared::startSharingThread_l() {
111     // Launch the callback loop thread.
112     int64_t periodNanos = getStreamInternal()->getFramesPerBurst()
113                           * AAUDIO_NANOS_PER_SECOND
114                           / getSampleRate();
115     mCallbackEnabled.store(true);
116     // Pass a smart pointer so the thread can hold a reference.
117     sp<AAudioServiceEndpointShared> *endpointForThread = new sp<AAudioServiceEndpointShared>(this);
118     aaudio_result_t result = getStreamInternal()->createThread(periodNanos,
119                                                                aaudio_endpoint_thread_proc,
120                                                                endpointForThread);
121     if (result != AAUDIO_OK) {
122         // The thread can't delete it so we have to do it here.
123         delete endpointForThread;
124     }
125     return result;
126 }
127 
stopSharingThread()128 aaudio_result_t aaudio::AAudioServiceEndpointShared::stopSharingThread() {
129     mCallbackEnabled.store(false);
130     aaudio_result_t result = getStreamInternal()->joinThread(NULL);
131     return result;
132 }
133 
startStream(sp<AAudioServiceStreamBase> sharedStream,audio_port_handle_t * clientHandle)134 aaudio_result_t AAudioServiceEndpointShared::startStream(sp<AAudioServiceStreamBase> sharedStream,
135                                                          audio_port_handle_t *clientHandle) {
136     aaudio_result_t result = AAUDIO_OK;
137 
138     {
139         std::lock_guard<std::mutex> lock(mLockStreams);
140         if (++mRunningStreamCount == 1) { // atomic
141             result = getStreamInternal()->requestStart();
142             if (result != AAUDIO_OK) {
143                 --mRunningStreamCount;
144             } else {
145                 result = startSharingThread_l();
146                 if (result != AAUDIO_OK) {
147                     getStreamInternal()->requestStop();
148                     --mRunningStreamCount;
149                 }
150             }
151         }
152     }
153 
154     if (result == AAUDIO_OK) {
155         const audio_attributes_t attr = getAudioAttributesFrom(sharedStream.get());
156         result = getStreamInternal()->startClient(
157                 sharedStream->getAudioClient(), &attr, clientHandle);
158         if (result != AAUDIO_OK) {
159             if (--mRunningStreamCount == 0) { // atomic
160                 stopSharingThread();
161                 getStreamInternal()->requestStop();
162             }
163         }
164     }
165 
166     return result;
167 }
168 
stopStream(sp<AAudioServiceStreamBase> sharedStream,audio_port_handle_t clientHandle)169 aaudio_result_t AAudioServiceEndpointShared::stopStream(sp<AAudioServiceStreamBase> sharedStream,
170                                                         audio_port_handle_t clientHandle) {
171     // Ignore result.
172     (void) getStreamInternal()->stopClient(clientHandle);
173 
174     if (--mRunningStreamCount == 0) { // atomic
175         stopSharingThread(); // the sharing thread locks mLockStreams
176         getStreamInternal()->requestStop();
177     }
178     return AAUDIO_OK;
179 }
180 
181 // Get timestamp that was written by the real-time service thread, eg. mixer.
getFreeRunningPosition(int64_t * positionFrames,int64_t * timeNanos)182 aaudio_result_t AAudioServiceEndpointShared::getFreeRunningPosition(int64_t *positionFrames,
183                                                                   int64_t *timeNanos) {
184     if (mAtomicEndpointTimestamp.isValid()) {
185         Timestamp timestamp = mAtomicEndpointTimestamp.read();
186         *positionFrames = timestamp.getPosition();
187         *timeNanos = timestamp.getNanoseconds();
188         return AAUDIO_OK;
189     } else {
190         return AAUDIO_ERROR_UNAVAILABLE;
191     }
192 }
193 
getTimestamp(int64_t * positionFrames,int64_t * timeNanos)194 aaudio_result_t AAudioServiceEndpointShared::getTimestamp(int64_t *positionFrames,
195                                                           int64_t *timeNanos) {
196     aaudio_result_t result = mStreamInternal->getTimestamp(CLOCK_MONOTONIC, positionFrames, timeNanos);
197     if (result == AAUDIO_ERROR_INVALID_STATE) {
198         // getTimestamp() can return AAUDIO_ERROR_INVALID_STATE if the stream has
199         // not completely started. This can cause a race condition that kills the
200         // timestamp service thread.  So we reduce the error to a less serious one
201         // that allows the timestamp thread to continue.
202         result = AAUDIO_ERROR_UNAVAILABLE;
203     }
204     return result;
205 }
206