1 /*
2 * Copyright 2019 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 "device_port_proxy.h"
18 #define LOG_TAG "BTAudioHalStream"
19
20 #include <android-base/logging.h>
21 #include <android-base/stringprintf.h>
22 #include <cutils/properties.h>
23 #include <errno.h>
24 #include <inttypes.h>
25 #include <log/log.h>
26 #include <string.h>
27 #include <time.h>
28 #include <unistd.h>
29
30 #include <memory>
31
32 #include "BluetoothAudioSession.h"
33 #include "stream_apis.h"
34 #include "utils.h"
35
36 using ::android::base::StringPrintf;
37 using ::android::bluetooth::audio::utils::FrameCount;
38 using ::android::bluetooth::audio::utils::GetAudioParamString;
39 using ::android::bluetooth::audio::utils::ParseAudioParams;
40
41 namespace {
42
43 constexpr unsigned int kMinimumDelayMs = 50;
44 constexpr unsigned int kMaximumDelayMs = 1000;
45 constexpr int kExtraAudioSyncMs = 200;
46
operator <<(std::ostream & os,const audio_config & config)47 std::ostream& operator<<(std::ostream& os, const audio_config& config) {
48 return os << "audio_config[sample_rate=" << config.sample_rate
49 << ", channels=" << StringPrintf("%#x", config.channel_mask)
50 << ", format=" << config.format << "]";
51 }
52
out_calculate_feeding_delay_ms(const BluetoothStreamOut * out,uint32_t * latency_ms,uint64_t * frames=nullptr,struct timespec * timestamp=nullptr)53 void out_calculate_feeding_delay_ms(const BluetoothStreamOut* out,
54 uint32_t* latency_ms,
55 uint64_t* frames = nullptr,
56 struct timespec* timestamp = nullptr) {
57 if (latency_ms == nullptr && frames == nullptr && timestamp == nullptr) {
58 return;
59 }
60
61 // delay_report is the audio delay from the remote headset receiving data to
62 // the headset playing sound in units of nanoseconds
63 uint64_t delay_report_ns = 0;
64 uint64_t delay_report_ms = 0;
65 // absorbed_bytes is the total number of bytes sent by the Bluetooth stack to
66 // a remote headset
67 uint64_t absorbed_bytes = 0;
68 // absorbed_timestamp is the ...
69 struct timespec absorbed_timestamp = {};
70 bool timestamp_fetched = false;
71
72 std::unique_lock<std::mutex> lock(out->mutex_);
73 if (out->bluetooth_output_->GetPresentationPosition(
74 &delay_report_ns, &absorbed_bytes, &absorbed_timestamp)) {
75 delay_report_ms = delay_report_ns / 1000000;
76 // assume kMinimumDelayMs (50ms) < delay_report_ns < kMaximumDelayMs
77 // (1000ms), or it is invalid / ignored and use old delay calculated
78 // by ourselves.
79 if (delay_report_ms > kMinimumDelayMs &&
80 delay_report_ms < kMaximumDelayMs) {
81 timestamp_fetched = true;
82 } else if (delay_report_ms >= kMaximumDelayMs) {
83 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
84 << ", delay_report=" << delay_report_ns << "ns abnormal";
85 }
86 }
87 if (!timestamp_fetched) {
88 // default to old delay if any failure is found when fetching from ports
89 // audio_a2dp_hw:
90 // frames_count = buffer_size / frame_size
91 // latency (sec.) = frames_count / samples_per_second (sample_rate)
92 // Sync from audio_a2dp_hw to add extra delay kExtraAudioSyncMs(+200ms)
93 delay_report_ms =
94 out->frames_count_ * 1000 / out->sample_rate_ + kExtraAudioSyncMs;
95 if (timestamp != nullptr) {
96 clock_gettime(CLOCK_MONOTONIC, &absorbed_timestamp);
97 }
98 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
99 << " uses the legacy delay " << delay_report_ms << " ms";
100 }
101 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
102 << ", delay=" << delay_report_ms << "ms, data=" << absorbed_bytes
103 << " bytes, timestamp=" << absorbed_timestamp.tv_sec << "."
104 << StringPrintf("%09ld", absorbed_timestamp.tv_nsec) << "s";
105
106 if (latency_ms != nullptr) {
107 *latency_ms = delay_report_ms;
108 }
109 if (frames != nullptr) {
110 const uint64_t latency_frames = delay_report_ms * out->sample_rate_ / 1000;
111 *frames = absorbed_bytes / audio_stream_out_frame_size(&out->stream_out_);
112 if (out->frames_presented_ < *frames) {
113 // Are we (the audio HAL) reset?! The stack counter is obsoleted.
114 *frames = out->frames_presented_;
115 } else if ((out->frames_presented_ - *frames) > latency_frames) {
116 // Is the Bluetooth output reset / restarted by AVDTP reconfig?! Its
117 // counter was reset but could not be used.
118 *frames = out->frames_presented_;
119 }
120 // suppose frames would be queued in the headset buffer for delay_report
121 // period, so those frames in buffers should not be included in the number
122 // of presented frames at the timestamp.
123 if (*frames > latency_frames) {
124 *frames -= latency_frames;
125 } else {
126 *frames = 0;
127 }
128 }
129 if (timestamp != nullptr) {
130 *timestamp = absorbed_timestamp;
131 }
132 }
133
in_calculate_starving_delay_ms(const BluetoothStreamIn * in,int64_t * frames,int64_t * time)134 void in_calculate_starving_delay_ms(const BluetoothStreamIn* in,
135 int64_t* frames, int64_t* time) {
136 // delay_report is the audio delay from the remote headset receiving data to
137 // the headset playing sound in units of nanoseconds
138 uint64_t delay_report_ns = 0;
139 uint64_t delay_report_ms = 0;
140 // dispersed_bytes is the total number of bytes received by the Bluetooth
141 // stack from a remote headset
142 uint64_t dispersed_bytes = 0;
143 struct timespec dispersed_timestamp = {};
144
145 std::unique_lock<std::mutex> lock(in->mutex_);
146 in->bluetooth_input_->GetPresentationPosition(
147 &delay_report_ns, &dispersed_bytes, &dispersed_timestamp);
148 delay_report_ms = delay_report_ns / 1000000;
149
150 const uint64_t latency_frames = delay_report_ms * in->sample_rate_ / 1000;
151 *frames = dispersed_bytes / audio_stream_in_frame_size(&in->stream_in_);
152
153 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
154 << ", delay=" << delay_report_ms
155 << "ms, data=" << dispersed_bytes
156 << " bytes, timestamp=" << dispersed_timestamp.tv_sec << "."
157 << StringPrintf("%09ld", dispersed_timestamp.tv_nsec) << "s";
158
159 if (in->frames_presented_ < *frames) {
160 // Was audio HAL reset?! The stack counter is obsoleted.
161 *frames = in->frames_presented_;
162 } else if ((in->frames_presented_ - *frames) > latency_frames) {
163 // Is the Bluetooth input reset ?! Its counter was reset but could not be
164 // used.
165 *frames = in->frames_presented_;
166 }
167 // suppose frames would be queued in the headset buffer for delay_report
168 // period, so those frames in buffers should not be included in the number
169 // of presented frames at the timestamp.
170 if (*frames > latency_frames) {
171 *frames -= latency_frames;
172 } else {
173 *frames = 0;
174 }
175
176 *time = (dispersed_timestamp.tv_sec * 1000000000LL +
177 dispersed_timestamp.tv_nsec) /
178 1000;
179 }
180
181 } // namespace
182
operator <<(std::ostream & os,const BluetoothStreamState & state)183 std::ostream& operator<<(std::ostream& os, const BluetoothStreamState& state) {
184 switch (state) {
185 case BluetoothStreamState::DISABLED:
186 return os << "DISABLED";
187 case BluetoothStreamState::STANDBY:
188 return os << "STANDBY";
189 case BluetoothStreamState::STARTING:
190 return os << "STARTING";
191 case BluetoothStreamState::STARTED:
192 return os << "STARTED";
193 case BluetoothStreamState::SUSPENDING:
194 return os << "SUSPENDING";
195 case BluetoothStreamState::UNKNOWN:
196 return os << "UNKNOWN";
197 default:
198 return os << StringPrintf("%#hhx", state);
199 }
200 }
201
out_get_sample_rate(const struct audio_stream * stream)202 static uint32_t out_get_sample_rate(const struct audio_stream* stream) {
203 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
204 audio_config_t audio_cfg;
205 if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) {
206 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
207 << " audio_cfg=" << audio_cfg;
208 return audio_cfg.sample_rate;
209 } else {
210 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
211 << ", sample_rate=" << out->sample_rate_ << " failed";
212 return out->sample_rate_;
213 }
214 }
215
out_set_sample_rate(struct audio_stream * stream,uint32_t rate)216 static int out_set_sample_rate(struct audio_stream* stream, uint32_t rate) {
217 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
218 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
219 << ", sample_rate=" << out->sample_rate_;
220 return (rate == out->sample_rate_ ? 0 : -1);
221 }
222
out_get_buffer_size(const struct audio_stream * stream)223 static size_t out_get_buffer_size(const struct audio_stream* stream) {
224 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
225 size_t buffer_size =
226 out->frames_count_ * audio_stream_out_frame_size(&out->stream_out_);
227 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
228 << ", buffer_size=" << buffer_size;
229 return buffer_size;
230 }
231
out_get_channels(const struct audio_stream * stream)232 static audio_channel_mask_t out_get_channels(
233 const struct audio_stream* stream) {
234 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
235 audio_config_t audio_cfg;
236 if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) {
237 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
238 << " audio_cfg=" << audio_cfg;
239 return audio_cfg.channel_mask;
240 } else {
241 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
242 << ", channels=" << StringPrintf("%#x", out->channel_mask_)
243 << " failure";
244 return out->channel_mask_;
245 }
246 }
247
out_get_format(const struct audio_stream * stream)248 static audio_format_t out_get_format(const struct audio_stream* stream) {
249 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
250 audio_config_t audio_cfg;
251 if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) {
252 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
253 << " audio_cfg=" << audio_cfg;
254 return audio_cfg.format;
255 } else {
256 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
257 << ", format=" << out->format_ << " failure";
258 return out->format_;
259 }
260 }
261
out_set_format(struct audio_stream * stream,audio_format_t format)262 static int out_set_format(struct audio_stream* stream, audio_format_t format) {
263 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
264 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
265 << ", format=" << out->format_;
266 return (format == out->format_ ? 0 : -1);
267 }
268
out_standby(struct audio_stream * stream)269 static int out_standby(struct audio_stream* stream) {
270 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
271 std::unique_lock<std::mutex> lock(out->mutex_);
272 int retval = 0;
273
274 // out->last_write_time_us_ = 0; unnecessary as a stale write time has same
275 // effect
276 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
277 << " being standby (suspend)";
278 if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) {
279 out->frames_rendered_ = 0;
280 retval = (out->bluetooth_output_->Suspend() ? 0 : -EIO);
281 } else if (out->bluetooth_output_->GetState() ==
282 BluetoothStreamState::STARTING ||
283 out->bluetooth_output_->GetState() ==
284 BluetoothStreamState::SUSPENDING) {
285 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
286 << " NOT ready to be standby";
287 retval = -EBUSY;
288 } else {
289 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_->GetState()
290 << " standby already";
291 }
292 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
293 << " standby (suspend) retval=" << retval;
294
295 return retval;
296 }
297
out_dump(const struct audio_stream * stream,int fd)298 static int out_dump(const struct audio_stream* stream, int fd) {
299 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
300 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState();
301 return 0;
302 }
303
out_set_parameters(struct audio_stream * stream,const char * kvpairs)304 static int out_set_parameters(struct audio_stream* stream,
305 const char* kvpairs) {
306 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
307 std::unique_lock<std::mutex> lock(out->mutex_);
308 int retval = 0;
309
310 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
311 << ", kvpairs=[" << kvpairs << "]";
312
313 std::unordered_map<std::string, std::string> params =
314 ParseAudioParams(kvpairs);
315 if (params.empty()) return retval;
316
317 LOG(VERBOSE) << __func__ << ": ParamsMap=[" << GetAudioParamString(params)
318 << "]";
319
320 audio_config_t audio_cfg;
321 if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end() ||
322 params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end() ||
323 params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
324 if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) {
325 out->sample_rate_ = audio_cfg.sample_rate;
326 out->channel_mask_ = audio_cfg.channel_mask;
327 out->format_ = audio_cfg.format;
328 LOG(VERBOSE) << "state=" << out->bluetooth_output_->GetState()
329 << ", sample_rate=" << out->sample_rate_
330 << ", channels=" << StringPrintf("%#x", out->channel_mask_)
331 << ", format=" << out->format_;
332 } else {
333 LOG(WARNING) << __func__
334 << ": state=" << out->bluetooth_output_->GetState()
335 << " failed to get audio config";
336 }
337 }
338
339 if (params.find(AUDIO_PARAMETER_STREAM_ROUTING) != params.end()) {
340 auto routing_param = params.find("routing");
341 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
342 << ", stream param '" << routing_param->first.c_str() << "="
343 << routing_param->second.c_str() << "'";
344 }
345
346 if (params.find("A2dpSuspended") != params.end() &&
347 out->bluetooth_output_->IsA2dp()) {
348 if (params["A2dpSuspended"] == "true") {
349 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
350 << " stream param stopped";
351 out->frames_rendered_ = 0;
352 if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) {
353 out->bluetooth_output_->Suspend();
354 out->bluetooth_output_->SetState(BluetoothStreamState::DISABLED);
355 } else if (out->bluetooth_output_->GetState() !=
356 BluetoothStreamState::DISABLED) {
357 out->bluetooth_output_->Stop();
358 }
359 } else {
360 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
361 << " stream param standby";
362 if (out->bluetooth_output_->GetState() ==
363 BluetoothStreamState::DISABLED) {
364 out->bluetooth_output_->SetState(BluetoothStreamState::STANDBY);
365 }
366 }
367 }
368
369 if (params.find("LeAudioSuspended") != params.end() &&
370 out->bluetooth_output_->IsLeAudio()) {
371 LOG(INFO) << __func__ << ": LeAudioSuspended found LEAudio="
372 << out->bluetooth_output_->IsLeAudio();
373 if (params["LeAudioSuspended"] == "true") {
374 LOG(INFO) << __func__ << ": LeAudioSuspended true, state="
375 << out->bluetooth_output_->GetState()
376 << " stream param standby";
377 if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) {
378 LOG(INFO) << __func__ << ": Stream is started, suspending LE Audio";
379 } else if (out->bluetooth_output_->GetState() !=
380 BluetoothStreamState::DISABLED) {
381 LOG(INFO) << __func__ << ": Stream is disabled, suspending LE Audio";
382 }
383 } else {
384 LOG(INFO) << __func__ << ": LeAudioSuspended false, state="
385 << out->bluetooth_output_->GetState()
386 << " stream param standby";
387 if (out->bluetooth_output_->GetState() ==
388 BluetoothStreamState::DISABLED) {
389 LOG(INFO) << __func__ << ": Stream is disabled, unsuspending LE Audio";
390 }
391 }
392 }
393
394 if (params.find(AUDIO_PARAMETER_KEY_CLOSING) != params.end()) {
395 if (params[AUDIO_PARAMETER_KEY_CLOSING] == "true") {
396 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
397 << " stream param closing, disallow any writes?";
398 if (out->bluetooth_output_->GetState() !=
399 BluetoothStreamState::DISABLED) {
400 out->frames_rendered_ = 0;
401 out->frames_presented_ = 0;
402 out->bluetooth_output_->Stop();
403 }
404 }
405 }
406
407 if (params.find(AUDIO_PARAMETER_KEY_EXITING) != params.end()) {
408 if (params[AUDIO_PARAMETER_KEY_EXITING] == "1") {
409 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
410 << " stream param exiting";
411 if (out->bluetooth_output_->GetState() !=
412 BluetoothStreamState::DISABLED) {
413 out->frames_rendered_ = 0;
414 out->frames_presented_ = 0;
415 out->bluetooth_output_->Stop();
416 }
417 }
418 }
419
420 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
421 << ", kvpairs=[" << kvpairs << "], retval=" << retval;
422 return retval;
423 }
424
out_get_parameters(const struct audio_stream * stream,const char * keys)425 static char* out_get_parameters(const struct audio_stream* stream,
426 const char* keys) {
427 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
428 std::unique_lock<std::mutex> lock(out->mutex_);
429
430 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
431 << ", keys=[" << keys << "]";
432
433 std::unordered_map<std::string, std::string> params = ParseAudioParams(keys);
434 if (params.empty()) return strdup("");
435
436 audio_config_t audio_cfg;
437 if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) {
438 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
439 << " audio_cfg=" << audio_cfg;
440 } else {
441 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_->GetState()
442 << " failed to get audio config";
443 }
444
445 std::unordered_map<std::string, std::string> return_params;
446 if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end()) {
447 std::string param;
448 if (audio_cfg.sample_rate == 16000) {
449 param = "16000";
450 }
451 if (audio_cfg.sample_rate == 24000) {
452 param = "24000";
453 }
454 if (audio_cfg.sample_rate == 44100) {
455 param = "44100";
456 }
457 if (audio_cfg.sample_rate == 48000) {
458 param = "48000";
459 }
460 if (audio_cfg.sample_rate == 88200) {
461 param = "88200";
462 }
463 if (audio_cfg.sample_rate == 96000) {
464 param = "96000";
465 }
466 if (audio_cfg.sample_rate == 176400) {
467 param = "176400";
468 }
469 if (audio_cfg.sample_rate == 192000) {
470 param = "192000";
471 }
472 return_params[AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES] = param;
473 }
474
475 if (params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end()) {
476 std::string param;
477 if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_MONO) {
478 param = "AUDIO_CHANNEL_OUT_MONO";
479 }
480 if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_STEREO) {
481 param = "AUDIO_CHANNEL_OUT_STEREO";
482 }
483 return_params[AUDIO_PARAMETER_STREAM_SUP_CHANNELS] = param;
484 }
485
486 if (params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
487 std::string param;
488 if (audio_cfg.format == AUDIO_FORMAT_PCM_16_BIT) {
489 param = "AUDIO_FORMAT_PCM_16_BIT";
490 }
491 if (audio_cfg.format == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
492 param = "AUDIO_FORMAT_PCM_24_BIT_PACKED";
493 }
494 if (audio_cfg.format == AUDIO_FORMAT_PCM_8_24_BIT) {
495 param = "AUDIO_FORMAT_PCM_8_24_BIT";
496 }
497 if (audio_cfg.format == AUDIO_FORMAT_PCM_32_BIT) {
498 param = "AUDIO_FORMAT_PCM_32_BIT";
499 }
500 return_params[AUDIO_PARAMETER_STREAM_SUP_FORMATS] = param;
501 }
502
503 std::string result;
504 for (const auto& ptr : return_params) {
505 result += ptr.first + "=" + ptr.second + ";";
506 }
507
508 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
509 << ", result=[" << result << "]";
510 return strdup(result.c_str());
511 }
512
out_get_latency_ms(const struct audio_stream_out * stream)513 static uint32_t out_get_latency_ms(const struct audio_stream_out* stream) {
514 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
515 uint32_t latency_ms = 0;
516 out_calculate_feeding_delay_ms(out, &latency_ms);
517 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
518 << ", latency=" << latency_ms << "ms";
519 return latency_ms;
520 }
521
out_set_volume(struct audio_stream_out * stream,float left,float right)522 static int out_set_volume(struct audio_stream_out* stream, float left,
523 float right) {
524 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
525 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
526 << ", Left=" << left << ", Right=" << right;
527 return -1;
528 }
529
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)530 static ssize_t out_write(struct audio_stream_out* stream, const void* buffer,
531 size_t bytes) {
532 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
533 std::unique_lock<std::mutex> lock(out->mutex_);
534 size_t totalWritten = 0;
535
536 if (out->bluetooth_output_->GetState() != BluetoothStreamState::STARTED) {
537 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
538 << " first time bytes=" << bytes;
539 lock.unlock();
540 if (stream->resume(stream)) {
541 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_->GetState()
542 << " failed to resume";
543 if (out->bluetooth_output_->GetState() ==
544 BluetoothStreamState::DISABLED) {
545 // drop data for cases of A2dpSuspended=true / closing=true
546 totalWritten = bytes;
547 }
548 usleep(out->preferred_data_interval_us);
549 return totalWritten;
550 }
551 lock.lock();
552 }
553 lock.unlock();
554 totalWritten = out->bluetooth_output_->WriteData(buffer, bytes);
555 lock.lock();
556
557 struct timespec ts = {.tv_sec = 0, .tv_nsec = 0};
558 clock_gettime(CLOCK_MONOTONIC, &ts);
559 if (totalWritten) {
560 const size_t frames = bytes / audio_stream_out_frame_size(stream);
561 out->frames_rendered_ += frames;
562 out->frames_presented_ += frames;
563 out->last_write_time_us_ = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
564 } else {
565 const int64_t now = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
566 const int64_t elapsed_time_since_last_write =
567 now - out->last_write_time_us_;
568 // frames_count = written_data / frame_size
569 // play_time (ms) = frames_count / (sample_rate (Sec.) / 1000000)
570 // sleep_time (ms) = play_time - elapsed_time
571 int64_t sleep_time = bytes * 1000000LL /
572 audio_stream_out_frame_size(stream) /
573 out_get_sample_rate(&stream->common) -
574 elapsed_time_since_last_write;
575 if (sleep_time > 0) {
576 LOG(VERBOSE) << __func__ << ": sleep " << (sleep_time / 1000)
577 << " ms when writting FMQ datapath";
578 lock.unlock();
579 usleep(sleep_time);
580 lock.lock();
581 } else {
582 // we don't sleep when we exit standby (this is typical for a real alsa
583 // buffer).
584 sleep_time = 0;
585 }
586 out->last_write_time_us_ = now + sleep_time;
587 }
588 return totalWritten;
589 }
590
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)591 static int out_get_render_position(const struct audio_stream_out* stream,
592 uint32_t* dsp_frames) {
593 if (dsp_frames == nullptr) return -EINVAL;
594
595 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
596 // frames = (latency (ms) / 1000) * samples_per_second (sample_rate)
597 const uint64_t latency_frames =
598 (uint64_t)out_get_latency_ms(stream) * out->sample_rate_ / 1000;
599 if (out->frames_rendered_ >= latency_frames) {
600 *dsp_frames = (uint32_t)(out->frames_rendered_ - latency_frames);
601 } else {
602 *dsp_frames = 0;
603 }
604
605 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
606 << ", dsp_frames=" << *dsp_frames;
607 return 0;
608 }
609
out_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)610 static int out_add_audio_effect(const struct audio_stream* stream,
611 effect_handle_t effect) {
612 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
613 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
614 << ", effect=" << effect;
615 return 0;
616 }
617
out_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)618 static int out_remove_audio_effect(const struct audio_stream* stream,
619 effect_handle_t effect) {
620 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
621 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
622 << ", effect=" << effect;
623 return 0;
624 }
625
out_get_next_write_timestamp(const struct audio_stream_out * stream,int64_t * timestamp)626 static int out_get_next_write_timestamp(const struct audio_stream_out* stream,
627 int64_t* timestamp) {
628 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
629 *timestamp = 0;
630 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
631 << ", timestamp=" << *timestamp;
632 return -EINVAL;
633 }
634
out_pause(struct audio_stream_out * stream)635 static int out_pause(struct audio_stream_out* stream) {
636 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
637 std::unique_lock<std::mutex> lock(out->mutex_);
638 int retval = 0;
639 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
640 << ", pausing (suspend)";
641 if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) {
642 out->frames_rendered_ = 0;
643 retval = (out->bluetooth_output_->Suspend() ? 0 : -EIO);
644 } else if (out->bluetooth_output_->GetState() ==
645 BluetoothStreamState::STARTING ||
646 out->bluetooth_output_->GetState() ==
647 BluetoothStreamState::SUSPENDING) {
648 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
649 << " NOT ready to pause?!";
650 retval = -EBUSY;
651 } else {
652 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_->GetState()
653 << " paused already";
654 }
655 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
656 << ", pausing (suspend) retval=" << retval;
657
658 return retval;
659 }
660
out_resume(struct audio_stream_out * stream)661 static int out_resume(struct audio_stream_out* stream) {
662 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
663 std::unique_lock<std::mutex> lock(out->mutex_);
664 int retval = 0;
665
666 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
667 << ", resuming (start)";
668 if (out->bluetooth_output_->GetState() == BluetoothStreamState::STANDBY) {
669 retval = (out->bluetooth_output_->Start() ? 0 : -EIO);
670 } else if (out->bluetooth_output_->GetState() ==
671 BluetoothStreamState::STARTING ||
672 out->bluetooth_output_->GetState() ==
673 BluetoothStreamState::SUSPENDING) {
674 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
675 << " NOT ready to resume?!";
676 retval = -EBUSY;
677 } else if (out->bluetooth_output_->GetState() ==
678 BluetoothStreamState::DISABLED) {
679 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
680 << " NOT allow to resume?!";
681 retval = -EINVAL;
682 } else {
683 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_->GetState()
684 << " resumed already";
685 }
686 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
687 << ", resuming (start) retval=" << retval;
688
689 return retval;
690 }
691
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)692 static int out_get_presentation_position(const struct audio_stream_out* stream,
693 uint64_t* frames,
694 struct timespec* timestamp) {
695 if (frames == nullptr || timestamp == nullptr) {
696 return -EINVAL;
697 }
698
699 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
700 out_calculate_feeding_delay_ms(out, nullptr, frames, timestamp);
701 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
702 << ", frames=" << *frames << ", timestamp=" << timestamp->tv_sec
703 << "." << StringPrintf("%09ld", timestamp->tv_nsec) << "s";
704 return 0;
705 }
706
out_update_source_metadata(struct audio_stream_out * stream,const struct source_metadata * source_metadata)707 static void out_update_source_metadata(
708 struct audio_stream_out* stream,
709 const struct source_metadata* source_metadata) {
710 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
711 std::unique_lock<std::mutex> lock(out->mutex_);
712 if (source_metadata == nullptr || source_metadata->track_count == 0) {
713 return;
714 }
715 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
716 << ", " << source_metadata->track_count << " track(s)";
717 out->bluetooth_output_->UpdateSourceMetadata(source_metadata);
718 }
719
adev_open_output_stream(struct audio_hw_device * dev,audio_io_handle_t handle,audio_devices_t devices,audio_output_flags_t flags,struct audio_config * config,struct audio_stream_out ** stream_out,const char * address __unused)720 int adev_open_output_stream(struct audio_hw_device* dev,
721 audio_io_handle_t handle, audio_devices_t devices,
722 audio_output_flags_t flags,
723 struct audio_config* config,
724 struct audio_stream_out** stream_out,
725 const char* address __unused) {
726 *stream_out = nullptr;
727 auto out = std::make_unique<BluetoothStreamOut>();
728 if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession::
729 IsAidlAvailable()) {
730 out->bluetooth_output_ = std::make_unique<
731 ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlOut>();
732 out->is_aidl = true;
733 } else {
734 out->bluetooth_output_ = std::make_unique<
735 ::android::bluetooth::audio::hidl::BluetoothAudioPortHidlOut>();
736 out->is_aidl = false;
737 }
738 if (!out->bluetooth_output_->SetUp(devices)) {
739 out->bluetooth_output_ = nullptr;
740 LOG(ERROR) << __func__ << ": cannot init HAL";
741 return -EINVAL;
742 }
743 LOG(VERBOSE) << __func__ << ": device=" << StringPrintf("%#x", devices);
744
745 out->stream_out_.common.get_sample_rate = out_get_sample_rate;
746 out->stream_out_.common.set_sample_rate = out_set_sample_rate;
747 out->stream_out_.common.get_buffer_size = out_get_buffer_size;
748 out->stream_out_.common.get_channels = out_get_channels;
749 out->stream_out_.common.get_format = out_get_format;
750 out->stream_out_.common.set_format = out_set_format;
751 out->stream_out_.common.standby = out_standby;
752 out->stream_out_.common.dump = out_dump;
753 out->stream_out_.common.set_parameters = out_set_parameters;
754 out->stream_out_.common.get_parameters = out_get_parameters;
755 out->stream_out_.common.add_audio_effect = out_add_audio_effect;
756 out->stream_out_.common.remove_audio_effect = out_remove_audio_effect;
757 out->stream_out_.get_latency = out_get_latency_ms;
758 out->stream_out_.set_volume = out_set_volume;
759 out->stream_out_.write = out_write;
760 out->stream_out_.get_render_position = out_get_render_position;
761 out->stream_out_.get_next_write_timestamp = out_get_next_write_timestamp;
762 out->stream_out_.pause = out_pause;
763 out->stream_out_.resume = out_resume;
764 out->stream_out_.get_presentation_position = out_get_presentation_position;
765 out->stream_out_.update_source_metadata = out_update_source_metadata;
766 /** Fix Coverity Scan Issue @{ */
767 out->channel_mask_ = AUDIO_CHANNEL_NONE;
768 /** @} */
769
770 if (!out->bluetooth_output_->LoadAudioConfig(config)) {
771 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_->GetState()
772 << " failed to get audio config";
773 }
774 // WAR to support Mono / 16 bits per sample as the Bluetooth stack required
775 if (config->channel_mask == AUDIO_CHANNEL_OUT_MONO &&
776 config->format == AUDIO_FORMAT_PCM_16_BIT) {
777 LOG(INFO) << __func__
778 << ": force channels=" << StringPrintf("%#x", out->channel_mask_)
779 << " to be AUDIO_CHANNEL_OUT_STEREO";
780 out->bluetooth_output_->ForcePcmStereoToMono(true);
781 config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
782 }
783 out->sample_rate_ = config->sample_rate;
784 out->channel_mask_ = config->channel_mask;
785 out->format_ = config->format;
786 // frame is number of samples per channel
787
788 size_t preferred_data_interval_us = kBluetoothDefaultOutputBufferMs * 1000;
789 if (out->bluetooth_output_->GetPreferredDataIntervalUs(
790 &preferred_data_interval_us) &&
791 preferred_data_interval_us != 0) {
792 out->preferred_data_interval_us = preferred_data_interval_us;
793 } else {
794 out->preferred_data_interval_us = kBluetoothDefaultOutputBufferMs * 1000;
795 }
796
797 // Ensure minimum buffer duration for spatialized output
798 if ((flags == (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER) ||
799 flags == AUDIO_OUTPUT_FLAG_SPATIALIZER) &&
800 out->preferred_data_interval_us <
801 kBluetoothSpatializerOutputBufferMs * 1000) {
802 out->preferred_data_interval_us =
803 kBluetoothSpatializerOutputBufferMs * 1000;
804 LOG(INFO) << __func__
805 << ": adjusting to minimum buffer duration for spatializer: "
806 << StringPrintf("%zu", out->preferred_data_interval_us);
807 }
808
809 out->frames_count_ =
810 FrameCount(out->preferred_data_interval_us, out->sample_rate_);
811
812 out->frames_rendered_ = 0;
813 out->frames_presented_ = 0;
814
815 BluetoothStreamOut* out_ptr = out.release();
816 {
817 auto* bluetooth_device = reinterpret_cast<BluetoothAudioDevice*>(dev);
818 std::lock_guard<std::mutex> guard(bluetooth_device->mutex_);
819 bluetooth_device->opened_stream_outs_.push_back(out_ptr);
820 }
821
822 *stream_out = &out_ptr->stream_out_;
823 LOG(INFO) << __func__ << ": state=" << out_ptr->bluetooth_output_->GetState()
824 << ", sample_rate=" << out_ptr->sample_rate_
825 << ", channels=" << StringPrintf("%#x", out_ptr->channel_mask_)
826 << ", format=" << out_ptr->format_
827 << ", preferred_data_interval_us="
828 << out_ptr->preferred_data_interval_us
829 << ", frames=" << out_ptr->frames_count_;
830 return 0;
831 }
832
adev_close_output_stream(struct audio_hw_device * dev,struct audio_stream_out * stream)833 void adev_close_output_stream(struct audio_hw_device* dev,
834 struct audio_stream_out* stream) {
835 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
836 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
837 << ", stopping";
838 {
839 auto* bluetooth_device = reinterpret_cast<BluetoothAudioDevice*>(dev);
840 std::lock_guard<std::mutex> guard(bluetooth_device->mutex_);
841 bluetooth_device->opened_stream_outs_.remove(out);
842 }
843 if (out->bluetooth_output_->GetState() != BluetoothStreamState::DISABLED) {
844 out->frames_rendered_ = 0;
845 out->frames_presented_ = 0;
846 out->bluetooth_output_->Stop();
847 }
848 out->bluetooth_output_->TearDown();
849 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
850 << ", stopped";
851 delete out;
852 }
853
adev_get_input_buffer_size(const struct audio_hw_device * dev,const struct audio_config * config)854 size_t adev_get_input_buffer_size(const struct audio_hw_device* dev,
855 const struct audio_config* config) {
856 /* TODO: Adjust this value */
857 LOG(VERBOSE) << __func__;
858 return 320;
859 }
860
in_get_sample_rate(const struct audio_stream * stream)861 static uint32_t in_get_sample_rate(const struct audio_stream* stream) {
862 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
863
864 return in->sample_rate_;
865 }
866
in_set_sample_rate(struct audio_stream * stream,uint32_t rate)867 static int in_set_sample_rate(struct audio_stream* stream, uint32_t rate) {
868 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
869
870 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
871 << ", sample_rate=" << in->sample_rate_;
872 return (rate == in->sample_rate_ ? 0 : -ENOSYS);
873 }
874
in_get_buffer_size(const struct audio_stream * stream)875 static size_t in_get_buffer_size(const struct audio_stream* stream) {
876 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
877 size_t buffer_size =
878 in->frames_count_ * audio_stream_in_frame_size(&in->stream_in_);
879 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
880 << ", buffer_size=" << buffer_size;
881 return buffer_size;
882 }
883
in_get_channels(const struct audio_stream * stream)884 static audio_channel_mask_t in_get_channels(const struct audio_stream* stream) {
885 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
886 audio_config_t audio_cfg;
887 if (in->bluetooth_input_->LoadAudioConfig(&audio_cfg)) {
888 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
889 << " audio_cfg=" << audio_cfg;
890 return audio_cfg.channel_mask;
891 } else {
892 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
893 << ", channels=" << StringPrintf("%#x", in->channel_mask_)
894 << " failure";
895 return in->channel_mask_;
896 }
897 }
898
in_get_format(const struct audio_stream * stream)899 static audio_format_t in_get_format(const struct audio_stream* stream) {
900 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
901 audio_config_t audio_cfg;
902 if (in->bluetooth_input_->LoadAudioConfig(&audio_cfg)) {
903 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
904 << " audio_cfg=" << audio_cfg;
905 return audio_cfg.format;
906 } else {
907 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
908 << ", format=" << in->format_ << " failure";
909 return in->format_;
910 }
911 }
912
in_set_format(struct audio_stream * stream,audio_format_t format)913 static int in_set_format(struct audio_stream* stream, audio_format_t format) {
914 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
915 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
916 << ", format=" << in->format_;
917 return (format == in->format_ ? 0 : -ENOSYS);
918 }
919
in_state_transition_timeout(BluetoothStreamIn * in,std::unique_lock<std::mutex> & lock,const BluetoothStreamState & state,uint16_t timeout_ms)920 static bool in_state_transition_timeout(BluetoothStreamIn* in,
921 std::unique_lock<std::mutex>& lock,
922 const BluetoothStreamState& state,
923 uint16_t timeout_ms) {
924 /* Don't loose suspend request, AF will not retry */
925 while (in->bluetooth_input_->GetState() == state) {
926 lock.unlock();
927 usleep(1000);
928 lock.lock();
929
930 /* Don't block AF forever */
931 if (--timeout_ms <= 0) {
932 LOG(WARNING) << __func__ << ", can't suspend - stucked in: "
933 << static_cast<int>(state) << " state";
934 return false;
935 }
936 }
937
938 return true;
939 }
940
in_standby(struct audio_stream * stream)941 static int in_standby(struct audio_stream* stream) {
942 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
943 std::unique_lock<std::mutex> lock(in->mutex_);
944 int retval = 0;
945
946 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
947 << " being standby (suspend)";
948
949 /* Give some time to start up */
950 if (!in_state_transition_timeout(in, lock, BluetoothStreamState::STARTING,
951 kBluetoothDefaultInputStateTimeoutMs)) {
952 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
953 << " NOT ready to by standby";
954 return retval;
955 }
956
957 if (in->bluetooth_input_->GetState() == BluetoothStreamState::STARTED) {
958 retval = (in->bluetooth_input_->Suspend() ? 0 : -EIO);
959 } else if (in->bluetooth_input_->GetState() !=
960 BluetoothStreamState::SUSPENDING) {
961 LOG(DEBUG) << __func__ << ": state=" << in->bluetooth_input_->GetState()
962 << " standby already";
963 return retval;
964 }
965
966 /* Give some time to suspend */
967 if (!in_state_transition_timeout(in, lock, BluetoothStreamState::SUSPENDING,
968 kBluetoothDefaultInputStateTimeoutMs)) {
969 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
970 << " NOT ready to by standby";
971 return 0;
972 }
973
974 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
975 << " standby (suspend) retval=" << retval;
976
977 return retval;
978 }
979
in_dump(const struct audio_stream * stream,int fd)980 static int in_dump(const struct audio_stream* stream, int fd) {
981 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
982 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState();
983
984 return 0;
985 }
986
in_set_parameters(struct audio_stream * stream,const char * kvpairs)987 static int in_set_parameters(struct audio_stream* stream, const char* kvpairs) {
988 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
989 std::unique_lock<std::mutex> lock(in->mutex_);
990 int retval = 0;
991
992 LOG(INFO) << __func__
993 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState()
994 << ", kvpairs=[" << kvpairs << "]";
995
996 std::unordered_map<std::string, std::string> params =
997 ParseAudioParams(kvpairs);
998
999 if (params.empty()) return retval;
1000
1001 LOG(INFO) << __func__ << ": ParamsMap=[" << GetAudioParamString(params)
1002 << "]";
1003
1004 return retval;
1005 }
1006
in_get_parameters(const struct audio_stream * stream,const char * keys)1007 static char* in_get_parameters(const struct audio_stream* stream,
1008 const char* keys) {
1009 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1010 std::unique_lock<std::mutex> lock(in->mutex_);
1011
1012 LOG(VERBOSE) << __func__
1013 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState()
1014 << ", keys=[" << keys << "]";
1015
1016 std::unordered_map<std::string, std::string> params = ParseAudioParams(keys);
1017 if (params.empty()) return strdup("");
1018
1019 audio_config_t audio_cfg;
1020 if (in->bluetooth_input_->LoadAudioConfig(&audio_cfg)) {
1021 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1022 << " audio_cfg=" << audio_cfg;
1023 } else {
1024 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1025 << " failed to get audio config";
1026 }
1027
1028 std::unordered_map<std::string, std::string> return_params;
1029
1030 /* TODO: Implement parameter getter */
1031
1032 std::string result;
1033 for (const auto& ptr : return_params) {
1034 result += ptr.first + "=" + ptr.second + ";";
1035 }
1036
1037 return strdup(result.c_str());
1038 }
1039
in_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1040 static int in_add_audio_effect(const struct audio_stream* stream,
1041 effect_handle_t effect) {
1042 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1043 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1044 << ", effect=" << effect;
1045 return 0;
1046 }
1047
in_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1048 static int in_remove_audio_effect(const struct audio_stream* stream,
1049 effect_handle_t effect) {
1050 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1051 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1052 << ", effect=" << effect;
1053 return 0;
1054 }
1055
in_set_gain(struct audio_stream_in * stream,float gain)1056 static int in_set_gain(struct audio_stream_in* stream, float gain) {
1057 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1058 LOG(VERBOSE) << __func__
1059 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1060
1061 return 0;
1062 }
1063
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)1064 static ssize_t in_read(struct audio_stream_in* stream, void* buffer,
1065 size_t bytes) {
1066 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
1067 std::unique_lock<std::mutex> lock(in->mutex_);
1068 size_t totalRead = 0;
1069
1070 /* Give some time to start up */
1071 if (!in_state_transition_timeout(in, lock, BluetoothStreamState::STARTING,
1072 kBluetoothDefaultInputStateTimeoutMs))
1073 return -EBUSY;
1074
1075 if (in->bluetooth_input_->GetState() != BluetoothStreamState::STARTED) {
1076 LOG(INFO) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1077 << " first time bytes=" << bytes;
1078
1079 int retval = 0;
1080 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1081 << ", starting";
1082 if (in->bluetooth_input_->GetState() == BluetoothStreamState::STANDBY) {
1083 retval = (in->bluetooth_input_->Start() ? 0 : -EIO);
1084 } else if (in->bluetooth_input_->GetState() ==
1085 BluetoothStreamState::SUSPENDING) {
1086 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1087 << " NOT ready to start?!";
1088 retval = -EBUSY;
1089 } else if (in->bluetooth_input_->GetState() ==
1090 BluetoothStreamState::DISABLED) {
1091 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1092 << " NOT allow to start?!";
1093 retval = -EINVAL;
1094 } else {
1095 LOG(DEBUG) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1096 << " started already";
1097 }
1098 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1099 << ", starting (start) retval=" << retval;
1100
1101 if (retval) {
1102 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1103 << " failed to start";
1104 return retval;
1105 }
1106 }
1107
1108 lock.unlock();
1109 totalRead = in->bluetooth_input_->ReadData(buffer, bytes);
1110 lock.lock();
1111
1112 struct timespec ts = {.tv_sec = 0, .tv_nsec = 0};
1113 clock_gettime(CLOCK_MONOTONIC, &ts);
1114 in->last_read_time_us_ = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
1115
1116 const size_t frames = totalRead / audio_stream_in_frame_size(stream);
1117 in->frames_presented_ += frames;
1118
1119 return totalRead;
1120 }
1121
in_get_input_frames_lost(struct audio_stream_in * stream)1122 static uint32_t in_get_input_frames_lost(struct audio_stream_in* stream) {
1123 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1124 LOG(VERBOSE) << __func__
1125 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1126
1127 return 0;
1128 }
1129
in_get_capture_position(const struct audio_stream_in * stream,int64_t * frames,int64_t * time)1130 static int in_get_capture_position(const struct audio_stream_in* stream,
1131 int64_t* frames, int64_t* time) {
1132 if (stream == NULL || frames == NULL || time == NULL) {
1133 return -EINVAL;
1134 }
1135 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1136
1137 if (in->bluetooth_input_->GetState() == BluetoothStreamState::STANDBY) {
1138 LOG(WARNING) << __func__ << ": state= " << in->bluetooth_input_->GetState();
1139 return -ENOSYS;
1140 }
1141
1142 in_calculate_starving_delay_ms(in, frames, time);
1143
1144 return 0;
1145 }
1146
in_start(const struct audio_stream_in * stream)1147 static int in_start(const struct audio_stream_in* stream) {
1148 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1149 LOG(VERBOSE) << __func__
1150 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1151
1152 return 0;
1153 }
1154
in_stop(const struct audio_stream_in * stream)1155 static int in_stop(const struct audio_stream_in* stream) {
1156 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1157 LOG(VERBOSE) << __func__
1158 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1159
1160 return 0;
1161 }
1162
in_create_mmap_buffer(const struct audio_stream_in * stream,int32_t min_size_frames,struct audio_mmap_buffer_info * info)1163 static int in_create_mmap_buffer(const struct audio_stream_in* stream,
1164 int32_t min_size_frames,
1165 struct audio_mmap_buffer_info* info) {
1166 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1167 LOG(VERBOSE) << __func__
1168 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1169
1170 return -ENOSYS;
1171 }
1172
in_get_mmap_position(const struct audio_stream_in * stream,struct audio_mmap_position * position)1173 static int in_get_mmap_position(const struct audio_stream_in* stream,
1174 struct audio_mmap_position* position) {
1175 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1176 LOG(VERBOSE) << __func__
1177 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1178
1179 return -ENOSYS;
1180 }
1181
in_get_active_microphones(const struct audio_stream_in * stream,struct audio_microphone_characteristic_t * mic_array,size_t * mic_count)1182 static int in_get_active_microphones(
1183 const struct audio_stream_in* stream,
1184 struct audio_microphone_characteristic_t* mic_array, size_t* mic_count) {
1185 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1186 LOG(VERBOSE) << __func__
1187 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1188
1189 return -ENOSYS;
1190 }
1191
in_set_microphone_direction(const struct audio_stream_in * stream,audio_microphone_direction_t direction)1192 static int in_set_microphone_direction(const struct audio_stream_in* stream,
1193 audio_microphone_direction_t direction) {
1194 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1195 LOG(VERBOSE) << __func__
1196 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1197
1198 return -ENOSYS;
1199 }
1200
in_set_microphone_field_dimension(const struct audio_stream_in * stream,float zoom)1201 static int in_set_microphone_field_dimension(
1202 const struct audio_stream_in* stream, float zoom) {
1203 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1204 LOG(VERBOSE) << __func__
1205 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1206
1207 return -ENOSYS;
1208 }
1209
in_update_sink_metadata(struct audio_stream_in * stream,const struct sink_metadata * sink_metadata)1210 static void in_update_sink_metadata(struct audio_stream_in* stream,
1211 const struct sink_metadata* sink_metadata) {
1212 LOG(INFO) << __func__;
1213 if (sink_metadata == nullptr || sink_metadata->track_count == 0) {
1214 return;
1215 }
1216
1217 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1218 LOG(INFO) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1219 << ", " << sink_metadata->track_count << " track(s)";
1220
1221 if (!in->is_aidl) {
1222 LOG(WARNING) << __func__
1223 << " is only supported in AIDL but using HIDL now!";
1224 return;
1225 }
1226 static_cast<::android::bluetooth::audio::aidl::BluetoothAudioPortAidl*>(
1227 in->bluetooth_input_.get())
1228 ->UpdateSinkMetadata(sink_metadata);
1229 }
1230
adev_open_input_stream(struct audio_hw_device * dev,audio_io_handle_t handle,audio_devices_t devices,struct audio_config * config,struct audio_stream_in ** stream_in,audio_input_flags_t flags __unused,const char * address __unused,audio_source_t source __unused)1231 int adev_open_input_stream(struct audio_hw_device* dev,
1232 audio_io_handle_t handle, audio_devices_t devices,
1233 struct audio_config* config,
1234 struct audio_stream_in** stream_in,
1235 audio_input_flags_t flags __unused,
1236 const char* address __unused,
1237 audio_source_t source __unused) {
1238 *stream_in = nullptr;
1239 auto in = std::make_unique<BluetoothStreamIn>();
1240 if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession::
1241 IsAidlAvailable()) {
1242 in->bluetooth_input_ = std::make_unique<
1243 ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlIn>();
1244 in->is_aidl = true;
1245 } else {
1246 in->bluetooth_input_ = std::make_unique<
1247 ::android::bluetooth::audio::hidl::BluetoothAudioPortHidlIn>();
1248 in->is_aidl = false;
1249 }
1250 if (!in->bluetooth_input_->SetUp(devices)) {
1251 in->bluetooth_input_ = nullptr;
1252 LOG(ERROR) << __func__ << ": cannot init HAL";
1253 return -EINVAL;
1254 }
1255
1256 LOG(INFO) << __func__ << ": device=" << StringPrintf("%#x", devices);
1257
1258 in->stream_in_.common.get_sample_rate = in_get_sample_rate;
1259 in->stream_in_.common.set_sample_rate = in_set_sample_rate;
1260 in->stream_in_.common.get_buffer_size = in_get_buffer_size;
1261 in->stream_in_.common.get_channels = in_get_channels;
1262 in->stream_in_.common.get_format = in_get_format;
1263 in->stream_in_.common.set_format = in_set_format;
1264 in->stream_in_.common.standby = in_standby;
1265 in->stream_in_.common.dump = in_dump;
1266 in->stream_in_.common.set_parameters = in_set_parameters;
1267 in->stream_in_.common.get_parameters = in_get_parameters;
1268 in->stream_in_.common.add_audio_effect = in_add_audio_effect;
1269 in->stream_in_.common.remove_audio_effect = in_remove_audio_effect;
1270 in->stream_in_.set_gain = in_set_gain;
1271 in->stream_in_.read = in_read;
1272 in->stream_in_.get_input_frames_lost = in_get_input_frames_lost;
1273 in->stream_in_.get_capture_position = in_get_capture_position;
1274 in->stream_in_.start = in_start;
1275 in->stream_in_.stop = in_stop;
1276 in->stream_in_.create_mmap_buffer = in_create_mmap_buffer;
1277 in->stream_in_.get_mmap_position = in_get_mmap_position;
1278 in->stream_in_.get_active_microphones = in_get_active_microphones;
1279 in->stream_in_.set_microphone_direction = in_set_microphone_direction;
1280 in->stream_in_.set_microphone_field_dimension =
1281 in_set_microphone_field_dimension;
1282 in->stream_in_.update_sink_metadata = in_update_sink_metadata;
1283
1284 if (!in->bluetooth_input_->LoadAudioConfig(config)) {
1285 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1286 << " failed to get audio config";
1287 return -EINVAL;
1288 }
1289
1290 in->sample_rate_ = config->sample_rate;
1291 in->channel_mask_ = config->channel_mask;
1292 in->format_ = config->format;
1293 // frame is number of samples per channel
1294
1295 size_t preferred_data_interval_us = kBluetoothDefaultInputBufferMs * 1000;
1296 if (in->bluetooth_input_->GetPreferredDataIntervalUs(
1297 &preferred_data_interval_us) &&
1298 preferred_data_interval_us != 0) {
1299 in->preferred_data_interval_us = preferred_data_interval_us;
1300 } else {
1301 in->preferred_data_interval_us = kBluetoothDefaultInputBufferMs * 1000;
1302 }
1303
1304 in->frames_count_ =
1305 FrameCount(in->preferred_data_interval_us, in->sample_rate_);
1306 in->frames_presented_ = 0;
1307
1308 BluetoothStreamIn* in_ptr = in.release();
1309 *stream_in = &in_ptr->stream_in_;
1310 LOG(INFO) << __func__ << ": state=" << in_ptr->bluetooth_input_->GetState()
1311 << ", sample_rate=" << in_ptr->sample_rate_
1312 << ", channels=" << StringPrintf("%#x", in_ptr->channel_mask_)
1313 << ", format=" << in_ptr->format_ << ", preferred_data_interval_us="
1314 << in_ptr->preferred_data_interval_us
1315 << ", frames=" << in_ptr->frames_count_;
1316
1317 return 0;
1318 }
1319
adev_close_input_stream(struct audio_hw_device * dev,struct audio_stream_in * stream)1320 void adev_close_input_stream(struct audio_hw_device* dev,
1321 struct audio_stream_in* stream) {
1322 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
1323
1324 if (in->bluetooth_input_->GetState() != BluetoothStreamState::DISABLED) {
1325 in->bluetooth_input_->Stop();
1326 }
1327
1328 in->bluetooth_input_->TearDown();
1329 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1330 << ", stopped";
1331
1332 delete in;
1333 }
1334