stream_apis.cc 27 KB

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