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