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