• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 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 #include "a2dp_encoding_host.h"
18 
19 #include <base/logging.h>
20 #include <errno.h>
21 #include <grp.h>
22 #include <sys/stat.h>
23 
24 #include <memory>
25 
26 #include "a2dp_encoding.h"
27 #include "a2dp_sbc_constants.h"
28 #include "btif_a2dp_source.h"
29 #include "btif_av.h"
30 #include "btif_av_co.h"
31 #include "btif_hf.h"
32 #include "osi/include/log.h"
33 #include "osi/include/properties.h"
34 #include "types/raw_address.h"
35 #include "udrv/include/uipc.h"
36 
37 #define A2DP_DATA_READ_POLL_MS 10
38 #define A2DP_HOST_DATA_PATH "/var/run/bluetooth/audio/.a2dp_data"
39 // TODO(b/198260375): Make A2DP data owner group configurable.
40 #define A2DP_HOST_DATA_GROUP "bluetooth-audio"
41 
42 namespace {
43 
44 std::unique_ptr<tUIPC_STATE> a2dp_uipc = nullptr;
45 
btif_a2dp_data_cb(tUIPC_CH_ID ch_id,tUIPC_EVENT event)46 static void btif_a2dp_data_cb([[maybe_unused]] tUIPC_CH_ID ch_id,
47                               tUIPC_EVENT event) {
48   APPL_TRACE_WARNING("%s: BTIF MEDIA (A2DP-DATA) EVENT %s", __func__,
49                      dump_uipc_event(event));
50 
51   switch (event) {
52     case UIPC_OPEN_EVT:
53       /*
54        * Read directly from media task from here on (keep callback for
55        * connection events.
56        */
57       UIPC_Ioctl(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO,
58                  UIPC_REG_REMOVE_ACTIVE_READSET, NULL);
59       UIPC_Ioctl(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO,
60                  reinterpret_cast<void*>(A2DP_DATA_READ_POLL_MS));
61 
62       // Will start audio on btif_a2dp_on_started
63 
64       /* ACK back when media task is fully started */
65       break;
66 
67     case UIPC_CLOSE_EVT:
68       /*
69        * Send stop request only if we are actively streaming and haven't
70        * received a stop request. Potentially, the audioflinger detached
71        * abnormally.
72        */
73       if (btif_a2dp_source_is_streaming()) {
74         /* Post stop event and wait for audio path to stop */
75         btif_av_stream_stop(RawAddress::kEmpty);
76       }
77       break;
78 
79     default:
80       APPL_TRACE_ERROR("%s: ### A2DP-DATA EVENT %d NOT HANDLED ###", __func__,
81                        event);
82       break;
83   }
84 }
85 
86 // If A2DP_HOST_DATA_GROUP exists we expect audio server and BT both are
87 // in this group therefore have access to A2DP socket. Otherwise audio
88 // server should be in the same group that BT stack runs with to access
89 // A2DP socket.
a2dp_data_path_open()90 static void a2dp_data_path_open() {
91   UIPC_Open(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, btif_a2dp_data_cb,
92             A2DP_HOST_DATA_PATH);
93   struct group* grp = getgrnam(A2DP_HOST_DATA_GROUP);
94   chmod(A2DP_HOST_DATA_PATH, 0770);
95   if (grp) {
96     int res = chown(A2DP_HOST_DATA_PATH, -1, grp->gr_gid);
97     if (res == -1) {
98       LOG(ERROR) << __func__ << " failed: " << strerror(errno);
99     }
100   }
101 }
102 
103 tA2DP_CTRL_CMD a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
104 uint64_t total_bytes_read_;
105 timespec data_position_;
106 uint16_t remote_delay_report_;
107 
108 }  // namespace
109 
110 namespace bluetooth {
111 namespace audio {
112 namespace a2dp {
113 
114 // Invoked by audio server to set audio config (PCM for now)
SetAudioConfig(AudioConfig config)115 bool SetAudioConfig(AudioConfig config) {
116   btav_a2dp_codec_config_t codec_config;
117   codec_config.sample_rate = config.sample_rate;
118   codec_config.bits_per_sample = config.bits_per_sample;
119   codec_config.channel_mode = config.channel_mode;
120   btif_a2dp_source_feeding_update_req(codec_config);
121   return true;
122 }
123 
124 // Invoked by audio server when it has audio data to stream.
StartRequest()125 bool StartRequest() {
126   // Reset total read bytes and timestamp to avoid confusing audio
127   // server at delay calculation.
128   total_bytes_read_ = 0;
129   data_position_ = {0, 0};
130 
131   // Check if a previous request is not finished
132   if (a2dp_pending_cmd_ == A2DP_CTRL_CMD_START) {
133     LOG(INFO) << __func__ << ": A2DP_CTRL_CMD_START in progress";
134     return false;
135   } else if (a2dp_pending_cmd_ != A2DP_CTRL_CMD_NONE) {
136     LOG(WARNING) << __func__ << ": busy in pending_cmd=" << a2dp_pending_cmd_;
137     return false;
138   }
139 
140   // Don't send START request to stack while we are in a call
141   if (!bluetooth::headset::IsCallIdle()) {
142     LOG(ERROR) << __func__ << ": call state is busy";
143     return false;
144   }
145 
146   if (btif_av_stream_started_ready()) {
147     // Already started, ACK back immediately.
148     a2dp_data_path_open();
149     return true;
150   }
151   if (btif_av_stream_ready()) {
152     a2dp_data_path_open();
153     /*
154      * Post start event and wait for audio path to open.
155      * If we are the source, the ACK will be sent after the start
156      * procedure is completed, othewise send it now.
157      */
158     a2dp_pending_cmd_ = A2DP_CTRL_CMD_START;
159     btif_av_stream_start();
160     if (btif_av_get_peer_sep() != AVDT_TSEP_SRC) {
161       LOG(INFO) << __func__ << ": accepted";
162       return false;  // TODO: should be pending
163     }
164     a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
165     return true;
166   }
167   LOG(ERROR) << __func__ << ": AV stream is not ready to start";
168   return false;
169 }
170 
171 // Invoked by audio server when audio streaming is done.
StopRequest()172 bool StopRequest() {
173   if (btif_av_get_peer_sep() == AVDT_TSEP_SNK &&
174       !btif_av_stream_started_ready()) {
175     btif_av_clear_remote_suspend_flag();
176     return true;
177   }
178   LOG(INFO) << __func__ << ": handling";
179   a2dp_pending_cmd_ = A2DP_CTRL_CMD_STOP;
180   btif_av_stream_stop(RawAddress::kEmpty);
181   return true;
182 }
183 
184 // Invoked by audio server to check audio presentation position periodically.
GetPresentationPosition()185 PresentationPosition GetPresentationPosition() {
186   PresentationPosition presentation_position{
187       .remote_delay_report_ns = remote_delay_report_ * 100000u,
188       .total_bytes_read = total_bytes_read_,
189       .data_position = data_position_,
190   };
191   return presentation_position;
192 }
193 
194 // delay reports from AVDTP is based on 1/10 ms (100us)
set_remote_delay(uint16_t delay_report)195 void set_remote_delay(uint16_t delay_report) {
196   remote_delay_report_ = delay_report;
197 }
198 
199 // Inform audio server about offloading codec; not used for now
update_codec_offloading_capabilities(const std::vector<btav_a2dp_codec_config_t> & framework_preference)200 bool update_codec_offloading_capabilities(
201     const std::vector<btav_a2dp_codec_config_t>& framework_preference) {
202   return false;
203 }
204 
205 // Checking if new bluetooth_audio is enabled
is_hal_enabled()206 bool is_hal_enabled() { return true; }
207 
208 // Check if new bluetooth_audio is running with offloading encoders
is_hal_offloading()209 bool is_hal_offloading() { return false; }
210 
211 // Initialize BluetoothAudio HAL: openProvider
init(bluetooth::common::MessageLoopThread * message_loop)212 bool init(bluetooth::common::MessageLoopThread* message_loop) {
213   a2dp_uipc = UIPC_Init();
214   total_bytes_read_ = 0;
215   data_position_ = {};
216   remote_delay_report_ = 0;
217 
218   return true;
219 }
220 
221 // Clean up BluetoothAudio HAL
cleanup()222 void cleanup() {
223   end_session();
224 
225   if (a2dp_uipc != nullptr) {
226     UIPC_Close(*a2dp_uipc, UIPC_CH_ID_ALL);
227   }
228 }
229 
230 // Set up the codec into BluetoothAudio HAL
setup_codec()231 bool setup_codec() {
232   // TODO: setup codec
233   return true;
234 }
235 
start_session()236 void start_session() {
237   // TODO: Notify server; or do we handle it during connected?
238 }
239 
end_session()240 void end_session() {
241   // TODO: Notify server; or do we handle it during disconnected?
242 
243   // Reset remote delay. New value will be set when new session starts.
244   remote_delay_report_ = 0;
245 }
246 
set_audio_low_latency_mode_allowed(bool allowed)247 void set_audio_low_latency_mode_allowed(bool allowed){
248 }
249 
250 
ack_stream_started(const tA2DP_CTRL_ACK & ack)251 void ack_stream_started(const tA2DP_CTRL_ACK& ack) {
252   a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
253   // TODO: Notify server
254 }
255 
ack_stream_suspended(const tA2DP_CTRL_ACK & ack)256 void ack_stream_suspended(const tA2DP_CTRL_ACK& ack) {
257   a2dp_pending_cmd_ = A2DP_CTRL_CMD_NONE;
258   // TODO: Notify server
259 }
260 
261 // Read from the FMQ of BluetoothAudio HAL
read(uint8_t * p_buf,uint32_t len)262 size_t read(uint8_t* p_buf, uint32_t len) {
263   uint32_t bytes_read = 0;
264   if (a2dp_uipc == nullptr) {
265     return 0;
266   }
267   bytes_read = UIPC_Read(*a2dp_uipc, UIPC_CH_ID_AV_AUDIO, p_buf, len);
268   total_bytes_read_ += bytes_read;
269   // MONOTONIC_RAW isn't affected by NTP, audio stack rely on this
270   // to get precise delay calculation.
271   clock_gettime(CLOCK_MONOTONIC_RAW, &data_position_);
272   return bytes_read;
273 }
274 
275 // Check if OPUS codec is supported
is_opus_supported()276 bool is_opus_supported() { return true; }
277 
278 }  // namespace a2dp
279 }  // namespace audio
280 }  // namespace bluetooth
281