1 /******************************************************************************
2  *
3  *  Copyright 2016 The Android Open Source Project
4  *  Copyright 2009-2012 Broadcom Corporation
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at:
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  ******************************************************************************/
19 
20 #define LOG_TAG "bluetooth-a2dp"
21 #define ATRACE_TAG ATRACE_TAG_AUDIO
22 
23 #include "btif_a2dp_source.h"
24 
25 #include <base/functional/bind.h>
26 #include <bluetooth/log.h>
27 #include <com_android_bluetooth_flags.h>
28 #include <stdio.h>
29 
30 #include <algorithm>
31 #include <chrono>
32 #include <cstdint>
33 #include <cstring>
34 #include <future>
35 #include <string>
36 #include <utility>
37 #include <vector>
38 
39 #include "a2dp_api.h"
40 #include "a2dp_codec_api.h"
41 #include "audio_hal_interface/a2dp_encoding.h"
42 #include "avdt_api.h"
43 #include "bta_av_api.h"
44 #include "bta_av_ci.h"
45 #include "btif_av.h"
46 #include "btif_av_co.h"
47 #include "btif_common.h"
48 #include "btif_hf.h"
49 #include "btif_metrics_logging.h"
50 #include "btm_iso_api.h"
51 #include "common/message_loop_thread.h"
52 #include "common/metrics.h"
53 #include "common/repeating_timer.h"
54 #include "common/time_util.h"
55 #include "hardware/bt_av.h"
56 #include "osi/include/allocator.h"
57 #include "osi/include/fixed_queue.h"
58 #include "osi/include/wakelock.h"
59 #include "stack/include/a2dp_sbc_constants.h"
60 #include "stack/include/acl_api.h"
61 #include "stack/include/acl_api_types.h"
62 #include "stack/include/bt_hdr.h"
63 #include "stack/include/btm_client_interface.h"
64 #include "stack/include/btm_status.h"
65 #include "stack/include/main_thread.h"
66 #include "types/bt_transport.h"
67 #include "types/raw_address.h"
68 
69 #ifdef __ANDROID__
70 #include <cutils/trace.h>
71 #endif
72 
73 using bluetooth::audio::a2dp::Status;
74 using bluetooth::common::A2dpSessionMetrics;
75 using bluetooth::common::BluetoothMetricsLogger;
76 using bluetooth::common::RepeatingTimer;
77 using namespace bluetooth;
78 
79 /**
80  * The typical runlevel of the tx queue size is ~1 buffer
81  * but due to link flow control or thread preemption in lower
82  * layers we might need to temporarily buffer up data.
83  */
84 #define MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ (MAX_PCM_FRAME_NUM_PER_TICK * 2)
85 
86 class SchedulingStats {
87 public:
SchedulingStats()88   SchedulingStats() { Reset(); }
Reset()89   void Reset() {
90     total_updates = 0;
91     last_update_us = 0;
92     overdue_scheduling_count = 0;
93     total_overdue_scheduling_delta_us = 0;
94     max_overdue_scheduling_delta_us = 0;
95     premature_scheduling_count = 0;
96     total_premature_scheduling_delta_us = 0;
97     max_premature_scheduling_delta_us = 0;
98     exact_scheduling_count = 0;
99     total_scheduling_time_us = 0;
100   }
101 
102   // Counter for total updates
103   size_t total_updates;
104 
105   // Last update timestamp (in us)
106   uint64_t last_update_us;
107 
108   // Counter for overdue scheduling
109   size_t overdue_scheduling_count;
110 
111   // Accumulated overdue scheduling deviations (in us)
112   uint64_t total_overdue_scheduling_delta_us;
113 
114   // Max. overdue scheduling delta time (in us)
115   uint64_t max_overdue_scheduling_delta_us;
116 
117   // Counter for premature scheduling
118   size_t premature_scheduling_count;
119 
120   // Accumulated premature scheduling deviations (in us)
121   uint64_t total_premature_scheduling_delta_us;
122 
123   // Max. premature scheduling delta time (in us)
124   uint64_t max_premature_scheduling_delta_us;
125 
126   // Counter for exact scheduling
127   size_t exact_scheduling_count;
128 
129   // Accumulated and counted scheduling time (in us)
130   uint64_t total_scheduling_time_us;
131 };
132 
133 class BtifMediaStats {
134 public:
BtifMediaStats()135   BtifMediaStats() { Reset(); }
Reset()136   void Reset() {
137     session_start_us = 0;
138     session_end_us = 0;
139     tx_queue_enqueue_stats.Reset();
140     tx_queue_dequeue_stats.Reset();
141     tx_queue_total_frames = 0;
142     tx_queue_max_frames_per_packet = 0;
143     tx_queue_total_queueing_time_us = 0;
144     tx_queue_max_queueing_time_us = 0;
145     tx_queue_total_readbuf_calls = 0;
146     tx_queue_last_readbuf_us = 0;
147     tx_queue_total_flushed_messages = 0;
148     tx_queue_last_flushed_us = 0;
149     tx_queue_total_dropped_messages = 0;
150     tx_queue_max_dropped_messages = 0;
151     tx_queue_dropouts = 0;
152     tx_queue_last_dropouts_us = 0;
153     media_read_total_underflow_bytes = 0;
154     media_read_total_underflow_count = 0;
155     media_read_last_underflow_us = 0;
156     codec_index = -1;
157   }
158 
159   uint64_t session_start_us;
160   uint64_t session_end_us;
161 
162   SchedulingStats tx_queue_enqueue_stats;
163   SchedulingStats tx_queue_dequeue_stats;
164 
165   size_t tx_queue_total_frames;
166   size_t tx_queue_max_frames_per_packet;
167 
168   uint64_t tx_queue_total_queueing_time_us;
169   uint64_t tx_queue_max_queueing_time_us;
170 
171   size_t tx_queue_total_readbuf_calls;
172   uint64_t tx_queue_last_readbuf_us;
173 
174   size_t tx_queue_total_flushed_messages;
175   uint64_t tx_queue_last_flushed_us;
176 
177   size_t tx_queue_total_dropped_messages;
178   size_t tx_queue_max_dropped_messages;
179   size_t tx_queue_dropouts;
180   uint64_t tx_queue_last_dropouts_us;
181 
182   size_t media_read_total_underflow_bytes;
183   size_t media_read_total_underflow_count;
184   uint64_t media_read_last_underflow_us;
185 
186   int codec_index = -1;
187 };
188 
189 class BtifA2dpSource {
190 public:
191   enum RunState { kStateOff, kStateStartingUp, kStateRunning, kStateShuttingDown };
192 
BtifA2dpSource()193   BtifA2dpSource()
194       : tx_audio_queue(nullptr),
195         tx_flush(false),
196         sw_audio_is_encoding(false),
197         encoder_interface(nullptr),
198         encoder_interval_ms(0),
199         state_(kStateOff) {}
200 
Reset()201   void Reset() {
202     fixed_queue_free(tx_audio_queue, nullptr);
203     tx_audio_queue = nullptr;
204     tx_flush = false;
205     media_alarm.CancelAndWait();
206     wakelock_release();
207     encoder_interface = nullptr;
208     encoder_interval_ms = 0;
209     stats.Reset();
210     accumulated_stats.Reset();
211     state_ = kStateOff;
212   }
213 
State() const214   BtifA2dpSource::RunState State() const { return state_; }
StateStr() const215   std::string StateStr() const {
216     switch (state_) {
217       case kStateOff:
218         return "STATE_OFF";
219       case kStateStartingUp:
220         return "STATE_STARTING_UP";
221       case kStateRunning:
222         return "STATE_RUNNING";
223       case kStateShuttingDown:
224         return "STATE_SHUTTING_DOWN";
225     }
226   }
227 
SetState(BtifA2dpSource::RunState state)228   void SetState(BtifA2dpSource::RunState state) { state_ = state; }
229 
230   fixed_queue_t* tx_audio_queue;
231   bool tx_flush; /* Discards any outgoing data when true */
232   bool sw_audio_is_encoding;
233   RepeatingTimer media_alarm;
234   const tA2DP_ENCODER_INTERFACE* encoder_interface;
235   uint64_t encoder_interval_ms; /* Local copy of the encoder interval */
236   BtifMediaStats stats;
237   BtifMediaStats accumulated_stats;
238 
239 private:
240   BtifA2dpSource::RunState state_;
241 };
242 
243 /// Source worker thread created to run the CPU heavy encoder calls.
244 /// Exactly three functions are executed on this thread:
245 ///   - btif_a2dp_source_audio_handle_timer
246 ///   - btif_a2dp_source_read_callback
247 ///   - btif_a2dp_source_enqueue_callback
248 static bluetooth::common::MessageLoopThread btif_a2dp_source_thread("bt_a2dp_source_worker_thread");
249 
250 static BtifA2dpSource btif_a2dp_source_cb;
251 static uint8_t btif_a2dp_source_dynamic_audio_buffer_size = MAX_OUTPUT_A2DP_FRAME_QUEUE_SZ;
252 
253 static void btif_a2dp_source_init_delayed(void);
254 static bool btif_a2dp_source_startup(void);
255 static void btif_a2dp_source_startup_delayed(void);
256 static void btif_a2dp_source_start_session_delayed(const RawAddress& peer_address,
257                                                    std::promise<void> start_session_promise);
258 static void btif_a2dp_source_end_session_delayed(const RawAddress& peer_address);
259 static void btif_a2dp_source_shutdown_delayed(std::promise<void>);
260 static void btif_a2dp_source_audio_tx_start_event(void);
261 static void btif_a2dp_source_audio_tx_stop_event(void);
262 static void btif_a2dp_source_audio_tx_flush_event(void);
263 // Set up the A2DP Source codec, and prepare the encoder.
264 // The peer address is |peer_addr|.
265 // This function should be called prior to starting A2DP streaming.
266 static void btif_a2dp_source_setup_codec(const RawAddress& peer_addr);
267 static void btif_a2dp_source_cleanup_codec();
268 static void btif_a2dp_source_cleanup_codec_delayed();
269 static void btif_a2dp_source_encoder_user_config_update_event(
270         const RawAddress& peer_address,
271         const std::vector<btav_a2dp_codec_config_t>& codec_user_preferences,
272         std::promise<void> peer_ready_promise);
273 static void btif_a2dp_source_audio_feeding_update_event(
274         const btav_a2dp_codec_config_t& codec_audio_config);
275 static bool btif_a2dp_source_audio_tx_flush_req(void);
276 static void btif_a2dp_source_audio_handle_timer(void);
277 static uint32_t btif_a2dp_source_read_callback(uint8_t* p_buf, uint32_t len);
278 static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n, uint32_t bytes_read);
279 static void log_tstamps_us(const char* comment, uint64_t timestamp_us);
280 static void update_scheduling_stats(SchedulingStats* stats, uint64_t now_us,
281                                     uint64_t expected_delta);
282 // Update the A2DP Source related metrics.
283 // This function should be called before collecting the metrics.
284 static void btif_a2dp_source_update_metrics(void);
285 static void btm_read_rssi_cb(void* data);
286 static void btm_read_failed_contact_counter_cb(void* data);
287 static void btm_read_tx_power_cb(void* data);
288 
btif_a2dp_source_accumulate_scheduling_stats(SchedulingStats * src,SchedulingStats * dst)289 static void btif_a2dp_source_accumulate_scheduling_stats(SchedulingStats* src,
290                                                          SchedulingStats* dst) {
291   dst->total_updates += src->total_updates;
292   dst->last_update_us = src->last_update_us;
293   dst->overdue_scheduling_count += src->overdue_scheduling_count;
294   dst->total_overdue_scheduling_delta_us += src->total_overdue_scheduling_delta_us;
295   dst->max_overdue_scheduling_delta_us =
296           std::max(dst->max_overdue_scheduling_delta_us, src->max_overdue_scheduling_delta_us);
297   dst->premature_scheduling_count += src->premature_scheduling_count;
298   dst->total_premature_scheduling_delta_us += src->total_premature_scheduling_delta_us;
299   dst->max_premature_scheduling_delta_us =
300           std::max(dst->max_premature_scheduling_delta_us, src->max_premature_scheduling_delta_us);
301   dst->exact_scheduling_count += src->exact_scheduling_count;
302   dst->total_scheduling_time_us += src->total_scheduling_time_us;
303 }
304 
btif_a2dp_source_accumulate_stats(BtifMediaStats * src,BtifMediaStats * dst)305 static void btif_a2dp_source_accumulate_stats(BtifMediaStats* src, BtifMediaStats* dst) {
306   dst->tx_queue_total_frames += src->tx_queue_total_frames;
307   dst->tx_queue_max_frames_per_packet =
308           std::max(dst->tx_queue_max_frames_per_packet, src->tx_queue_max_frames_per_packet);
309   dst->tx_queue_total_queueing_time_us += src->tx_queue_total_queueing_time_us;
310   dst->tx_queue_max_queueing_time_us =
311           std::max(dst->tx_queue_max_queueing_time_us, src->tx_queue_max_queueing_time_us);
312   dst->tx_queue_total_readbuf_calls += src->tx_queue_total_readbuf_calls;
313   dst->tx_queue_last_readbuf_us = src->tx_queue_last_readbuf_us;
314   dst->tx_queue_total_flushed_messages += src->tx_queue_total_flushed_messages;
315   dst->tx_queue_last_flushed_us = src->tx_queue_last_flushed_us;
316   dst->tx_queue_total_dropped_messages += src->tx_queue_total_dropped_messages;
317   dst->tx_queue_max_dropped_messages =
318           std::max(dst->tx_queue_max_dropped_messages, src->tx_queue_max_dropped_messages);
319   dst->tx_queue_dropouts += src->tx_queue_dropouts;
320   dst->tx_queue_last_dropouts_us = src->tx_queue_last_dropouts_us;
321   dst->media_read_total_underflow_bytes += src->media_read_total_underflow_bytes;
322   dst->media_read_total_underflow_count += src->media_read_total_underflow_count;
323   dst->media_read_last_underflow_us = src->media_read_last_underflow_us;
324   if (dst->codec_index < 0) {
325     dst->codec_index = src->codec_index;
326   }
327   btif_a2dp_source_accumulate_scheduling_stats(&src->tx_queue_enqueue_stats,
328                                                &dst->tx_queue_enqueue_stats);
329   btif_a2dp_source_accumulate_scheduling_stats(&src->tx_queue_dequeue_stats,
330                                                &dst->tx_queue_dequeue_stats);
331   src->Reset();
332 }
333 
334 /// Select the thread to run a2dp source actions on (a2dp encoder excluded).
local_thread()335 static bluetooth::common::MessageLoopThread* local_thread() {
336   return com::android::bluetooth::flags::a2dp_source_threading_fix() ? get_main_thread()
337                                                                      : &btif_a2dp_source_thread;
338 }
339 
btif_a2dp_source_init(void)340 bool btif_a2dp_source_init(void) {
341   log::info("");
342 
343   // Start A2DP Source media task
344   btif_a2dp_source_thread.StartUp();
345 
346   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_init_delayed));
347   return true;
348 }
349 
350 class A2dpStreamCallbacks : public bluetooth::audio::a2dp::StreamCallbacks {
StartStream(bool low_latency) const351   Status StartStream(bool low_latency) const override {
352     // Check if a phone call is currently active.
353     if (!bluetooth::headset::IsCallIdle()) {
354       log::error("unable to start stream: call is active");
355       return Status::FAILURE;
356     }
357 
358     // Check if LE Audio is currently active.
359     if (com::android::bluetooth::flags::a2dp_check_lea_iso_channel() &&
360         hci::IsoManager::GetInstance()->GetNumberOfActiveIso() > 0) {
361       log::error("unable to start stream: LEA is active");
362       return Status::FAILURE;
363     }
364 
365     // Check if the stream has already been started.
366     if (btif_av_stream_started_ready(A2dpType::kSource)) {
367       log::verbose("stream is already started");
368       return Status::SUCCESS;
369     }
370 
371     // Check if the stream is ready to start.
372     if (!btif_av_stream_ready(A2dpType::kSource)) {
373       log::error("unable to start stream: not ready");
374       return Status::FAILURE;
375     }
376 
377     // Check if codec needs to be switched prior to stream start.
378     invoke_switch_codec_cb(low_latency);
379 
380     // Post start event. The start request is pending, completion will be
381     // notified to bluetooth::audio::a2dp::ack_stream_started.
382     btif_av_stream_start_with_latency(low_latency);
383     return Status::PENDING;
384   }
385 
SuspendStream() const386   Status SuspendStream() const override {
387     // Check if the stream is already suspended.
388     if (!btif_av_stream_started_ready(A2dpType::kSource)) {
389       btif_av_clear_remote_suspend_flag(A2dpType::kSource);
390       log::verbose("stream is already suspended");
391       return Status::SUCCESS;
392     }
393 
394     // Post suspend event. The suspend request is pending, completion will
395     // be notified to bluetooth::audio::a2dp::ack_stream_suspended.
396     btif_av_stream_suspend();
397     return Status::PENDING;
398   }
399 
StopStream() const400   Status StopStream() const override {
401     // Check if the stream is already suspended.
402     if (!btif_av_stream_started_ready(A2dpType::kSource)) {
403       btif_av_clear_remote_suspend_flag(A2dpType::kSource);
404       log::verbose("stream is already stopped");
405       return Status::SUCCESS;
406     }
407 
408     // Post stop event. The stop request is pending, but completion is not
409     // notified to the HAL.
410     btif_av_stream_stop(RawAddress::kEmpty);
411     return Status::PENDING;
412   }
413 
SetLatencyMode(bool low_latency) const414   Status SetLatencyMode(bool low_latency) const override {
415     btif_av_set_low_latency(low_latency);
416     return Status::SUCCESS;
417   }
418 };
419 
420 static const A2dpStreamCallbacks a2dp_stream_callbacks;
421 
btif_a2dp_source_init_delayed(void)422 static void btif_a2dp_source_init_delayed(void) {
423   log::info("");
424   // When codec extensibility is enabled in the audio HAL interface,
425   // the provider needs to be initialized earlier in order to ensure
426   // get_a2dp_configuration and parse_a2dp_configuration can be
427   // invoked before the stream is started.
428   bluetooth::audio::a2dp::init(local_thread(), &a2dp_stream_callbacks,
429                                btif_av_is_a2dp_offload_enabled());
430 }
431 
btif_a2dp_source_startup(void)432 static bool btif_a2dp_source_startup(void) {
433   log::info("state={}", btif_a2dp_source_cb.StateStr());
434 
435   if (btif_a2dp_source_cb.State() != BtifA2dpSource::kStateOff) {
436     log::error("A2DP Source media task already running");
437     return false;
438   }
439 
440   btif_a2dp_source_cb.Reset();
441   btif_a2dp_source_cb.SetState(BtifA2dpSource::kStateStartingUp);
442   btif_a2dp_source_cb.tx_audio_queue = fixed_queue_new(SIZE_MAX);
443 
444   // Schedule the rest of the operations
445   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_startup_delayed));
446 
447   return true;
448 }
449 
btif_a2dp_source_startup_delayed()450 static void btif_a2dp_source_startup_delayed() {
451   log::info("state={}", btif_a2dp_source_cb.StateStr());
452   if (!btif_a2dp_source_thread.EnableRealTimeScheduling()) {
453 #if defined(__ANDROID__)
454     log::fatal("unable to enable real time scheduling");
455 #endif
456   }
457   if (!bluetooth::audio::a2dp::init(local_thread(), &a2dp_stream_callbacks,
458                                     btif_av_is_a2dp_offload_enabled())) {
459     log::warn("Failed to setup the bluetooth audio HAL");
460   }
461   btif_a2dp_source_cb.SetState(BtifA2dpSource::kStateRunning);
462 }
463 
btif_a2dp_source_start_session(const RawAddress & peer_address,std::promise<void> peer_ready_promise)464 bool btif_a2dp_source_start_session(const RawAddress& peer_address,
465                                     std::promise<void> peer_ready_promise) {
466   log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr());
467 
468   btif_a2dp_source_audio_tx_flush_req();
469 
470   if (local_thread()->DoInThread(
471               FROM_HERE, base::BindOnce(&btif_a2dp_source_start_session_delayed, peer_address,
472                                         std::move(peer_ready_promise)))) {
473     return true;
474   } else {
475     // cannot set promise but triggers crash
476     log::fatal("peer_address={} state={} fails to context switch", peer_address,
477                btif_a2dp_source_cb.StateStr());
478     return false;
479   }
480 }
481 
btif_a2dp_source_start_session_delayed(const RawAddress & peer_address,std::promise<void> peer_ready_promise)482 static void btif_a2dp_source_start_session_delayed(const RawAddress& peer_address,
483                                                    std::promise<void> peer_ready_promise) {
484   log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr());
485 
486   btif_a2dp_source_setup_codec(peer_address);
487 
488   if (btif_a2dp_source_cb.State() != BtifA2dpSource::kStateRunning) {
489     log::error("A2DP Source media task is not running");
490     peer_ready_promise.set_value();
491     return;
492   }
493 
494   if (bluetooth::audio::a2dp::is_hal_enabled()) {
495     bluetooth::audio::a2dp::start_session();
496     bluetooth::audio::a2dp::set_remote_delay(btif_av_get_audio_delay(A2dpType::kSource));
497     BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart(
498             bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0);
499   } else {
500     BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionStart(
501             bluetooth::common::CONNECTION_TECHNOLOGY_TYPE_BREDR, 0);
502   }
503 
504   peer_ready_promise.set_value();
505 }
506 
btif_a2dp_source_restart_session(const RawAddress & old_peer_address,const RawAddress & new_peer_address,std::promise<void> peer_ready_promise)507 bool btif_a2dp_source_restart_session(const RawAddress& old_peer_address,
508                                       const RawAddress& new_peer_address,
509                                       std::promise<void> peer_ready_promise) {
510   log::info("old_peer_address={} new_peer_address={} state={}", old_peer_address, new_peer_address,
511             btif_a2dp_source_cb.StateStr());
512 
513   log::assert_that(!new_peer_address.IsEmpty(), "assert failed: !new_peer_address.IsEmpty()");
514 
515   // Must stop first the audio streaming
516   btif_a2dp_source_stop_audio_req();
517 
518   // If the old active peer was valid, end the old session.
519   // Otherwise, time to startup the A2DP Source processing.
520   if (!old_peer_address.IsEmpty()) {
521     btif_a2dp_source_end_session(old_peer_address);
522   } else {
523     btif_a2dp_source_startup();
524   }
525 
526   // Start the session.
527   btif_a2dp_source_start_session(new_peer_address, std::move(peer_ready_promise));
528   // If audio was streaming before, DON'T start audio streaming, but leave the
529   // control to the audio HAL.
530   return true;
531 }
532 
btif_a2dp_source_end_session(const RawAddress & peer_address)533 bool btif_a2dp_source_end_session(const RawAddress& peer_address) {
534   log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr());
535   local_thread()->DoInThread(FROM_HERE,
536                              base::BindOnce(&btif_a2dp_source_end_session_delayed, peer_address));
537   btif_a2dp_source_cleanup_codec();
538   return true;
539 }
540 
btif_a2dp_source_end_session_delayed(const RawAddress & peer_address)541 static void btif_a2dp_source_end_session_delayed(const RawAddress& peer_address) {
542   log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr());
543   if ((btif_a2dp_source_cb.State() == BtifA2dpSource::kStateRunning) ||
544       (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateShuttingDown)) {
545     btif_av_stream_stop(peer_address);
546   } else {
547     log::error("A2DP Source media task is not running");
548   }
549   if (bluetooth::audio::a2dp::is_hal_enabled()) {
550     bluetooth::audio::a2dp::end_session();
551     BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd(
552             bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0);
553   } else {
554     BluetoothMetricsLogger::GetInstance()->LogBluetoothSessionEnd(
555             bluetooth::common::DISCONNECT_REASON_UNKNOWN, 0);
556   }
557 }
558 
btif_a2dp_source_allow_low_latency_audio(bool allowed)559 void btif_a2dp_source_allow_low_latency_audio(bool allowed) {
560   log::info("allowed={}", allowed);
561 
562   local_thread()->DoInThread(
563           FROM_HERE,
564           base::BindOnce(bluetooth::audio::a2dp::set_audio_low_latency_mode_allowed, allowed));
565 }
566 
btif_a2dp_source_shutdown(std::promise<void> shutdown_complete_promise)567 void btif_a2dp_source_shutdown(std::promise<void> shutdown_complete_promise) {
568   log::info("state={}", btif_a2dp_source_cb.StateStr());
569 
570   if ((btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) ||
571       (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateShuttingDown)) {
572     return;
573   }
574 
575   /* Make sure no channels are restarted while shutting down */
576   btif_a2dp_source_cb.SetState(BtifA2dpSource::kStateShuttingDown);
577 
578   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_shutdown_delayed,
579                                                        std::move(shutdown_complete_promise)));
580 }
581 
btif_a2dp_source_shutdown_delayed(std::promise<void> shutdown_complete_promise)582 static void btif_a2dp_source_shutdown_delayed(std::promise<void> shutdown_complete_promise) {
583   log::info("state={}", btif_a2dp_source_cb.StateStr());
584 
585   // Stop the timer
586   btif_a2dp_source_cb.media_alarm.CancelAndWait();
587   wakelock_release();
588 
589   bluetooth::audio::a2dp::cleanup();
590 
591   fixed_queue_free(btif_a2dp_source_cb.tx_audio_queue, nullptr);
592   btif_a2dp_source_cb.tx_audio_queue = nullptr;
593 
594   btif_a2dp_source_cb.SetState(BtifA2dpSource::kStateOff);
595 
596   shutdown_complete_promise.set_value();
597 }
598 
btif_a2dp_source_cleanup(void)599 void btif_a2dp_source_cleanup(void) {
600   log::info("state={}", btif_a2dp_source_cb.StateStr());
601 
602   // Make sure the source is shutdown
603   std::promise<void> shutdown_complete_promise;
604   btif_a2dp_source_shutdown(std::move(shutdown_complete_promise));
605 
606   // Exit the thread
607   btif_a2dp_source_thread.ShutDown();
608 }
609 
610 // This runs on worker thread
btif_a2dp_source_is_streaming(void)611 bool btif_a2dp_source_is_streaming(void) { return btif_a2dp_source_cb.media_alarm.IsScheduled(); }
612 
613 /// Return the MTU for the active peer audio connection.
btif_a2dp_get_peer_mtu(A2dpCodecConfig * a2dp_config)614 static uint16_t btif_a2dp_get_peer_mtu(A2dpCodecConfig* a2dp_config) {
615   uint8_t codec_info[AVDT_CODEC_SIZE];
616   a2dp_config->copyOutOtaCodecConfig(codec_info);
617 
618   RawAddress peer_addr = btif_av_source_active_peer();
619   tA2DP_ENCODER_INIT_PEER_PARAMS peer_params;
620   bta_av_co_get_peer_params(peer_addr, &peer_params);
621   uint16_t peer_mtu = peer_params.peer_mtu;
622   uint16_t effective_mtu = bta_av_co_get_encoder_effective_frame_size(peer_addr);
623 
624   if (effective_mtu > 0 && effective_mtu < peer_mtu) {
625     peer_mtu = effective_mtu;
626   }
627 
628   // b/188020925
629   // When SBC headsets report middle quality bitpool under a larger MTU, we
630   // reduce the packet size to prevent the hardware encoder from putting too
631   // many frames in one packet.
632   if (a2dp_config->codecIndex() == BTAV_A2DP_CODEC_INDEX_SOURCE_SBC &&
633       codec_info[2] /* maxBitpool */ <= A2DP_SBC_BITPOOL_MIDDLE_QUALITY) {
634     peer_mtu = MAX_2MBPS_AVDTP_MTU;
635   }
636 
637   // b/177205770
638   // Fix the MTU value not to be greater than an AVDTP packet, so the data
639   // encoded by A2DP hardware encoder can be fitted into one AVDTP packet
640   // without fragmented
641   if (peer_mtu > MAX_3MBPS_AVDTP_MTU) {
642     peer_mtu = MAX_3MBPS_AVDTP_MTU;
643   }
644 
645   return peer_mtu;
646 }
647 
btif_a2dp_source_setup_codec(const RawAddress & peer_address)648 static void btif_a2dp_source_setup_codec(const RawAddress& peer_address) {
649   log::info("peer_address={} state={}", peer_address, btif_a2dp_source_cb.StateStr());
650 
651   tA2DP_ENCODER_INIT_PEER_PARAMS peer_params;
652   bta_av_co_get_peer_params(peer_address, &peer_params);
653   if (!bta_av_co_set_active_source_peer(peer_address)) {
654     log::error("Cannot stream audio: cannot set active peer to {}", peer_address);
655     return;
656   }
657 
658   const tA2DP_ENCODER_INTERFACE* encoder_interface = bta_av_co_get_encoder_interface(peer_address);
659   if (encoder_interface == nullptr) {
660     log::error("Cannot stream audio: no source encoder interface");
661     return;
662   }
663 
664   A2dpCodecConfig* a2dp_codec_config = bta_av_get_a2dp_current_codec();
665   if (a2dp_codec_config == nullptr) {
666     log::error("Cannot stream audio: current codec is not set");
667     return;
668   }
669 
670   encoder_interface->encoder_init(&peer_params, a2dp_codec_config, btif_a2dp_source_read_callback,
671                                   btif_a2dp_source_enqueue_callback);
672 
673   // Save a local copy of the encoder_interval_ms
674   btif_a2dp_source_cb.encoder_interface = encoder_interface;
675   btif_a2dp_source_cb.encoder_interval_ms =
676           btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms();
677 
678   if (bluetooth::audio::a2dp::is_hal_enabled()) {
679     bluetooth::audio::a2dp::setup_codec(a2dp_codec_config,
680                                         btif_a2dp_get_peer_mtu(a2dp_codec_config),
681                                         bta_av_co_get_encoder_preferred_interval_us());
682   }
683 }
684 
btif_a2dp_source_cleanup_codec()685 static void btif_a2dp_source_cleanup_codec() {
686   log::info("state={}", btif_a2dp_source_cb.StateStr());
687   // Must stop media task first before cleaning up the encoder
688   btif_a2dp_source_stop_audio_req();
689   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup_codec_delayed));
690 }
691 
btif_a2dp_source_cleanup_codec_delayed()692 static void btif_a2dp_source_cleanup_codec_delayed() {
693   log::info("state={}", btif_a2dp_source_cb.StateStr());
694   if (btif_a2dp_source_cb.encoder_interface != nullptr) {
695     btif_a2dp_source_cb.encoder_interface->encoder_cleanup();
696     btif_a2dp_source_cb.encoder_interface = nullptr;
697   }
698 }
699 
btif_a2dp_source_start_audio_req(void)700 void btif_a2dp_source_start_audio_req(void) {
701   log::info("state={}", btif_a2dp_source_cb.StateStr());
702 
703   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_start_event));
704 }
705 
btif_a2dp_source_stop_audio_req(void)706 void btif_a2dp_source_stop_audio_req(void) {
707   log::info("state={}", btif_a2dp_source_cb.StateStr());
708 
709   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_stop_event));
710 }
711 
btif_a2dp_source_encoder_user_config_update_req(const RawAddress & peer_address,const std::vector<btav_a2dp_codec_config_t> & codec_user_preferences,std::promise<void> peer_ready_promise)712 void btif_a2dp_source_encoder_user_config_update_req(
713         const RawAddress& peer_address,
714         const std::vector<btav_a2dp_codec_config_t>& codec_user_preferences,
715         std::promise<void> peer_ready_promise) {
716   log::info("peer_address={} state={} {} codec_preference(s)", peer_address,
717             btif_a2dp_source_cb.StateStr(), codec_user_preferences.size());
718 
719   if (!local_thread()->DoInThread(
720               FROM_HERE,
721               base::BindOnce(&btif_a2dp_source_encoder_user_config_update_event, peer_address,
722                              codec_user_preferences, std::move(peer_ready_promise)))) {
723     // cannot set promise but triggers crash
724     log::fatal("peer_address={} state={} fails to context switch", peer_address,
725                btif_a2dp_source_cb.StateStr());
726   }
727 }
728 
btif_a2dp_source_encoder_user_config_update_event(const RawAddress & peer_address,const std::vector<btav_a2dp_codec_config_t> & codec_user_preferences,std::promise<void> peer_ready_promise)729 static void btif_a2dp_source_encoder_user_config_update_event(
730         const RawAddress& peer_address,
731         const std::vector<btav_a2dp_codec_config_t>& codec_user_preferences,
732         std::promise<void> peer_ready_promise) {
733   bool restart_output = false;
734   bool success = false;
735   for (auto codec_user_config : codec_user_preferences) {
736     success = bta_av_co_set_codec_user_config(peer_address, codec_user_config, &restart_output);
737     if (success) {
738       log::info("peer_address={} state={} codec_preference=[{}] restart_output={}", peer_address,
739                 btif_a2dp_source_cb.StateStr(), codec_user_config.ToString(), restart_output);
740       break;
741     }
742   }
743   if (success && restart_output) {
744     // Codec reconfiguration is in progress, and it is safe to unlock since
745     // remaining tasks like starting audio session and reporting new codec
746     // will be handled by BTA_AV_RECONFIG_EVT later.
747     peer_ready_promise.set_value();
748     return;
749   }
750   if (!success) {
751     log::error("cannot update codec user configuration(s)");
752   }
753   if (!peer_address.IsEmpty() && peer_address == btif_av_source_active_peer()) {
754     // No more actions needed with remote, and if succeed, user had changed the
755     // config like the bits per sample only. Let's resume the session now.
756     btif_a2dp_source_start_session(peer_address, std::move(peer_ready_promise));
757   } else {
758     // Unlock for non-active peer
759     peer_ready_promise.set_value();
760   }
761 }
762 
btif_a2dp_source_feeding_update_req(const btav_a2dp_codec_config_t & codec_audio_config)763 void btif_a2dp_source_feeding_update_req(const btav_a2dp_codec_config_t& codec_audio_config) {
764   log::info("state={}", btif_a2dp_source_cb.StateStr());
765   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_feeding_update_event,
766                                                        codec_audio_config));
767 }
768 
btif_a2dp_source_audio_feeding_update_event(const btav_a2dp_codec_config_t & codec_audio_config)769 static void btif_a2dp_source_audio_feeding_update_event(
770         const btav_a2dp_codec_config_t& codec_audio_config) {
771   log::info("state={}", btif_a2dp_source_cb.StateStr());
772   if (!bta_av_co_set_codec_audio_config(codec_audio_config)) {
773     log::error("cannot update codec audio feeding parameters");
774   }
775 }
776 
btif_a2dp_source_on_idle(void)777 void btif_a2dp_source_on_idle(void) {
778   log::info("state={}", btif_a2dp_source_cb.StateStr());
779   if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) {
780     return;
781   }
782 
783   /* Make sure media task is stopped */
784   btif_a2dp_source_stop_audio_req();
785 }
786 
btif_a2dp_source_on_stopped(tBTA_AV_SUSPEND * p_av_suspend)787 void btif_a2dp_source_on_stopped(tBTA_AV_SUSPEND* p_av_suspend) {
788   log::info("state={}", btif_a2dp_source_cb.StateStr());
789 
790   btif_a2dp_source_cb.sw_audio_is_encoding = false;
791 
792   // allow using this API for other (acknowledgement and stopping media task)
793   // than suspend
794   if (p_av_suspend != nullptr && p_av_suspend->status != BTA_AV_SUCCESS) {
795     log::error("A2DP stop failed: status={}, initiator={}", p_av_suspend->status,
796                p_av_suspend->initiator);
797     if (p_av_suspend->initiator) {
798       bluetooth::audio::a2dp::ack_stream_suspended(Status::FAILURE);
799     }
800   } else {
801     bluetooth::audio::a2dp::ack_stream_suspended(Status::SUCCESS);
802   }
803 
804   if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) {
805     return;
806   }
807 
808   // ensure tx frames are immediately suspended
809   btif_a2dp_source_cb.tx_flush = true;
810   // ensure tx frames are immediately flushed
811   btif_a2dp_source_audio_tx_flush_req();
812 
813   // request to stop media task
814   btif_a2dp_source_stop_audio_req();
815 
816   // once software stream is fully stopped we will ack back
817 }
818 
btif_a2dp_source_on_suspended(tBTA_AV_SUSPEND * p_av_suspend)819 void btif_a2dp_source_on_suspended(tBTA_AV_SUSPEND* p_av_suspend) {
820   log::info("state={}", btif_a2dp_source_cb.StateStr());
821 
822   if (btif_a2dp_source_cb.State() == BtifA2dpSource::kStateOff) {
823     return;
824   }
825 
826   log::assert_that(p_av_suspend != nullptr, "Suspend result could not be nullptr");
827 
828   // check for status failures
829   if (p_av_suspend->status != BTA_AV_SUCCESS) {
830     log::warn("A2DP suspend failed: status={}, initiator={}", p_av_suspend->status,
831               p_av_suspend->initiator);
832     if (p_av_suspend->initiator) {
833       bluetooth::audio::a2dp::ack_stream_suspended(Status::FAILURE);
834     }
835   } else if (btif_av_is_a2dp_offload_running()) {
836     bluetooth::audio::a2dp::ack_stream_suspended(Status::SUCCESS);
837   }
838 
839   // ensure tx frames are immediately suspended
840   btif_a2dp_source_cb.tx_flush = true;
841 
842   // stop timer tick
843   btif_a2dp_source_stop_audio_req();
844 
845   // once software stream is fully stopped we will ack back
846 }
847 
848 /* when true media task discards any tx frames */
btif_a2dp_source_set_tx_flush(bool enable)849 void btif_a2dp_source_set_tx_flush(bool enable) {
850   log::info("enable={} state={}", enable, btif_a2dp_source_cb.StateStr());
851   btif_a2dp_source_cb.tx_flush = enable;
852 }
853 
btif_a2dp_source_audio_tx_start_event(void)854 static void btif_a2dp_source_audio_tx_start_event(void) {
855   log::info("streaming {} state={}", btif_a2dp_source_is_streaming(),
856             btif_a2dp_source_cb.StateStr());
857 
858   btif_a2dp_source_cb.stats.Reset();
859   btif_a2dp_source_cb.stats.session_start_us = bluetooth::common::time_get_os_boottime_us();
860   btif_a2dp_source_cb.stats.session_end_us = 0;
861 
862   A2dpCodecConfig* codec_config = bta_av_get_a2dp_current_codec();
863   if (codec_config != nullptr) {
864     btif_a2dp_source_cb.stats.codec_index = codec_config->codecIndex();
865   }
866 
867   if (btif_av_is_a2dp_offload_running()) {
868     return;
869   }
870 
871   log::assert_that(btif_a2dp_source_cb.encoder_interface != nullptr,
872                    "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr");
873 
874   log::verbose("starting media encoder timer with interval {}ms",
875                btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms());
876 
877   wakelock_acquire();
878   btif_a2dp_source_cb.encoder_interface->feeding_reset();
879   btif_a2dp_source_cb.tx_flush = false;
880   btif_a2dp_source_cb.sw_audio_is_encoding = true;
881   btif_a2dp_source_cb.media_alarm.SchedulePeriodic(
882           btif_a2dp_source_thread.GetWeakPtr(), FROM_HERE,
883           base::BindRepeating(&btif_a2dp_source_audio_handle_timer),
884           std::chrono::milliseconds(
885                   btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms()));
886 }
887 
btif_a2dp_source_audio_tx_stop_event(void)888 static void btif_a2dp_source_audio_tx_stop_event(void) {
889   log::info("streaming {} state={}", btif_a2dp_source_is_streaming(),
890             btif_a2dp_source_cb.StateStr());
891 
892   btif_a2dp_source_cb.stats.session_end_us = bluetooth::common::time_get_os_boottime_us();
893 
894   btif_a2dp_source_update_metrics();
895   btif_a2dp_source_accumulate_stats(&btif_a2dp_source_cb.stats,
896                                     &btif_a2dp_source_cb.accumulated_stats);
897 
898   if (btif_av_is_a2dp_offload_running()) {
899     return;
900   }
901 
902   if (!btif_a2dp_source_is_streaming()) {
903     return;
904   }
905 
906   /* Drain data still left in the queue */
907   static constexpr size_t AUDIO_STREAM_OUTPUT_BUFFER_SZ = 28 * 512;
908   uint8_t p_buf[AUDIO_STREAM_OUTPUT_BUFFER_SZ * 2];
909   bluetooth::audio::a2dp::read(p_buf, sizeof(p_buf));
910 
911   /* Stop the timer first */
912   btif_a2dp_source_cb.media_alarm.CancelAndWait();
913   wakelock_release();
914 
915   bluetooth::audio::a2dp::ack_stream_suspended(Status::SUCCESS);
916 
917   /* audio engine stopped, reset tx suspended flag */
918   btif_a2dp_source_cb.tx_flush = false;
919 
920   /* Reset the media feeding state */
921   if (btif_a2dp_source_cb.encoder_interface != nullptr) {
922     btif_a2dp_source_cb.encoder_interface->feeding_reset();
923   }
924 }
925 
926 /// Periodic task responsible for encoding the audio stream and forwarding
927 /// to the remote device. It will read PCM samples from the HAL provided FMQ,
928 /// encode them into audio frames. Runs on the source worker thread.
929 ///
930 /// The timer driving the periodic task is cancelled before any state cleanup
931 /// when the stream is ended.
btif_a2dp_source_audio_handle_timer(void)932 static void btif_a2dp_source_audio_handle_timer(void) {
933   uint64_t timestamp_us = bluetooth::common::time_get_audio_server_tick_us();
934   uint64_t stats_timestamp_us = bluetooth::common::time_get_os_boottime_us();
935 
936   log_tstamps_us("A2DP Source tx scheduling timer", timestamp_us);
937 
938   log::assert_that(btif_a2dp_source_cb.encoder_interface != nullptr,
939                    "assert failed: btif_a2dp_source_cb.encoder_interface != nullptr");
940 
941   size_t transmit_queue_length = fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue);
942 
943 #ifdef __ANDROID__
944   ATRACE_INT("btif TX queue", transmit_queue_length);
945 #endif
946 
947   if (btif_a2dp_source_cb.encoder_interface->set_transmit_queue_length != nullptr) {
948     btif_a2dp_source_cb.encoder_interface->set_transmit_queue_length(transmit_queue_length);
949   }
950 
951   btif_a2dp_source_cb.encoder_interface->send_frames(timestamp_us);
952 
953   bta_av_ci_src_data_ready(BTA_AV_CHNL_AUDIO);
954   update_scheduling_stats(&btif_a2dp_source_cb.stats.tx_queue_enqueue_stats, stats_timestamp_us,
955                           btif_a2dp_source_cb.encoder_interval_ms * 1000);
956 }
957 
958 /// Callback invoked by the encoder for reading PCM audio data from the
959 /// Bluetooth Audio HAL. Runs on the source worker thread.
btif_a2dp_source_read_callback(uint8_t * p_buf,uint32_t len)960 static uint32_t btif_a2dp_source_read_callback(uint8_t* p_buf, uint32_t len) {
961   if (!btif_a2dp_source_cb.sw_audio_is_encoding) {
962     return 0;
963   }
964 
965   uint32_t bytes_read = bluetooth::audio::a2dp::read(p_buf, len);
966 
967   if (bytes_read < len) {
968     log::warn("UNDERFLOW: ONLY READ {} BYTES OUT OF {}", bytes_read, len);
969     btif_a2dp_source_cb.stats.media_read_total_underflow_bytes += (len - bytes_read);
970     btif_a2dp_source_cb.stats.media_read_total_underflow_count++;
971     btif_a2dp_source_cb.stats.media_read_last_underflow_us =
972             bluetooth::common::time_get_os_boottime_us();
973     log_a2dp_audio_underrun_event(btif_av_source_active_peer(),
974                                   btif_a2dp_source_cb.encoder_interval_ms, len - bytes_read);
975   }
976 
977   return bytes_read;
978 }
979 
980 /// Callback invoked by the encoder for sending encoded audio frames to the
981 /// remote Bluetooth device. Runs on the source worker thread.
btif_a2dp_source_enqueue_callback(BT_HDR * p_buf,size_t frames_n,uint32_t)982 static bool btif_a2dp_source_enqueue_callback(BT_HDR* p_buf, size_t frames_n,
983                                               uint32_t /*bytes_read*/) {
984   uint64_t now_us = bluetooth::common::time_get_os_boottime_us();
985 
986   // Check if the transmission queue has been flushed.
987   if (btif_a2dp_source_cb.tx_flush) {
988     log::verbose("tx suspended, discarded frame");
989 
990     btif_a2dp_source_cb.stats.tx_queue_total_flushed_messages +=
991             fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue);
992     btif_a2dp_source_cb.stats.tx_queue_last_flushed_us = now_us;
993     fixed_queue_flush(btif_a2dp_source_cb.tx_audio_queue, osi_free);
994 
995     osi_free(p_buf);
996     return false;
997   }
998 
999   // Check for TX queue overflow
1000   // TODO: Using frames_n here is probably wrong: should be "+ 1" instead.
1001   if (fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue) + frames_n >
1002       btif_a2dp_source_dynamic_audio_buffer_size) {
1003     log::warn("TX queue buffer size now={} adding={} max={}",
1004               (uint32_t)fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue), (uint32_t)frames_n,
1005               btif_a2dp_source_dynamic_audio_buffer_size);
1006     // Keep track of drop-outs
1007     btif_a2dp_source_cb.stats.tx_queue_dropouts++;
1008     btif_a2dp_source_cb.stats.tx_queue_last_dropouts_us = now_us;
1009 
1010     // Flush all queued buffers
1011     size_t drop_n = fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue);
1012     btif_a2dp_source_cb.stats.tx_queue_max_dropped_messages =
1013             std::max(drop_n, btif_a2dp_source_cb.stats.tx_queue_max_dropped_messages);
1014     int num_dropped_encoded_bytes = 0;
1015     int num_dropped_encoded_frames = 0;
1016     while (fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue)) {
1017       btif_a2dp_source_cb.stats.tx_queue_total_dropped_messages++;
1018       void* p_data = fixed_queue_try_dequeue(btif_a2dp_source_cb.tx_audio_queue);
1019       if (p_data != nullptr) {
1020         auto p_dropped_buf = static_cast<BT_HDR*>(p_data);
1021         num_dropped_encoded_bytes += p_dropped_buf->len;
1022         num_dropped_encoded_frames += p_dropped_buf->layer_specific;
1023         osi_free(p_data);
1024       }
1025     }
1026     log_a2dp_audio_overrun_event(btif_av_source_active_peer(),
1027                                  btif_a2dp_source_cb.encoder_interval_ms, drop_n,
1028                                  num_dropped_encoded_frames, num_dropped_encoded_bytes);
1029 
1030     // Request additional debug info if we had to flush buffers
1031     RawAddress peer_bda = btif_av_source_active_peer();
1032     tBTM_STATUS status =
1033             get_btm_client_interface().link_controller.BTM_ReadRSSI(peer_bda, btm_read_rssi_cb);
1034     if (status != tBTM_STATUS::BTM_CMD_STARTED) {
1035       log::warn("Cannot read RSSI: status {}", status);
1036     }
1037 
1038     status = BTM_ReadFailedContactCounter(peer_bda, btm_read_failed_contact_counter_cb);
1039     if (status != tBTM_STATUS::BTM_CMD_STARTED) {
1040       log::warn("Cannot read Failed Contact Counter: status {}", status);
1041     }
1042 
1043     status = BTM_ReadTxPower(peer_bda, BT_TRANSPORT_BR_EDR, btm_read_tx_power_cb);
1044     if (status != tBTM_STATUS::BTM_CMD_STARTED) {
1045       log::warn("Cannot read Tx Power: status {}", status);
1046     }
1047   }
1048 
1049   // Update the statistics.
1050   btif_a2dp_source_cb.stats.tx_queue_total_frames += frames_n;
1051   btif_a2dp_source_cb.stats.tx_queue_max_frames_per_packet =
1052           std::max(frames_n, btif_a2dp_source_cb.stats.tx_queue_max_frames_per_packet);
1053 
1054   fixed_queue_enqueue(btif_a2dp_source_cb.tx_audio_queue, p_buf);
1055 
1056   return true;
1057 }
1058 
btif_a2dp_source_audio_tx_flush_event(void)1059 static void btif_a2dp_source_audio_tx_flush_event(void) {
1060   /* Flush all enqueued audio buffers (encoded) */
1061   log::info("state={}", btif_a2dp_source_cb.StateStr());
1062   if (btif_av_is_a2dp_offload_running()) {
1063     return;
1064   }
1065 
1066   if (btif_a2dp_source_cb.encoder_interface != nullptr) {
1067     btif_a2dp_source_cb.encoder_interface->feeding_flush();
1068   }
1069 
1070   btif_a2dp_source_cb.stats.tx_queue_total_flushed_messages +=
1071           fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue);
1072   btif_a2dp_source_cb.stats.tx_queue_last_flushed_us = bluetooth::common::time_get_os_boottime_us();
1073   fixed_queue_flush(btif_a2dp_source_cb.tx_audio_queue, osi_free);
1074 }
1075 
btif_a2dp_source_audio_tx_flush_req(void)1076 static bool btif_a2dp_source_audio_tx_flush_req(void) {
1077   log::info("state={}", btif_a2dp_source_cb.StateStr());
1078 
1079   local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_flush_event));
1080   return true;
1081 }
1082 
btif_a2dp_source_audio_readbuf(void)1083 BT_HDR* btif_a2dp_source_audio_readbuf(void) {
1084   uint64_t now_us = bluetooth::common::time_get_os_boottime_us();
1085   BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_dequeue(btif_a2dp_source_cb.tx_audio_queue);
1086 
1087   btif_a2dp_source_cb.stats.tx_queue_total_readbuf_calls++;
1088   btif_a2dp_source_cb.stats.tx_queue_last_readbuf_us = now_us;
1089   if (p_buf != nullptr) {
1090     // Update the statistics
1091     update_scheduling_stats(&btif_a2dp_source_cb.stats.tx_queue_dequeue_stats, now_us,
1092                             btif_a2dp_source_cb.encoder_interval_ms * 1000);
1093   }
1094 
1095   return p_buf;
1096 }
1097 
log_tstamps_us(const char * comment,uint64_t timestamp_us)1098 static void log_tstamps_us(const char* comment, uint64_t timestamp_us) {
1099   static uint64_t prev_us = 0;
1100   log::verbose("[{}] ts {:08}, diff : {:08}, queue sz {}", comment, timestamp_us,
1101                timestamp_us - prev_us, fixed_queue_length(btif_a2dp_source_cb.tx_audio_queue));
1102   prev_us = timestamp_us;
1103 }
1104 
update_scheduling_stats(SchedulingStats * stats,uint64_t now_us,uint64_t expected_delta)1105 static void update_scheduling_stats(SchedulingStats* stats, uint64_t now_us,
1106                                     uint64_t expected_delta) {
1107   uint64_t last_us = stats->last_update_us;
1108 
1109   stats->total_updates++;
1110   stats->last_update_us = now_us;
1111 
1112   if (last_us == 0) {
1113     return;  // First update: expected delta doesn't apply
1114   }
1115 
1116   uint64_t deadline_us = last_us + expected_delta;
1117   if (deadline_us < now_us) {
1118     // Overdue scheduling
1119     uint64_t delta_us = now_us - deadline_us;
1120     // Ignore extreme outliers
1121     if (delta_us < 10 * expected_delta) {
1122       stats->max_overdue_scheduling_delta_us =
1123               std::max(delta_us, stats->max_overdue_scheduling_delta_us);
1124       stats->total_overdue_scheduling_delta_us += delta_us;
1125       stats->overdue_scheduling_count++;
1126       stats->total_scheduling_time_us += now_us - last_us;
1127     }
1128   } else if (deadline_us > now_us) {
1129     // Premature scheduling
1130     uint64_t delta_us = deadline_us - now_us;
1131     // Ignore extreme outliers
1132     if (delta_us < 10 * expected_delta) {
1133       stats->max_premature_scheduling_delta_us =
1134               std::max(delta_us, stats->max_premature_scheduling_delta_us);
1135       stats->total_premature_scheduling_delta_us += delta_us;
1136       stats->premature_scheduling_count++;
1137       stats->total_scheduling_time_us += now_us - last_us;
1138     }
1139   } else {
1140     // On-time scheduling
1141     stats->exact_scheduling_count++;
1142     stats->total_scheduling_time_us += now_us - last_us;
1143   }
1144 }
1145 
btif_a2dp_source_debug_dump(int fd)1146 void btif_a2dp_source_debug_dump(int fd) {
1147   btif_a2dp_source_accumulate_stats(&btif_a2dp_source_cb.stats,
1148                                     &btif_a2dp_source_cb.accumulated_stats);
1149   uint64_t now_us = bluetooth::common::time_get_os_boottime_us();
1150   BtifMediaStats* accumulated_stats = &btif_a2dp_source_cb.accumulated_stats;
1151   SchedulingStats* enqueue_stats = &accumulated_stats->tx_queue_enqueue_stats;
1152   SchedulingStats* dequeue_stats = &accumulated_stats->tx_queue_dequeue_stats;
1153   size_t ave_size;
1154   uint64_t ave_time_us;
1155 
1156   dprintf(fd, "\nA2DP State:\n");
1157   dprintf(fd, "  TxQueue:\n");
1158 
1159   dprintf(fd, "  Counts (enqueue/dequeue/readbuf)                        : %zu / %zu / %zu\n",
1160           enqueue_stats->total_updates, dequeue_stats->total_updates,
1161           accumulated_stats->tx_queue_total_readbuf_calls);
1162 
1163   dprintf(fd, "  Last update time ago in ms (enqueue/dequeue/readbuf)    : %llu / %llu / %llu\n",
1164           (enqueue_stats->last_update_us > 0)
1165                   ? (unsigned long long)(now_us - enqueue_stats->last_update_us) / 1000
1166                   : 0,
1167           (dequeue_stats->last_update_us > 0)
1168                   ? (unsigned long long)(now_us - dequeue_stats->last_update_us) / 1000
1169                   : 0,
1170           (accumulated_stats->tx_queue_last_readbuf_us > 0)
1171                   ? (unsigned long long)(now_us - accumulated_stats->tx_queue_last_readbuf_us) /
1172                             1000
1173                   : 0);
1174 
1175   ave_size = 0;
1176   if (enqueue_stats->total_updates != 0) {
1177     ave_size = accumulated_stats->tx_queue_total_frames / enqueue_stats->total_updates;
1178   }
1179   dprintf(fd, "  Frames per packet (total/max/ave)                       : %zu / %zu / %zu\n",
1180           accumulated_stats->tx_queue_total_frames,
1181           accumulated_stats->tx_queue_max_frames_per_packet, ave_size);
1182 
1183   dprintf(fd, "  Counts (flushed/dropped/dropouts)                       : %zu / %zu / %zu\n",
1184           accumulated_stats->tx_queue_total_flushed_messages,
1185           accumulated_stats->tx_queue_total_dropped_messages, accumulated_stats->tx_queue_dropouts);
1186 
1187   dprintf(fd, "  Counts (max dropped)                                    : %zu\n",
1188           accumulated_stats->tx_queue_max_dropped_messages);
1189 
1190   dprintf(fd, "  Last update time ago in ms (flushed/dropped)            : %llu / %llu\n",
1191           (accumulated_stats->tx_queue_last_flushed_us > 0)
1192                   ? (unsigned long long)(now_us - accumulated_stats->tx_queue_last_flushed_us) /
1193                             1000
1194                   : 0,
1195           (accumulated_stats->tx_queue_last_dropouts_us > 0)
1196                   ? (unsigned long long)(now_us - accumulated_stats->tx_queue_last_dropouts_us) /
1197                             1000
1198                   : 0);
1199 
1200   dprintf(fd, "  Counts (underflow)                                      : %zu\n",
1201           accumulated_stats->media_read_total_underflow_count);
1202 
1203   dprintf(fd, "  Bytes (underflow)                                       : %zu\n",
1204           accumulated_stats->media_read_total_underflow_bytes);
1205 
1206   dprintf(fd, "  Last update time ago in ms (underflow)                  : %llu\n",
1207           (accumulated_stats->media_read_last_underflow_us > 0)
1208                   ? (unsigned long long)(now_us - accumulated_stats->media_read_last_underflow_us) /
1209                             1000
1210                   : 0);
1211 
1212   //
1213   // TxQueue enqueue stats
1214   //
1215   dprintf(fd, "  Enqueue deviation counts (overdue/premature)            : %zu / %zu\n",
1216           enqueue_stats->overdue_scheduling_count, enqueue_stats->premature_scheduling_count);
1217 
1218   ave_time_us = 0;
1219   if (enqueue_stats->overdue_scheduling_count != 0) {
1220     ave_time_us = enqueue_stats->total_overdue_scheduling_delta_us /
1221                   enqueue_stats->overdue_scheduling_count;
1222   }
1223   dprintf(fd, "  Enqueue overdue scheduling time in ms (total/max/ave)   : %llu / %llu / %llu\n",
1224           (unsigned long long)enqueue_stats->total_overdue_scheduling_delta_us / 1000,
1225           (unsigned long long)enqueue_stats->max_overdue_scheduling_delta_us / 1000,
1226           (unsigned long long)ave_time_us / 1000);
1227 
1228   ave_time_us = 0;
1229   if (enqueue_stats->premature_scheduling_count != 0) {
1230     ave_time_us = enqueue_stats->total_premature_scheduling_delta_us /
1231                   enqueue_stats->premature_scheduling_count;
1232   }
1233   dprintf(fd, "  Enqueue premature scheduling time in ms (total/max/ave) : %llu / %llu / %llu\n",
1234           (unsigned long long)enqueue_stats->total_premature_scheduling_delta_us / 1000,
1235           (unsigned long long)enqueue_stats->max_premature_scheduling_delta_us / 1000,
1236           (unsigned long long)ave_time_us / 1000);
1237 
1238   //
1239   // TxQueue dequeue stats
1240   //
1241   dprintf(fd, "  Dequeue deviation counts (overdue/premature)            : %zu / %zu\n",
1242           dequeue_stats->overdue_scheduling_count, dequeue_stats->premature_scheduling_count);
1243 
1244   ave_time_us = 0;
1245   if (dequeue_stats->overdue_scheduling_count != 0) {
1246     ave_time_us = dequeue_stats->total_overdue_scheduling_delta_us /
1247                   dequeue_stats->overdue_scheduling_count;
1248   }
1249   dprintf(fd, "  Dequeue overdue scheduling time in ms (total/max/ave)   : %llu / %llu / %llu\n",
1250           (unsigned long long)dequeue_stats->total_overdue_scheduling_delta_us / 1000,
1251           (unsigned long long)dequeue_stats->max_overdue_scheduling_delta_us / 1000,
1252           (unsigned long long)ave_time_us / 1000);
1253 
1254   ave_time_us = 0;
1255   if (dequeue_stats->premature_scheduling_count != 0) {
1256     ave_time_us = dequeue_stats->total_premature_scheduling_delta_us /
1257                   dequeue_stats->premature_scheduling_count;
1258   }
1259   dprintf(fd, "  Dequeue premature scheduling time in ms (total/max/ave) : %llu / %llu / %llu\n",
1260           (unsigned long long)dequeue_stats->total_premature_scheduling_delta_us / 1000,
1261           (unsigned long long)dequeue_stats->max_premature_scheduling_delta_us / 1000,
1262           (unsigned long long)ave_time_us / 1000);
1263 }
1264 
btif_a2dp_source_update_metrics(void)1265 static void btif_a2dp_source_update_metrics(void) {
1266   BtifMediaStats stats = btif_a2dp_source_cb.stats;
1267   SchedulingStats enqueue_stats = stats.tx_queue_enqueue_stats;
1268   A2dpSessionMetrics metrics;
1269   metrics.codec_index = stats.codec_index;
1270   metrics.is_a2dp_offload = btif_av_is_a2dp_offload_running();
1271 
1272   // session_start_us is 0 when btif_a2dp_source_start_audio_req() is not called
1273   // mark the metric duration as invalid (-1) in this case
1274   if (stats.session_start_us != 0) {
1275     metrics.audio_duration_ms = (stats.session_end_us - stats.session_start_us) / 1000;
1276   }
1277 
1278   if (enqueue_stats.total_updates > 1) {
1279     metrics.media_timer_min_ms = btif_a2dp_source_cb.encoder_interval_ms -
1280                                  (enqueue_stats.max_premature_scheduling_delta_us / 1000);
1281     metrics.media_timer_max_ms = btif_a2dp_source_cb.encoder_interval_ms +
1282                                  (enqueue_stats.max_overdue_scheduling_delta_us / 1000);
1283 
1284     metrics.total_scheduling_count = enqueue_stats.overdue_scheduling_count +
1285                                      enqueue_stats.premature_scheduling_count +
1286                                      enqueue_stats.exact_scheduling_count;
1287     if (metrics.total_scheduling_count > 0) {
1288       metrics.media_timer_avg_ms =
1289               enqueue_stats.total_scheduling_time_us / (1000 * metrics.total_scheduling_count);
1290     }
1291 
1292     metrics.buffer_overruns_max_count = stats.tx_queue_max_dropped_messages;
1293     metrics.buffer_overruns_total = stats.tx_queue_total_dropped_messages;
1294     metrics.buffer_underruns_count = stats.media_read_total_underflow_count;
1295     metrics.buffer_underruns_average = 0;
1296     if (metrics.buffer_underruns_count > 0) {
1297       metrics.buffer_underruns_average =
1298               (float)stats.media_read_total_underflow_bytes / metrics.buffer_underruns_count;
1299     }
1300   }
1301   BluetoothMetricsLogger::GetInstance()->LogA2dpSession(metrics);
1302 
1303   if (metrics.audio_duration_ms != -1) {
1304     log_a2dp_session_metrics_event(btif_av_source_active_peer(), metrics.audio_duration_ms,
1305                                    metrics.media_timer_min_ms, metrics.media_timer_max_ms,
1306                                    metrics.media_timer_avg_ms, metrics.total_scheduling_count,
1307                                    metrics.buffer_overruns_max_count, metrics.buffer_overruns_total,
1308                                    metrics.buffer_underruns_average, metrics.buffer_underruns_count,
1309                                    metrics.codec_index, metrics.is_a2dp_offload);
1310   }
1311 }
1312 
btif_a2dp_source_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size)1313 void btif_a2dp_source_set_dynamic_audio_buffer_size(uint8_t dynamic_audio_buffer_size) {
1314   btif_a2dp_source_dynamic_audio_buffer_size = dynamic_audio_buffer_size;
1315 }
1316 
btm_read_rssi_cb(void * data)1317 static void btm_read_rssi_cb(void* data) {
1318   if (data == nullptr) {
1319     log::error("Read RSSI request timed out");
1320     return;
1321   }
1322 
1323   tBTM_RSSI_RESULT* result = (tBTM_RSSI_RESULT*)data;
1324   if (result->status != tBTM_STATUS::BTM_SUCCESS) {
1325     log::error("unable to read remote RSSI (status {})", result->status);
1326     return;
1327   }
1328 
1329   log_read_rssi_result(result->rem_bda, bluetooth::common::kUnknownConnectionHandle,
1330                        result->hci_status, result->rssi);
1331 
1332   log::warn("device: {}, rssi: {}", result->rem_bda, result->rssi);
1333 }
1334 
btm_read_failed_contact_counter_cb(void * data)1335 static void btm_read_failed_contact_counter_cb(void* data) {
1336   if (data == nullptr) {
1337     log::error("Read Failed Contact Counter request timed out");
1338     return;
1339   }
1340 
1341   tBTM_FAILED_CONTACT_COUNTER_RESULT* result = (tBTM_FAILED_CONTACT_COUNTER_RESULT*)data;
1342   if (result->status != tBTM_STATUS::BTM_SUCCESS) {
1343     log::error("unable to read Failed Contact Counter (status {})", result->status);
1344     return;
1345   }
1346   log_read_failed_contact_counter_result(result->rem_bda,
1347                                          bluetooth::common::kUnknownConnectionHandle,
1348                                          result->hci_status, result->failed_contact_counter);
1349 
1350   log::warn("device: {}, Failed Contact Counter: {}", result->rem_bda,
1351             result->failed_contact_counter);
1352 }
1353 
btm_read_tx_power_cb(void * data)1354 static void btm_read_tx_power_cb(void* data) {
1355   if (data == nullptr) {
1356     log::error("Read Tx Power request timed out");
1357     return;
1358   }
1359 
1360   tBTM_TX_POWER_RESULT* result = (tBTM_TX_POWER_RESULT*)data;
1361   if (result->status != tBTM_STATUS::BTM_SUCCESS) {
1362     log::error("unable to read Tx Power (status {})", result->status);
1363     return;
1364   }
1365   log_read_tx_power_level_result(result->rem_bda, bluetooth::common::kUnknownConnectionHandle,
1366                                  result->hci_status, result->tx_power);
1367 
1368   log::warn("device: {}, Tx Power: {}", result->rem_bda, result->tx_power);
1369 }
1370