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