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