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("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("closing") != params.end()) {
370 if (params["closing"] == "true") {
371 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
372 << " stream param closing, disallow any writes?";
373 if (out->bluetooth_output_->GetState() !=
374 BluetoothStreamState::DISABLED) {
375 out->frames_rendered_ = 0;
376 out->frames_presented_ = 0;
377 out->bluetooth_output_->Stop();
378 }
379 }
380 }
381
382 if (params.find("exiting") != params.end()) {
383 if (params["exiting"] == "1") {
384 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
385 << " stream param exiting";
386 if (out->bluetooth_output_->GetState() !=
387 BluetoothStreamState::DISABLED) {
388 out->frames_rendered_ = 0;
389 out->frames_presented_ = 0;
390 out->bluetooth_output_->Stop();
391 }
392 }
393 }
394
395 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
396 << ", kvpairs=[" << kvpairs << "], retval=" << retval;
397 return retval;
398 }
399
out_get_parameters(const struct audio_stream * stream,const char * keys)400 static char* out_get_parameters(const struct audio_stream* stream,
401 const char* keys) {
402 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
403 std::unique_lock<std::mutex> lock(out->mutex_);
404
405 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
406 << ", keys=[" << keys << "]";
407
408 std::unordered_map<std::string, std::string> params = ParseAudioParams(keys);
409 if (params.empty()) return strdup("");
410
411 audio_config_t audio_cfg;
412 if (out->bluetooth_output_->LoadAudioConfig(&audio_cfg)) {
413 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
414 << " audio_cfg=" << audio_cfg;
415 } else {
416 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_->GetState()
417 << " failed to get audio config";
418 }
419
420 std::unordered_map<std::string, std::string> return_params;
421 if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end()) {
422 std::string param;
423 if (audio_cfg.sample_rate == 16000) {
424 param = "16000";
425 }
426 if (audio_cfg.sample_rate == 24000) {
427 param = "24000";
428 }
429 if (audio_cfg.sample_rate == 44100) {
430 param = "44100";
431 }
432 if (audio_cfg.sample_rate == 48000) {
433 param = "48000";
434 }
435 if (audio_cfg.sample_rate == 88200) {
436 param = "88200";
437 }
438 if (audio_cfg.sample_rate == 96000) {
439 param = "96000";
440 }
441 if (audio_cfg.sample_rate == 176400) {
442 param = "176400";
443 }
444 if (audio_cfg.sample_rate == 192000) {
445 param = "192000";
446 }
447 return_params[AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES] = param;
448 }
449
450 if (params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end()) {
451 std::string param;
452 if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_MONO) {
453 param = "AUDIO_CHANNEL_OUT_MONO";
454 }
455 if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_STEREO) {
456 param = "AUDIO_CHANNEL_OUT_STEREO";
457 }
458 return_params[AUDIO_PARAMETER_STREAM_SUP_CHANNELS] = param;
459 }
460
461 if (params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
462 std::string param;
463 if (audio_cfg.format == AUDIO_FORMAT_PCM_16_BIT) {
464 param = "AUDIO_FORMAT_PCM_16_BIT";
465 }
466 if (audio_cfg.format == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
467 param = "AUDIO_FORMAT_PCM_24_BIT_PACKED";
468 }
469 if (audio_cfg.format == AUDIO_FORMAT_PCM_8_24_BIT) {
470 param = "AUDIO_FORMAT_PCM_8_24_BIT";
471 }
472 if (audio_cfg.format == AUDIO_FORMAT_PCM_32_BIT) {
473 param = "AUDIO_FORMAT_PCM_32_BIT";
474 }
475 return_params[AUDIO_PARAMETER_STREAM_SUP_FORMATS] = param;
476 }
477
478 std::string result;
479 for (const auto& ptr : return_params) {
480 result += ptr.first + "=" + ptr.second + ";";
481 }
482
483 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
484 << ", result=[" << result << "]";
485 return strdup(result.c_str());
486 }
487
out_get_latency_ms(const struct audio_stream_out * stream)488 static uint32_t out_get_latency_ms(const struct audio_stream_out* stream) {
489 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
490 uint32_t latency_ms = 0;
491 out_calculate_feeding_delay_ms(out, &latency_ms);
492 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
493 << ", latency=" << latency_ms << "ms";
494 return latency_ms;
495 }
496
out_set_volume(struct audio_stream_out * stream,float left,float right)497 static int out_set_volume(struct audio_stream_out* stream, float left,
498 float right) {
499 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
500 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
501 << ", Left=" << left << ", Right=" << right;
502 return -1;
503 }
504
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)505 static ssize_t out_write(struct audio_stream_out* stream, const void* buffer,
506 size_t bytes) {
507 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
508 std::unique_lock<std::mutex> lock(out->mutex_);
509 size_t totalWritten = 0;
510
511 if (out->bluetooth_output_->GetState() != BluetoothStreamState::STARTED) {
512 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_->GetState()
513 << " first time bytes=" << bytes;
514 lock.unlock();
515 if (stream->resume(stream)) {
516 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_->GetState()
517 << " failed to resume";
518 if (out->bluetooth_output_->GetState() ==
519 BluetoothStreamState::DISABLED) {
520 // drop data for cases of A2dpSuspended=true / closing=true
521 totalWritten = bytes;
522 }
523 usleep(out->preferred_data_interval_us);
524 return totalWritten;
525 }
526 lock.lock();
527 }
528 lock.unlock();
529 totalWritten = out->bluetooth_output_->WriteData(buffer, bytes);
530 lock.lock();
531
532 struct timespec ts = {.tv_sec = 0, .tv_nsec = 0};
533 clock_gettime(CLOCK_MONOTONIC, &ts);
534 if (totalWritten) {
535 const size_t frames = bytes / audio_stream_out_frame_size(stream);
536 out->frames_rendered_ += frames;
537 out->frames_presented_ += frames;
538 out->last_write_time_us_ = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
539 } else {
540 const int64_t now = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
541 const int64_t elapsed_time_since_last_write =
542 now - out->last_write_time_us_;
543 // frames_count = written_data / frame_size
544 // play_time (ms) = frames_count / (sample_rate (Sec.) / 1000000)
545 // sleep_time (ms) = play_time - elapsed_time
546 int64_t sleep_time = bytes * 1000000LL /
547 audio_stream_out_frame_size(stream) /
548 out_get_sample_rate(&stream->common) -
549 elapsed_time_since_last_write;
550 if (sleep_time > 0) {
551 LOG(VERBOSE) << __func__ << ": sleep " << (sleep_time / 1000)
552 << " ms when writting FMQ datapath";
553 lock.unlock();
554 usleep(sleep_time);
555 lock.lock();
556 } else {
557 // we don't sleep when we exit standby (this is typical for a real alsa
558 // buffer).
559 sleep_time = 0;
560 }
561 out->last_write_time_us_ = now + sleep_time;
562 }
563 return totalWritten;
564 }
565
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)566 static int out_get_render_position(const struct audio_stream_out* stream,
567 uint32_t* dsp_frames) {
568 if (dsp_frames == nullptr) return -EINVAL;
569
570 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
571 // frames = (latency (ms) / 1000) * samples_per_second (sample_rate)
572 const uint64_t latency_frames =
573 (uint64_t)out_get_latency_ms(stream) * out->sample_rate_ / 1000;
574 if (out->frames_rendered_ >= latency_frames) {
575 *dsp_frames = (uint32_t)(out->frames_rendered_ - latency_frames);
576 } else {
577 *dsp_frames = 0;
578 }
579
580 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
581 << ", dsp_frames=" << *dsp_frames;
582 return 0;
583 }
584
out_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)585 static int out_add_audio_effect(const struct audio_stream* stream,
586 effect_handle_t effect) {
587 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
588 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
589 << ", effect=" << effect;
590 return 0;
591 }
592
out_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)593 static int out_remove_audio_effect(const struct audio_stream* stream,
594 effect_handle_t effect) {
595 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
596 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
597 << ", effect=" << effect;
598 return 0;
599 }
600
out_get_next_write_timestamp(const struct audio_stream_out * stream,int64_t * timestamp)601 static int out_get_next_write_timestamp(const struct audio_stream_out* stream,
602 int64_t* timestamp) {
603 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
604 *timestamp = 0;
605 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
606 << ", timestamp=" << *timestamp;
607 return -EINVAL;
608 }
609
out_pause(struct audio_stream_out * stream)610 static int out_pause(struct audio_stream_out* stream) {
611 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
612 std::unique_lock<std::mutex> lock(out->mutex_);
613 int retval = 0;
614 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
615 << ", pausing (suspend)";
616 if (out->bluetooth_output_->GetState() == BluetoothStreamState::STARTED) {
617 out->frames_rendered_ = 0;
618 retval = (out->bluetooth_output_->Suspend() ? 0 : -EIO);
619 } else if (out->bluetooth_output_->GetState() ==
620 BluetoothStreamState::STARTING ||
621 out->bluetooth_output_->GetState() ==
622 BluetoothStreamState::SUSPENDING) {
623 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
624 << " NOT ready to pause?!";
625 retval = -EBUSY;
626 } else {
627 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_->GetState()
628 << " paused already";
629 }
630 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
631 << ", pausing (suspend) retval=" << retval;
632
633 return retval;
634 }
635
out_resume(struct audio_stream_out * stream)636 static int out_resume(struct audio_stream_out* stream) {
637 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
638 std::unique_lock<std::mutex> lock(out->mutex_);
639 int retval = 0;
640
641 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
642 << ", resuming (start)";
643 if (out->bluetooth_output_->GetState() == BluetoothStreamState::STANDBY) {
644 retval = (out->bluetooth_output_->Start() ? 0 : -EIO);
645 } else if (out->bluetooth_output_->GetState() ==
646 BluetoothStreamState::STARTING ||
647 out->bluetooth_output_->GetState() ==
648 BluetoothStreamState::SUSPENDING) {
649 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
650 << " NOT ready to resume?!";
651 retval = -EBUSY;
652 } else if (out->bluetooth_output_->GetState() ==
653 BluetoothStreamState::DISABLED) {
654 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_->GetState()
655 << " NOT allow to resume?!";
656 retval = -EINVAL;
657 } else {
658 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_->GetState()
659 << " resumed already";
660 }
661 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
662 << ", resuming (start) retval=" << retval;
663
664 return retval;
665 }
666
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)667 static int out_get_presentation_position(const struct audio_stream_out* stream,
668 uint64_t* frames,
669 struct timespec* timestamp) {
670 if (frames == nullptr || timestamp == nullptr) {
671 return -EINVAL;
672 }
673
674 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
675 out_calculate_feeding_delay_ms(out, nullptr, frames, timestamp);
676 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
677 << ", frames=" << *frames << ", timestamp=" << timestamp->tv_sec
678 << "." << StringPrintf("%09ld", timestamp->tv_nsec) << "s";
679 return 0;
680 }
681
out_update_source_metadata(struct audio_stream_out * stream,const struct source_metadata * source_metadata)682 static void out_update_source_metadata(
683 struct audio_stream_out* stream,
684 const struct source_metadata* source_metadata) {
685 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
686 std::unique_lock<std::mutex> lock(out->mutex_);
687 if (source_metadata == nullptr || source_metadata->track_count == 0) {
688 return;
689 }
690 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
691 << ", " << source_metadata->track_count << " track(s)";
692 out->bluetooth_output_->UpdateSourceMetadata(source_metadata);
693 }
694
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)695 int adev_open_output_stream(struct audio_hw_device* dev,
696 audio_io_handle_t handle, audio_devices_t devices,
697 audio_output_flags_t flags,
698 struct audio_config* config,
699 struct audio_stream_out** stream_out,
700 const char* address __unused) {
701 *stream_out = nullptr;
702 auto out = std::make_unique<BluetoothStreamOut>();
703 if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession::
704 IsAidlAvailable()) {
705 out->bluetooth_output_ = std::make_unique<
706 ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlOut>();
707 out->is_aidl = true;
708 } else {
709 out->bluetooth_output_ = std::make_unique<
710 ::android::bluetooth::audio::hidl::BluetoothAudioPortHidlOut>();
711 out->is_aidl = false;
712 }
713 if (!out->bluetooth_output_->SetUp(devices)) {
714 out->bluetooth_output_ = nullptr;
715 LOG(ERROR) << __func__ << ": cannot init HAL";
716 return -EINVAL;
717 }
718 LOG(VERBOSE) << __func__ << ": device=" << StringPrintf("%#x", devices);
719
720 out->stream_out_.common.get_sample_rate = out_get_sample_rate;
721 out->stream_out_.common.set_sample_rate = out_set_sample_rate;
722 out->stream_out_.common.get_buffer_size = out_get_buffer_size;
723 out->stream_out_.common.get_channels = out_get_channels;
724 out->stream_out_.common.get_format = out_get_format;
725 out->stream_out_.common.set_format = out_set_format;
726 out->stream_out_.common.standby = out_standby;
727 out->stream_out_.common.dump = out_dump;
728 out->stream_out_.common.set_parameters = out_set_parameters;
729 out->stream_out_.common.get_parameters = out_get_parameters;
730 out->stream_out_.common.add_audio_effect = out_add_audio_effect;
731 out->stream_out_.common.remove_audio_effect = out_remove_audio_effect;
732 out->stream_out_.get_latency = out_get_latency_ms;
733 out->stream_out_.set_volume = out_set_volume;
734 out->stream_out_.write = out_write;
735 out->stream_out_.get_render_position = out_get_render_position;
736 out->stream_out_.get_next_write_timestamp = out_get_next_write_timestamp;
737 out->stream_out_.pause = out_pause;
738 out->stream_out_.resume = out_resume;
739 out->stream_out_.get_presentation_position = out_get_presentation_position;
740 out->stream_out_.update_source_metadata = out_update_source_metadata;
741
742 if (!out->bluetooth_output_->LoadAudioConfig(config)) {
743 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_->GetState()
744 << " failed to get audio config";
745 }
746 // WAR to support Mono / 16 bits per sample as the Bluetooth stack required
747 if (config->channel_mask == AUDIO_CHANNEL_OUT_MONO &&
748 config->format == AUDIO_FORMAT_PCM_16_BIT) {
749 LOG(INFO) << __func__
750 << ": force channels=" << StringPrintf("%#x", out->channel_mask_)
751 << " to be AUDIO_CHANNEL_OUT_STEREO";
752 out->bluetooth_output_->ForcePcmStereoToMono(true);
753 config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
754 }
755 out->sample_rate_ = config->sample_rate;
756 out->channel_mask_ = config->channel_mask;
757 out->format_ = config->format;
758 // frame is number of samples per channel
759
760 size_t preferred_data_interval_us = kBluetoothDefaultOutputBufferMs * 1000;
761 if (out->bluetooth_output_->GetPreferredDataIntervalUs(
762 &preferred_data_interval_us) &&
763 preferred_data_interval_us != 0) {
764 out->preferred_data_interval_us = preferred_data_interval_us;
765 } else {
766 out->preferred_data_interval_us = kBluetoothDefaultOutputBufferMs * 1000;
767 }
768
769 // Ensure minimum buffer duration for spatialized output
770 if ((flags == (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER) ||
771 flags == AUDIO_OUTPUT_FLAG_SPATIALIZER) &&
772 out->preferred_data_interval_us <
773 kBluetoothSpatializerOutputBufferMs * 1000) {
774 out->preferred_data_interval_us =
775 kBluetoothSpatializerOutputBufferMs * 1000;
776 LOG(INFO) << __func__
777 << ": adjusting to minimum buffer duration for spatializer: "
778 << StringPrintf("%zu", out->preferred_data_interval_us);
779 }
780
781 out->frames_count_ =
782 FrameCount(out->preferred_data_interval_us, out->sample_rate_);
783
784 out->frames_rendered_ = 0;
785 out->frames_presented_ = 0;
786
787 BluetoothStreamOut* out_ptr = out.release();
788 {
789 auto* bluetooth_device = reinterpret_cast<BluetoothAudioDevice*>(dev);
790 std::lock_guard<std::mutex> guard(bluetooth_device->mutex_);
791 bluetooth_device->opened_stream_outs_.push_back(out_ptr);
792 }
793
794 *stream_out = &out_ptr->stream_out_;
795 LOG(INFO) << __func__ << ": state=" << out_ptr->bluetooth_output_->GetState()
796 << ", sample_rate=" << out_ptr->sample_rate_
797 << ", channels=" << StringPrintf("%#x", out_ptr->channel_mask_)
798 << ", format=" << out_ptr->format_
799 << ", preferred_data_interval_us="
800 << out_ptr->preferred_data_interval_us
801 << ", frames=" << out_ptr->frames_count_;
802 return 0;
803 }
804
adev_close_output_stream(struct audio_hw_device * dev,struct audio_stream_out * stream)805 void adev_close_output_stream(struct audio_hw_device* dev,
806 struct audio_stream_out* stream) {
807 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
808 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
809 << ", stopping";
810 {
811 auto* bluetooth_device = reinterpret_cast<BluetoothAudioDevice*>(dev);
812 std::lock_guard<std::mutex> guard(bluetooth_device->mutex_);
813 bluetooth_device->opened_stream_outs_.remove(out);
814 }
815 if (out->bluetooth_output_->GetState() != BluetoothStreamState::DISABLED) {
816 out->frames_rendered_ = 0;
817 out->frames_presented_ = 0;
818 out->bluetooth_output_->Stop();
819 }
820 out->bluetooth_output_->TearDown();
821 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_->GetState()
822 << ", stopped";
823 delete out;
824 }
825
adev_get_input_buffer_size(const struct audio_hw_device * dev,const struct audio_config * config)826 size_t adev_get_input_buffer_size(const struct audio_hw_device* dev,
827 const struct audio_config* config) {
828 /* TODO: Adjust this value */
829 LOG(VERBOSE) << __func__;
830 return 320;
831 }
832
in_get_sample_rate(const struct audio_stream * stream)833 static uint32_t in_get_sample_rate(const struct audio_stream* stream) {
834 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
835
836 return in->sample_rate_;
837 }
838
in_set_sample_rate(struct audio_stream * stream,uint32_t rate)839 static int in_set_sample_rate(struct audio_stream* stream, uint32_t rate) {
840 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
841
842 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
843 << ", sample_rate=" << in->sample_rate_;
844 return (rate == in->sample_rate_ ? 0 : -ENOSYS);
845 }
846
in_get_buffer_size(const struct audio_stream * stream)847 static size_t in_get_buffer_size(const struct audio_stream* stream) {
848 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
849 size_t buffer_size =
850 in->frames_count_ * audio_stream_in_frame_size(&in->stream_in_);
851 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
852 << ", buffer_size=" << buffer_size;
853 return buffer_size;
854 }
855
in_get_channels(const struct audio_stream * stream)856 static audio_channel_mask_t in_get_channels(const struct audio_stream* stream) {
857 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
858 audio_config_t audio_cfg;
859 if (in->bluetooth_input_->LoadAudioConfig(&audio_cfg)) {
860 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
861 << " audio_cfg=" << audio_cfg;
862 return audio_cfg.channel_mask;
863 } else {
864 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
865 << ", channels=" << StringPrintf("%#x", in->channel_mask_)
866 << " failure";
867 return in->channel_mask_;
868 }
869 }
870
in_get_format(const struct audio_stream * stream)871 static audio_format_t in_get_format(const struct audio_stream* stream) {
872 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
873 audio_config_t audio_cfg;
874 if (in->bluetooth_input_->LoadAudioConfig(&audio_cfg)) {
875 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
876 << " audio_cfg=" << audio_cfg;
877 return audio_cfg.format;
878 } else {
879 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
880 << ", format=" << in->format_ << " failure";
881 return in->format_;
882 }
883 }
884
in_set_format(struct audio_stream * stream,audio_format_t format)885 static int in_set_format(struct audio_stream* stream, audio_format_t format) {
886 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
887 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
888 << ", format=" << in->format_;
889 return (format == in->format_ ? 0 : -ENOSYS);
890 }
891
in_state_transition_timeout(BluetoothStreamIn * in,std::unique_lock<std::mutex> & lock,const BluetoothStreamState & state,uint16_t timeout_ms)892 static bool in_state_transition_timeout(BluetoothStreamIn* in,
893 std::unique_lock<std::mutex>& lock,
894 const BluetoothStreamState& state,
895 uint16_t timeout_ms) {
896 /* Don't loose suspend request, AF will not retry */
897 while (in->bluetooth_input_->GetState() == state) {
898 lock.unlock();
899 usleep(1000);
900 lock.lock();
901
902 /* Don't block AF forever */
903 if (--timeout_ms <= 0) {
904 LOG(WARNING) << __func__ << ", can't suspend - stucked in: "
905 << static_cast<int>(state) << " state";
906 return false;
907 }
908 }
909
910 return true;
911 }
912
in_standby(struct audio_stream * stream)913 static int in_standby(struct audio_stream* stream) {
914 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
915 std::unique_lock<std::mutex> lock(in->mutex_);
916 int retval = 0;
917
918 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
919 << " being standby (suspend)";
920
921 /* Give some time to start up */
922 if (!in_state_transition_timeout(in, lock, BluetoothStreamState::STARTING,
923 kBluetoothDefaultInputStateTimeoutMs)) {
924 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
925 << " NOT ready to by standby";
926 return retval;
927 }
928
929 if (in->bluetooth_input_->GetState() == BluetoothStreamState::STARTED) {
930 retval = (in->bluetooth_input_->Suspend() ? 0 : -EIO);
931 } else if (in->bluetooth_input_->GetState() !=
932 BluetoothStreamState::SUSPENDING) {
933 LOG(DEBUG) << __func__ << ": state=" << in->bluetooth_input_->GetState()
934 << " standby already";
935 return retval;
936 }
937
938 /* Give some time to suspend */
939 if (!in_state_transition_timeout(in, lock, BluetoothStreamState::SUSPENDING,
940 kBluetoothDefaultInputStateTimeoutMs)) {
941 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
942 << " NOT ready to by standby";
943 return 0;
944 }
945
946 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
947 << " standby (suspend) retval=" << retval;
948
949 return retval;
950 }
951
in_dump(const struct audio_stream * stream,int fd)952 static int in_dump(const struct audio_stream* stream, int fd) {
953 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
954 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState();
955
956 return 0;
957 }
958
in_set_parameters(struct audio_stream * stream,const char * kvpairs)959 static int in_set_parameters(struct audio_stream* stream, const char* kvpairs) {
960 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
961 std::unique_lock<std::mutex> lock(in->mutex_);
962 int retval = 0;
963
964 LOG(INFO) << __func__
965 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState()
966 << ", kvpairs=[" << kvpairs << "]";
967
968 std::unordered_map<std::string, std::string> params =
969 ParseAudioParams(kvpairs);
970
971 if (params.empty()) return retval;
972
973 LOG(INFO) << __func__ << ": ParamsMap=[" << GetAudioParamString(params)
974 << "]";
975
976 return retval;
977 }
978
in_get_parameters(const struct audio_stream * stream,const char * keys)979 static char* in_get_parameters(const struct audio_stream* stream,
980 const char* keys) {
981 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
982 std::unique_lock<std::mutex> lock(in->mutex_);
983
984 LOG(VERBOSE) << __func__
985 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState()
986 << ", keys=[" << keys << "]";
987
988 std::unordered_map<std::string, std::string> params = ParseAudioParams(keys);
989 if (params.empty()) return strdup("");
990
991 audio_config_t audio_cfg;
992 if (in->bluetooth_input_->LoadAudioConfig(&audio_cfg)) {
993 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
994 << " audio_cfg=" << audio_cfg;
995 } else {
996 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
997 << " failed to get audio config";
998 }
999
1000 std::unordered_map<std::string, std::string> return_params;
1001
1002 /* TODO: Implement parameter getter */
1003
1004 std::string result;
1005 for (const auto& ptr : return_params) {
1006 result += ptr.first + "=" + ptr.second + ";";
1007 }
1008
1009 return strdup(result.c_str());
1010 }
1011
in_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1012 static int in_add_audio_effect(const struct audio_stream* stream,
1013 effect_handle_t effect) {
1014 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1015 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1016 << ", effect=" << effect;
1017 return 0;
1018 }
1019
in_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)1020 static int in_remove_audio_effect(const struct audio_stream* stream,
1021 effect_handle_t effect) {
1022 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1023 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1024 << ", effect=" << effect;
1025 return 0;
1026 }
1027
in_set_gain(struct audio_stream_in * stream,float gain)1028 static int in_set_gain(struct audio_stream_in* stream, float gain) {
1029 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1030 LOG(VERBOSE) << __func__
1031 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1032
1033 return 0;
1034 }
1035
in_read(struct audio_stream_in * stream,void * buffer,size_t bytes)1036 static ssize_t in_read(struct audio_stream_in* stream, void* buffer,
1037 size_t bytes) {
1038 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
1039 std::unique_lock<std::mutex> lock(in->mutex_);
1040 size_t totalRead = 0;
1041
1042 /* Give some time to start up */
1043 if (!in_state_transition_timeout(in, lock, BluetoothStreamState::STARTING,
1044 kBluetoothDefaultInputStateTimeoutMs))
1045 return -EBUSY;
1046
1047 if (in->bluetooth_input_->GetState() != BluetoothStreamState::STARTED) {
1048 LOG(INFO) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1049 << " first time bytes=" << bytes;
1050
1051 int retval = 0;
1052 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1053 << ", starting";
1054 if (in->bluetooth_input_->GetState() == BluetoothStreamState::STANDBY) {
1055 retval = (in->bluetooth_input_->Start() ? 0 : -EIO);
1056 } else if (in->bluetooth_input_->GetState() ==
1057 BluetoothStreamState::SUSPENDING) {
1058 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1059 << " NOT ready to start?!";
1060 retval = -EBUSY;
1061 } else if (in->bluetooth_input_->GetState() ==
1062 BluetoothStreamState::DISABLED) {
1063 LOG(WARNING) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1064 << " NOT allow to start?!";
1065 retval = -EINVAL;
1066 } else {
1067 LOG(DEBUG) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1068 << " started already";
1069 }
1070 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1071 << ", starting (start) retval=" << retval;
1072
1073 if (retval) {
1074 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1075 << " failed to start";
1076 return retval;
1077 }
1078 }
1079
1080 lock.unlock();
1081 totalRead = in->bluetooth_input_->ReadData(buffer, bytes);
1082 lock.lock();
1083
1084 struct timespec ts = {.tv_sec = 0, .tv_nsec = 0};
1085 clock_gettime(CLOCK_MONOTONIC, &ts);
1086 in->last_read_time_us_ = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
1087
1088 const size_t frames = totalRead / audio_stream_in_frame_size(stream);
1089 in->frames_presented_ += frames;
1090
1091 return totalRead;
1092 }
1093
in_get_input_frames_lost(struct audio_stream_in * stream)1094 static uint32_t in_get_input_frames_lost(struct audio_stream_in* stream) {
1095 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1096 LOG(VERBOSE) << __func__
1097 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1098
1099 return 0;
1100 }
1101
in_get_capture_position(const struct audio_stream_in * stream,int64_t * frames,int64_t * time)1102 static int in_get_capture_position(const struct audio_stream_in* stream,
1103 int64_t* frames, int64_t* time) {
1104 if (stream == NULL || frames == NULL || time == NULL) {
1105 return -EINVAL;
1106 }
1107 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1108
1109 if (in->bluetooth_input_->GetState() == BluetoothStreamState::STANDBY) {
1110 LOG(WARNING) << __func__ << ": state= " << in->bluetooth_input_->GetState();
1111 return -ENOSYS;
1112 }
1113
1114 in_calculate_starving_delay_ms(in, frames, time);
1115
1116 return 0;
1117 }
1118
in_start(const struct audio_stream_in * stream)1119 static int in_start(const struct audio_stream_in* stream) {
1120 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1121 LOG(VERBOSE) << __func__
1122 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1123
1124 return 0;
1125 }
1126
in_stop(const struct audio_stream_in * stream)1127 static int in_stop(const struct audio_stream_in* stream) {
1128 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1129 LOG(VERBOSE) << __func__
1130 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1131
1132 return 0;
1133 }
1134
in_create_mmap_buffer(const struct audio_stream_in * stream,int32_t min_size_frames,struct audio_mmap_buffer_info * info)1135 static int in_create_mmap_buffer(const struct audio_stream_in* stream,
1136 int32_t min_size_frames,
1137 struct audio_mmap_buffer_info* info) {
1138 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1139 LOG(VERBOSE) << __func__
1140 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1141
1142 return -ENOSYS;
1143 }
1144
in_get_mmap_position(const struct audio_stream_in * stream,struct audio_mmap_position * position)1145 static int in_get_mmap_position(const struct audio_stream_in* stream,
1146 struct audio_mmap_position* position) {
1147 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1148 LOG(VERBOSE) << __func__
1149 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1150
1151 return -ENOSYS;
1152 }
1153
in_get_active_microphones(const struct audio_stream_in * stream,struct audio_microphone_characteristic_t * mic_array,size_t * mic_count)1154 static int in_get_active_microphones(
1155 const struct audio_stream_in* stream,
1156 struct audio_microphone_characteristic_t* mic_array, size_t* mic_count) {
1157 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1158 LOG(VERBOSE) << __func__
1159 << ": NOT HANDLED! state=" << in->bluetooth_input_->GetState();
1160
1161 return -ENOSYS;
1162 }
1163
in_set_microphone_direction(const struct audio_stream_in * stream,audio_microphone_direction_t direction)1164 static int in_set_microphone_direction(const struct audio_stream_in* stream,
1165 audio_microphone_direction_t direction) {
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_set_microphone_field_dimension(const struct audio_stream_in * stream,float zoom)1173 static int in_set_microphone_field_dimension(
1174 const struct audio_stream_in* stream, float zoom) {
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_update_sink_metadata(struct audio_stream_in * stream,const struct sink_metadata * sink_metadata)1182 static void in_update_sink_metadata(struct audio_stream_in* stream,
1183 const struct sink_metadata* sink_metadata) {
1184 LOG(INFO) << __func__;
1185 if (sink_metadata == nullptr || sink_metadata->track_count == 0) {
1186 return;
1187 }
1188
1189 const auto* in = reinterpret_cast<const BluetoothStreamIn*>(stream);
1190 LOG(INFO) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1191 << ", " << sink_metadata->track_count << " track(s)";
1192
1193 if (!in->is_aidl) {
1194 LOG(WARNING) << __func__
1195 << " is only supported in AIDL but using HIDL now!";
1196 return;
1197 }
1198 static_cast<::android::bluetooth::audio::aidl::BluetoothAudioPortAidl*>(
1199 in->bluetooth_input_.get())
1200 ->UpdateSinkMetadata(sink_metadata);
1201 }
1202
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)1203 int adev_open_input_stream(struct audio_hw_device* dev,
1204 audio_io_handle_t handle, audio_devices_t devices,
1205 struct audio_config* config,
1206 struct audio_stream_in** stream_in,
1207 audio_input_flags_t flags __unused,
1208 const char* address __unused,
1209 audio_source_t source __unused) {
1210 *stream_in = nullptr;
1211 auto in = std::make_unique<BluetoothStreamIn>();
1212 if (::aidl::android::hardware::bluetooth::audio::BluetoothAudioSession::
1213 IsAidlAvailable()) {
1214 in->bluetooth_input_ = std::make_unique<
1215 ::android::bluetooth::audio::aidl::BluetoothAudioPortAidlIn>();
1216 in->is_aidl = true;
1217 } else {
1218 in->bluetooth_input_ = std::make_unique<
1219 ::android::bluetooth::audio::hidl::BluetoothAudioPortHidlIn>();
1220 in->is_aidl = false;
1221 }
1222 if (!in->bluetooth_input_->SetUp(devices)) {
1223 in->bluetooth_input_ = nullptr;
1224 LOG(ERROR) << __func__ << ": cannot init HAL";
1225 return -EINVAL;
1226 }
1227
1228 LOG(INFO) << __func__ << ": device=" << StringPrintf("%#x", devices);
1229
1230 in->stream_in_.common.get_sample_rate = in_get_sample_rate;
1231 in->stream_in_.common.set_sample_rate = in_set_sample_rate;
1232 in->stream_in_.common.get_buffer_size = in_get_buffer_size;
1233 in->stream_in_.common.get_channels = in_get_channels;
1234 in->stream_in_.common.get_format = in_get_format;
1235 in->stream_in_.common.set_format = in_set_format;
1236 in->stream_in_.common.standby = in_standby;
1237 in->stream_in_.common.dump = in_dump;
1238 in->stream_in_.common.set_parameters = in_set_parameters;
1239 in->stream_in_.common.get_parameters = in_get_parameters;
1240 in->stream_in_.common.add_audio_effect = in_add_audio_effect;
1241 in->stream_in_.common.remove_audio_effect = in_remove_audio_effect;
1242 in->stream_in_.set_gain = in_set_gain;
1243 in->stream_in_.read = in_read;
1244 in->stream_in_.get_input_frames_lost = in_get_input_frames_lost;
1245 in->stream_in_.get_capture_position = in_get_capture_position;
1246 in->stream_in_.start = in_start;
1247 in->stream_in_.stop = in_stop;
1248 in->stream_in_.create_mmap_buffer = in_create_mmap_buffer;
1249 in->stream_in_.get_mmap_position = in_get_mmap_position;
1250 in->stream_in_.get_active_microphones = in_get_active_microphones;
1251 in->stream_in_.set_microphone_direction = in_set_microphone_direction;
1252 in->stream_in_.set_microphone_field_dimension =
1253 in_set_microphone_field_dimension;
1254 in->stream_in_.update_sink_metadata = in_update_sink_metadata;
1255
1256 if (!in->bluetooth_input_->LoadAudioConfig(config)) {
1257 LOG(ERROR) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1258 << " failed to get audio config";
1259 return -EINVAL;
1260 }
1261
1262 in->sample_rate_ = config->sample_rate;
1263 in->channel_mask_ = config->channel_mask;
1264 in->format_ = config->format;
1265 // frame is number of samples per channel
1266
1267 size_t preferred_data_interval_us = kBluetoothDefaultInputBufferMs * 1000;
1268 if (in->bluetooth_input_->GetPreferredDataIntervalUs(
1269 &preferred_data_interval_us) &&
1270 preferred_data_interval_us != 0) {
1271 in->preferred_data_interval_us = preferred_data_interval_us;
1272 } else {
1273 in->preferred_data_interval_us = kBluetoothDefaultInputBufferMs * 1000;
1274 }
1275
1276 in->frames_count_ =
1277 FrameCount(in->preferred_data_interval_us, in->sample_rate_);
1278 in->frames_presented_ = 0;
1279
1280 BluetoothStreamIn* in_ptr = in.release();
1281 *stream_in = &in_ptr->stream_in_;
1282 LOG(INFO) << __func__ << ": state=" << in_ptr->bluetooth_input_->GetState()
1283 << ", sample_rate=" << in_ptr->sample_rate_
1284 << ", channels=" << StringPrintf("%#x", in_ptr->channel_mask_)
1285 << ", format=" << in_ptr->format_ << ", preferred_data_interval_us="
1286 << in_ptr->preferred_data_interval_us
1287 << ", frames=" << in_ptr->frames_count_;
1288
1289 return 0;
1290 }
1291
adev_close_input_stream(struct audio_hw_device * dev,struct audio_stream_in * stream)1292 void adev_close_input_stream(struct audio_hw_device* dev,
1293 struct audio_stream_in* stream) {
1294 auto* in = reinterpret_cast<BluetoothStreamIn*>(stream);
1295
1296 if (in->bluetooth_input_->GetState() != BluetoothStreamState::DISABLED) {
1297 in->bluetooth_input_->Stop();
1298 }
1299
1300 in->bluetooth_input_->TearDown();
1301 LOG(VERBOSE) << __func__ << ": state=" << in->bluetooth_input_->GetState()
1302 << ", stopped";
1303
1304 delete in;
1305 }
1306