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 #define LOG_TAG "BTAudioHalStream"
18
19 #include <android-base/logging.h>
20 #include <android-base/stringprintf.h>
21 #include <cutils/properties.h>
22 #include <errno.h>
23 #include <inttypes.h>
24 #include <log/log.h>
25 #include <string.h>
26 #include <time.h>
27 #include <unistd.h>
28
29 #include "stream_apis.h"
30 #include "utils.h"
31
32 using ::android::base::StringPrintf;
33 using ::android::bluetooth::audio::BluetoothAudioPortOut;
34 using ::android::bluetooth::audio::utils::GetAudioParamString;
35 using ::android::bluetooth::audio::utils::ParseAudioParams;
36
37 namespace {
38
39 constexpr unsigned int kMinimumDelayMs = 100;
40 constexpr unsigned int kMaximumDelayMs = 1000;
41 constexpr int kExtraAudioSyncMs = 200;
42
operator <<(std::ostream & os,const audio_config & config)43 std::ostream& operator<<(std::ostream& os, const audio_config& config) {
44 return os << "audio_config[sample_rate=" << config.sample_rate
45 << ", channels=" << StringPrintf("%#x", config.channel_mask) << ", format=" << config.format << "]";
46 }
47
48 } // namespace
49
operator <<(std::ostream & os,const BluetoothStreamState & state)50 std::ostream& operator<<(std::ostream& os, const BluetoothStreamState& state) {
51 switch (state) {
52 case BluetoothStreamState::DISABLED:
53 return os << "DISABLED";
54 case BluetoothStreamState::STANDBY:
55 return os << "STANDBY";
56 case BluetoothStreamState::STARTING:
57 return os << "STARTING";
58 case BluetoothStreamState::STARTED:
59 return os << "STARTED";
60 case BluetoothStreamState::SUSPENDING:
61 return os << "SUSPENDING";
62 case BluetoothStreamState::UNKNOWN:
63 return os << "UNKNOWN";
64 default:
65 return os << StringPrintf("%#hhx", state);
66 }
67 }
68
out_get_sample_rate(const struct audio_stream * stream)69 static uint32_t out_get_sample_rate(const struct audio_stream* stream) {
70 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
71 audio_config_t audio_cfg;
72 if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
73 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
74 << " audio_cfg=" << audio_cfg;
75 return audio_cfg.sample_rate;
76 } else {
77 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
78 << ", sample_rate=" << out->sample_rate_ << " failed";
79 return out->sample_rate_;
80 }
81 }
82
out_set_sample_rate(struct audio_stream * stream,uint32_t rate)83 static int out_set_sample_rate(struct audio_stream* stream, uint32_t rate) {
84 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
85 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
86 << ", sample_rate=" << out->sample_rate_;
87 return (rate == out->sample_rate_ ? 0 : -1);
88 }
89
out_get_buffer_size(const struct audio_stream * stream)90 static size_t out_get_buffer_size(const struct audio_stream* stream) {
91 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
92 size_t buffer_size =
93 out->frames_count_ * audio_stream_out_frame_size(&out->stream_out_);
94 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
95 << ", buffer_size=" << buffer_size;
96 return buffer_size;
97 }
98
out_get_channels(const struct audio_stream * stream)99 static audio_channel_mask_t out_get_channels(
100 const struct audio_stream* stream) {
101 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
102 audio_config_t audio_cfg;
103 if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
104 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
105 << " audio_cfg=" << audio_cfg;
106 return audio_cfg.channel_mask;
107 } else {
108 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
109 << ", channels=" << StringPrintf("%#x", out->channel_mask_) << " failure";
110 return out->channel_mask_;
111 }
112 }
113
out_get_format(const struct audio_stream * stream)114 static audio_format_t out_get_format(const struct audio_stream* stream) {
115 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
116 audio_config_t audio_cfg;
117 if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
118 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
119 << " audio_cfg=" << audio_cfg;
120 return audio_cfg.format;
121 } else {
122 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
123 << ", format=" << out->format_ << " failure";
124 return out->format_;
125 }
126 }
127
out_set_format(struct audio_stream * stream,audio_format_t format)128 static int out_set_format(struct audio_stream* stream, audio_format_t format) {
129 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
130 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
131 << ", format=" << out->format_;
132 return (format == out->format_ ? 0 : -1);
133 }
134
out_standby(struct audio_stream * stream)135 static int out_standby(struct audio_stream* stream) {
136 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
137 std::unique_lock<std::mutex> lock(out->mutex_);
138 int retval = 0;
139
140 // out->last_write_time_us_ = 0; unnecessary as a stale write time has same
141 // effect
142 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
143 << " being standby (suspend)";
144 if (out->bluetooth_output_.GetState() == BluetoothStreamState::STARTED) {
145 out->frames_rendered_ = 0;
146 retval = (out->bluetooth_output_.Suspend() ? 0 : -EIO);
147 } else if (out->bluetooth_output_.GetState() ==
148 BluetoothStreamState::STARTING ||
149 out->bluetooth_output_.GetState() ==
150 BluetoothStreamState::SUSPENDING) {
151 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
152 << " NOT ready to be standby";
153 retval = -EBUSY;
154 } else {
155 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_.GetState()
156 << " standby already";
157 }
158 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
159 << " standby (suspend) retval=" << retval;
160
161 return retval;
162 }
163
out_dump(const struct audio_stream * stream,int fd)164 static int out_dump(const struct audio_stream* stream, int fd) {
165 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
166 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState();
167 return 0;
168 }
169
out_set_parameters(struct audio_stream * stream,const char * kvpairs)170 static int out_set_parameters(struct audio_stream* stream,
171 const char* kvpairs) {
172 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
173 std::unique_lock<std::mutex> lock(out->mutex_);
174 int retval = 0;
175
176 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
177 << ", kvpairs=[" << kvpairs << "]";
178
179 std::unordered_map<std::string, std::string> params =
180 ParseAudioParams(kvpairs);
181 if (params.empty()) return retval;
182
183 LOG(VERBOSE) << __func__ << ": ParamsMap=[" << GetAudioParamString(params)
184 << "]";
185
186 audio_config_t audio_cfg;
187 if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end() ||
188 params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end() ||
189 params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
190 if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
191 out->sample_rate_ = audio_cfg.sample_rate;
192 out->channel_mask_ = audio_cfg.channel_mask;
193 out->format_ = audio_cfg.format;
194 LOG(VERBOSE) << "state=" << out->bluetooth_output_.GetState() << ", sample_rate=" << out->sample_rate_
195 << ", channels=" << StringPrintf("%#x", out->channel_mask_) << ", format=" << out->format_;
196 } else {
197 LOG(WARNING) << __func__
198 << ": state=" << out->bluetooth_output_.GetState()
199 << " failed to get audio config";
200 }
201 }
202
203 if (params.find("routing") != params.end()) {
204 auto routing_param = params.find("routing");
205 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
206 << ", stream param '" << routing_param->first.c_str() << "="
207 << routing_param->second.c_str() << "'";
208 }
209
210 if (params.find("A2dpSuspended") != params.end()) {
211 if (params["A2dpSuspended"] == "true") {
212 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
213 << " stream param stopped";
214 if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
215 out->frames_rendered_ = 0;
216 out->bluetooth_output_.Stop();
217 }
218 } else {
219 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
220 << " stream param standby";
221 if (out->bluetooth_output_.GetState() == BluetoothStreamState::DISABLED) {
222 out->bluetooth_output_.SetState(BluetoothStreamState::STANDBY);
223 }
224 }
225 }
226
227 if (params.find("closing") != params.end()) {
228 if (params["closing"] == "true") {
229 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
230 << " stream param closing, disallow any writes?";
231 if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
232 out->frames_rendered_ = 0;
233 out->frames_presented_ = 0;
234 out->bluetooth_output_.Stop();
235 }
236 }
237 }
238
239 if (params.find("exiting") != params.end()) {
240 if (params["exiting"] == "1") {
241 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
242 << " stream param exiting";
243 if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
244 out->frames_rendered_ = 0;
245 out->frames_presented_ = 0;
246 out->bluetooth_output_.Stop();
247 }
248 }
249 }
250
251 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
252 << ", kvpairs=[" << kvpairs << "], retval=" << retval;
253 return retval;
254 }
255
out_get_parameters(const struct audio_stream * stream,const char * keys)256 static char* out_get_parameters(const struct audio_stream* stream,
257 const char* keys) {
258 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
259 std::unique_lock<std::mutex> lock(out->mutex_);
260
261 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
262 << ", keys=[" << keys << "]";
263
264 std::unordered_map<std::string, std::string> params = ParseAudioParams(keys);
265 if (params.empty()) return strdup("");
266
267 audio_config_t audio_cfg;
268 if (out->bluetooth_output_.LoadAudioConfig(&audio_cfg)) {
269 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
270 << " audio_cfg=" << audio_cfg;
271 } else {
272 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_.GetState()
273 << " failed to get audio config";
274 }
275
276 std::unordered_map<std::string, std::string> return_params;
277 if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end()) {
278 std::string param;
279 if (audio_cfg.sample_rate == 16000) {
280 param = "16000";
281 }
282 if (audio_cfg.sample_rate == 24000) {
283 param = "24000";
284 }
285 if (audio_cfg.sample_rate == 44100) {
286 param = "44100";
287 }
288 if (audio_cfg.sample_rate == 48000) {
289 param = "48000";
290 }
291 if (audio_cfg.sample_rate == 88200) {
292 param = "88200";
293 }
294 if (audio_cfg.sample_rate == 96000) {
295 param = "96000";
296 }
297 if (audio_cfg.sample_rate == 176400) {
298 param = "176400";
299 }
300 if (audio_cfg.sample_rate == 192000) {
301 param = "192000";
302 }
303 return_params[AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES] = param;
304 }
305
306 if (params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end()) {
307 std::string param;
308 if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_MONO) {
309 param = "AUDIO_CHANNEL_OUT_MONO";
310 }
311 if (audio_cfg.channel_mask == AUDIO_CHANNEL_OUT_STEREO) {
312 param = "AUDIO_CHANNEL_OUT_STEREO";
313 }
314 return_params[AUDIO_PARAMETER_STREAM_SUP_CHANNELS] = param;
315 }
316
317 if (params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) {
318 std::string param;
319 if (audio_cfg.format == AUDIO_FORMAT_PCM_16_BIT) {
320 param = "AUDIO_FORMAT_PCM_16_BIT";
321 }
322 if (audio_cfg.format == AUDIO_FORMAT_PCM_24_BIT_PACKED) {
323 param = "AUDIO_FORMAT_PCM_24_BIT_PACKED";
324 }
325 if (audio_cfg.format == AUDIO_FORMAT_PCM_32_BIT) {
326 param = "AUDIO_FORMAT_PCM_32_BIT";
327 }
328 return_params[AUDIO_PARAMETER_STREAM_SUP_FORMATS] = param;
329 }
330
331 std::string result;
332 for (const auto& ptr : return_params) {
333 result += ptr.first + "=" + ptr.second + ";";
334 }
335
336 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
337 << ", result=[" << result << "]";
338 return strdup(result.c_str());
339 }
340
out_get_latency_ms(const struct audio_stream_out * stream)341 static uint32_t out_get_latency_ms(const struct audio_stream_out* stream) {
342 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
343 std::unique_lock<std::mutex> lock(out->mutex_);
344 /***
345 * audio_a2dp_hw:
346 * frames_count = buffer_size / frame_size
347 * latency (sec.) = frames_count / sample_rate
348 */
349 uint32_t latency_ms = out->frames_count_ * 1000 / out->sample_rate_;
350 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
351 << ", latency_ms=" << latency_ms;
352 // Sync from audio_a2dp_hw to add extra +200ms
353 return latency_ms + kExtraAudioSyncMs;
354 }
355
out_set_volume(struct audio_stream_out * stream,float left,float right)356 static int out_set_volume(struct audio_stream_out* stream, float left,
357 float right) {
358 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
359 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
360 << ", Left=" << left << ", Right=" << right;
361 return -1;
362 }
363
out_write(struct audio_stream_out * stream,const void * buffer,size_t bytes)364 static ssize_t out_write(struct audio_stream_out* stream, const void* buffer,
365 size_t bytes) {
366 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
367 std::unique_lock<std::mutex> lock(out->mutex_);
368 size_t totalWritten = 0;
369
370 if (out->bluetooth_output_.GetState() != BluetoothStreamState::STARTED) {
371 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState()
372 << " first time bytes=" << bytes;
373 lock.unlock();
374 if (stream->resume(stream)) {
375 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_.GetState()
376 << " failed to resume";
377 usleep(kBluetoothDefaultOutputBufferMs * 1000);
378 return totalWritten;
379 }
380 lock.lock();
381 }
382 lock.unlock();
383 totalWritten = out->bluetooth_output_.WriteData(buffer, bytes);
384 lock.lock();
385
386 struct timespec ts = {.tv_sec = 0, .tv_nsec = 0};
387 clock_gettime(CLOCK_MONOTONIC, &ts);
388 if (totalWritten) {
389 const size_t frames = bytes / audio_stream_out_frame_size(stream);
390 out->frames_rendered_ += frames;
391 out->frames_presented_ += frames;
392 out->last_write_time_us_ = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
393 } else {
394 const int64_t now = (ts.tv_sec * 1000000000LL + ts.tv_nsec) / 1000;
395 const int64_t elapsed_time_since_last_write =
396 now - out->last_write_time_us_;
397 // frames_count = written_data / frame_size
398 // play_time (ms) = frames_count / (sample_rate (Sec.) / 1000000)
399 // sleep_time (ms) = play_time - elapsed_time
400 int64_t sleep_time = bytes * 1000000LL /
401 audio_stream_out_frame_size(stream) /
402 out_get_sample_rate(&stream->common) -
403 elapsed_time_since_last_write;
404 if (sleep_time > 0) {
405 LOG(VERBOSE) << __func__ << ": sleep " << (sleep_time / 1000)
406 << " ms when writting FMQ datapath";
407 lock.unlock();
408 usleep(sleep_time);
409 lock.lock();
410 } else {
411 // we don't sleep when we exit standby (this is typical for a real alsa
412 // buffer).
413 sleep_time = 0;
414 }
415 out->last_write_time_us_ = now + sleep_time;
416 }
417 return totalWritten;
418 }
419
out_get_render_position(const struct audio_stream_out * stream,uint32_t * dsp_frames)420 static int out_get_render_position(const struct audio_stream_out* stream,
421 uint32_t* dsp_frames) {
422 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
423 std::unique_lock<std::mutex> lock(out->mutex_);
424
425 if (dsp_frames == nullptr) return -EINVAL;
426
427 /* frames = (latency (ms) / 1000) * sample_per_seconds */
428 uint64_t latency_frames =
429 (uint64_t)out_get_latency_ms(stream) * out->sample_rate_ / 1000;
430 if (out->frames_rendered_ >= latency_frames) {
431 *dsp_frames = (uint32_t)(out->frames_rendered_ - latency_frames);
432 } else {
433 *dsp_frames = 0;
434 }
435
436 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
437 << ", dsp_frames=" << *dsp_frames;
438 return 0;
439 }
440
out_add_audio_effect(const struct audio_stream * stream,effect_handle_t effect)441 static int out_add_audio_effect(const struct audio_stream* stream,
442 effect_handle_t effect) {
443 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
444 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
445 << ", effect=" << effect;
446 return 0;
447 }
448
out_remove_audio_effect(const struct audio_stream * stream,effect_handle_t effect)449 static int out_remove_audio_effect(const struct audio_stream* stream,
450 effect_handle_t effect) {
451 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
452 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
453 << ", effect=" << effect;
454 return 0;
455 }
456
out_get_next_write_timestamp(const struct audio_stream_out * stream,int64_t * timestamp)457 static int out_get_next_write_timestamp(const struct audio_stream_out* stream,
458 int64_t* timestamp) {
459 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
460 *timestamp = 0;
461 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
462 << ", timestamp=" << *timestamp;
463 return -EINVAL;
464 }
465
out_pause(struct audio_stream_out * stream)466 static int out_pause(struct audio_stream_out* stream) {
467 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
468 std::unique_lock<std::mutex> lock(out->mutex_);
469 int retval = 0;
470 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
471 << ", pausing (suspend)";
472 if (out->bluetooth_output_.GetState() == BluetoothStreamState::STARTED) {
473 out->frames_rendered_ = 0;
474 retval = (out->bluetooth_output_.Suspend() ? 0 : -EIO);
475 } else if (out->bluetooth_output_.GetState() ==
476 BluetoothStreamState::STARTING ||
477 out->bluetooth_output_.GetState() ==
478 BluetoothStreamState::SUSPENDING) {
479 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
480 << " NOT ready to pause?!";
481 retval = -EBUSY;
482 } else {
483 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_.GetState()
484 << " paused already";
485 }
486 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
487 << ", pausing (suspend) retval=" << retval;
488
489 return retval;
490 }
491
out_resume(struct audio_stream_out * stream)492 static int out_resume(struct audio_stream_out* stream) {
493 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
494 std::unique_lock<std::mutex> lock(out->mutex_);
495 int retval = 0;
496
497 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
498 << ", resuming (start)";
499 if (out->bluetooth_output_.GetState() == BluetoothStreamState::STANDBY) {
500 retval = (out->bluetooth_output_.Start() ? 0 : -EIO);
501 } else if (out->bluetooth_output_.GetState() ==
502 BluetoothStreamState::STARTING ||
503 out->bluetooth_output_.GetState() ==
504 BluetoothStreamState::SUSPENDING) {
505 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
506 << " NOT ready to resume?!";
507 retval = -EBUSY;
508 } else if (out->bluetooth_output_.GetState() ==
509 BluetoothStreamState::DISABLED) {
510 LOG(WARNING) << __func__ << ": state=" << out->bluetooth_output_.GetState()
511 << " NOT allow to resume?!";
512 retval = -EINVAL;
513 } else {
514 LOG(DEBUG) << __func__ << ": state=" << out->bluetooth_output_.GetState()
515 << " resumed already";
516 }
517 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
518 << ", resuming (start) retval=" << retval;
519
520 return retval;
521 }
522
out_get_presentation_position(const struct audio_stream_out * stream,uint64_t * frames,struct timespec * timestamp)523 static int out_get_presentation_position(const struct audio_stream_out* stream,
524 uint64_t* frames,
525 struct timespec* timestamp) {
526 if (frames == nullptr || timestamp == nullptr) {
527 return -EINVAL;
528 }
529
530 // bytes is the total number of bytes sent by the Bluetooth stack to a
531 // remote headset
532 uint64_t bytes = 0;
533 // delay_report is the audio delay from the remote headset receiving data to
534 // the headset playing sound in units of nanoseconds
535 uint64_t delay_report_ns = 0;
536 const auto* out = reinterpret_cast<const BluetoothStreamOut*>(stream);
537 std::unique_lock<std::mutex> lock(out->mutex_);
538
539 if (out->bluetooth_output_.GetPresentationPosition(&delay_report_ns, &bytes,
540 timestamp)) {
541 // assume kMinimumDelayMs (100ms) < delay_report_ns < kMaximumDelayMs
542 // (1000ms), or it is invalid / ignored and use old delay calculated
543 // by ourselves.
544 if (delay_report_ns > kMinimumDelayMs * 1000000 &&
545 delay_report_ns < kMaximumDelayMs * 1000000) {
546 *frames = bytes / audio_stream_out_frame_size(stream);
547 timestamp->tv_nsec += delay_report_ns;
548 if (timestamp->tv_nsec > 1000000000) {
549 timestamp->tv_sec += static_cast<int>(timestamp->tv_nsec / 1000000000);
550 timestamp->tv_nsec %= 1000000000;
551 }
552 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState() << ", frames=" << *frames << " ("
553 << bytes << " bytes), timestamp=" << timestamp->tv_sec << "."
554 << StringPrintf("%09ld", timestamp->tv_nsec) << "s";
555 return 0;
556 } else if (delay_report_ns >= kMaximumDelayMs * 1000000) {
557 LOG(WARNING) << __func__
558 << ": state=" << out->bluetooth_output_.GetState()
559 << ", delay_report=" << delay_report_ns << "ns abnormal";
560 }
561 }
562
563 // default to old delay if any failure is found when fetching from ports
564 if (out->frames_presented_ >= out->frames_count_) {
565 clock_gettime(CLOCK_MONOTONIC, timestamp);
566 *frames = out->frames_presented_ - out->frames_count_;
567 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState() << ", frames=" << *frames << " ("
568 << bytes << " bytes), timestamp=" << timestamp->tv_sec << "."
569 << StringPrintf("%09ld", timestamp->tv_nsec) << "s";
570 return 0;
571 }
572
573 *frames = 0;
574 *timestamp = {};
575 return -EWOULDBLOCK;
576 }
577
out_update_source_metadata(struct audio_stream_out * stream,const struct source_metadata * source_metadata)578 static void out_update_source_metadata(
579 struct audio_stream_out* stream,
580 const struct source_metadata* source_metadata) {
581 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
582 std::unique_lock<std::mutex> lock(out->mutex_);
583 if (source_metadata == nullptr || source_metadata->track_count == 0) {
584 return;
585 }
586 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
587 << ", " << source_metadata->track_count << " track(s)";
588 out->bluetooth_output_.UpdateMetadata(source_metadata);
589 }
590
samples_per_ticks(size_t milliseconds,uint32_t sample_rate,size_t channel_count)591 static size_t samples_per_ticks(size_t milliseconds, uint32_t sample_rate,
592 size_t channel_count) {
593 return milliseconds * sample_rate * channel_count / 1000;
594 }
595
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)596 int adev_open_output_stream(struct audio_hw_device* dev,
597 audio_io_handle_t handle, audio_devices_t devices,
598 audio_output_flags_t flags,
599 struct audio_config* config,
600 struct audio_stream_out** stream_out,
601 const char* address __unused) {
602 *stream_out = nullptr;
603 auto* out = new BluetoothStreamOut;
604 if (!out->bluetooth_output_.SetUp(devices)) {
605 delete out;
606 return -EINVAL;
607 }
608 LOG(VERBOSE) << __func__ << ": device=" << StringPrintf("%#x", devices);
609
610 out->stream_out_.common.get_sample_rate = out_get_sample_rate;
611 out->stream_out_.common.set_sample_rate = out_set_sample_rate;
612 out->stream_out_.common.get_buffer_size = out_get_buffer_size;
613 out->stream_out_.common.get_channels = out_get_channels;
614 out->stream_out_.common.get_format = out_get_format;
615 out->stream_out_.common.set_format = out_set_format;
616 out->stream_out_.common.standby = out_standby;
617 out->stream_out_.common.dump = out_dump;
618 out->stream_out_.common.set_parameters = out_set_parameters;
619 out->stream_out_.common.get_parameters = out_get_parameters;
620 out->stream_out_.common.add_audio_effect = out_add_audio_effect;
621 out->stream_out_.common.remove_audio_effect = out_remove_audio_effect;
622 out->stream_out_.get_latency = out_get_latency_ms;
623 out->stream_out_.set_volume = out_set_volume;
624 out->stream_out_.write = out_write;
625 out->stream_out_.get_render_position = out_get_render_position;
626 out->stream_out_.get_next_write_timestamp = out_get_next_write_timestamp;
627 out->stream_out_.pause = out_pause;
628 out->stream_out_.resume = out_resume;
629 out->stream_out_.get_presentation_position = out_get_presentation_position;
630 out->stream_out_.update_source_metadata = out_update_source_metadata;
631
632 if (!out->bluetooth_output_.LoadAudioConfig(config)) {
633 LOG(ERROR) << __func__ << ": state=" << out->bluetooth_output_.GetState()
634 << " failed to get audio config";
635 }
636 // WAR to support Mono / 16 bits per sample as the Bluetooth stack required
637 if (config->channel_mask == AUDIO_CHANNEL_OUT_MONO && config->format == AUDIO_FORMAT_PCM_16_BIT) {
638 LOG(INFO) << __func__ << ": force channels=" << StringPrintf("%#x", out->channel_mask_)
639 << " to be AUDIO_CHANNEL_OUT_STEREO";
640 out->bluetooth_output_.ForcePcmStereoToMono(true);
641 config->channel_mask = AUDIO_CHANNEL_OUT_STEREO;
642 }
643 out->sample_rate_ = config->sample_rate;
644 out->channel_mask_ = config->channel_mask;
645 out->format_ = config->format;
646 // frame is number of samples per channel
647 out->frames_count_ =
648 samples_per_ticks(kBluetoothDefaultOutputBufferMs, out->sample_rate_, 1);
649 out->frames_rendered_ = 0;
650 out->frames_presented_ = 0;
651
652 *stream_out = &out->stream_out_;
653 LOG(INFO) << __func__ << ": state=" << out->bluetooth_output_.GetState() << ", sample_rate=" << out->sample_rate_
654 << ", channels=" << StringPrintf("%#x", out->channel_mask_) << ", format=" << out->format_
655 << ", frames=" << out->frames_count_;
656 return 0;
657 }
658
adev_close_output_stream(struct audio_hw_device * dev,struct audio_stream_out * stream)659 void adev_close_output_stream(struct audio_hw_device* dev,
660 struct audio_stream_out* stream) {
661 auto* out = reinterpret_cast<BluetoothStreamOut*>(stream);
662 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
663 << ", stopping";
664 if (out->bluetooth_output_.GetState() != BluetoothStreamState::DISABLED) {
665 out->frames_rendered_ = 0;
666 out->frames_presented_ = 0;
667 out->bluetooth_output_.Stop();
668 }
669 out->bluetooth_output_.TearDown();
670 LOG(VERBOSE) << __func__ << ": state=" << out->bluetooth_output_.GetState()
671 << ", stopped";
672 delete out;
673 }
674
adev_get_input_buffer_size(const struct audio_hw_device * dev,const struct audio_config * config)675 size_t adev_get_input_buffer_size(const struct audio_hw_device* dev,
676 const struct audio_config* config) {
677 return 320;
678 }
679
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)680 int adev_open_input_stream(struct audio_hw_device* dev,
681 audio_io_handle_t handle, audio_devices_t devices,
682 struct audio_config* config,
683 struct audio_stream_in** stream_in,
684 audio_input_flags_t flags __unused,
685 const char* address __unused,
686 audio_source_t source __unused) {
687 return -EINVAL;
688 }
689
adev_close_input_stream(struct audio_hw_device * dev,struct audio_stream_in * stream_in)690 void adev_close_input_stream(struct audio_hw_device* dev,
691 struct audio_stream_in* stream_in) {}
692