esp32.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. #include <signal.h>
  2. #include "sdkconfig.h"
  3. #include "esp_system.h"
  4. #include "squeezelite.h"
  5. #include <signal.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <unistd.h>
  9. #include <string.h>
  10. #include "freertos/FreeRTOS.h"
  11. #include "freertos/task.h"
  12. #include "freertos/timers.h"
  13. #include "nvs.h"
  14. #include "nvs_flash.h"
  15. #include "esp_system.h"
  16. #include "esp_log.h"
  17. #include "esp_bt.h"
  18. #include "bt_app_core.h"
  19. #include "esp_bt_main.h"
  20. #include "esp_bt_device.h"
  21. #include "esp_gap_bt_api.h"
  22. #include "esp_a2dp_api.h"
  23. #include "esp_avrc_api.h"
  24. #define BT_AV_TAG "BT_AV"
  25. u8_t *bt_optr;
  26. extern log_level loglevel;
  27. extern struct outputstate output;
  28. extern struct buffer *outputbuf;
  29. extern struct buffer *streambuf;
  30. #define LOCK mutex_lock(outputbuf->mutex)
  31. #define UNLOCK mutex_unlock(outputbuf->mutex)
  32. int64_t connecting_timeout = 0;
  33. #define A2DP_TIMER_INIT connecting_timeout = esp_timer_get_time() +(CONFIG_A2DP_CONNECT_TIMEOUT_MS * 1000)
  34. #define IS_A2DP_TIMER_OVER esp_timer_get_time() >= connecting_timeout
  35. void get_mac(u8_t mac[]) {
  36. esp_read_mac(mac, ESP_MAC_WIFI_STA);
  37. }
  38. _sig_func_ptr signal(int sig, _sig_func_ptr func) {
  39. return NULL;
  40. }
  41. void *audio_calloc(size_t nmemb, size_t size) {
  42. return calloc(nmemb, size);
  43. }
  44. struct codec *register_mpg(void) {
  45. LOG_INFO("mpg unavailable");
  46. return NULL;
  47. }
  48. #if !CONFIG_INCLUDE_FAAD
  49. struct codec *register_faad(void) {
  50. LOG_INFO("aac unavailable");
  51. return NULL;
  52. }
  53. #endif
  54. #if !CONFIG_INCLUDE_MAD
  55. struct codec *register_mad(void) {
  56. LOG_INFO("mad unavailable");
  57. return NULL;
  58. }
  59. #endif
  60. #if !CONFIG_INCLUDE_FLAC
  61. struct codec *register_flac(void) {
  62. LOG_INFO("flac unavailable");
  63. return NULL;
  64. }
  65. #endif
  66. #if !CONFIG_INCLUDE_VORBIS
  67. struct codec *register_vorbis(void) {
  68. LOG_INFO("vorbis unavailable");
  69. return NULL;
  70. }
  71. #endif
  72. #if !CONFIG_INCLUDE_ALAC
  73. struct codec *register_alac(void) {
  74. LOG_INFO("alac unavailable");
  75. return NULL;
  76. }
  77. #endif
  78. #define LOG_DEBUG_EVENT(e) LOG_DEBUG("evt: " STR(e))
  79. #define LOG_SDEBUG_EVENT(e) LOG_SDEBUG("evt: " STR(e))
  80. /* event for handler "bt_av_hdl_stack_up */
  81. enum {
  82. BT_APP_EVT_STACK_UP = 0,
  83. };
  84. /* A2DP global state */
  85. enum {
  86. APP_AV_STATE_IDLE,
  87. APP_AV_STATE_DISCOVERING,
  88. APP_AV_STATE_DISCOVERED,
  89. APP_AV_STATE_UNCONNECTED,
  90. APP_AV_STATE_CONNECTING,
  91. APP_AV_STATE_CONNECTED,
  92. APP_AV_STATE_DISCONNECTING,
  93. };
  94. char * APP_AV_STATE_DESC[] = {
  95. "APP_AV_STATE_IDLE",
  96. "APP_AV_STATE_DISCOVERING",
  97. "APP_AV_STATE_DISCOVERED",
  98. "APP_AV_STATE_UNCONNECTED",
  99. "APP_AV_STATE_CONNECTING",
  100. "APP_AV_STATE_CONNECTED",
  101. "APP_AV_STATE_DISCONNECTING"
  102. };
  103. /* sub states of APP_AV_STATE_CONNECTED */
  104. enum {
  105. APP_AV_MEDIA_STATE_IDLE,
  106. APP_AV_MEDIA_STATE_STARTING,
  107. APP_AV_MEDIA_STATE_STARTED,
  108. APP_AV_MEDIA_STATE_STOPPING,
  109. APP_AV_MEDIA_STATE_WAIT_DISCONNECT
  110. };
  111. #define BT_APP_HEART_BEAT_EVT (0xff00)
  112. /// handler for bluetooth stack enabled events
  113. static void bt_av_hdl_stack_evt(uint16_t event, void *p_param);
  114. /// callback function for A2DP source
  115. static void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param);
  116. /// callback function for A2DP source audio data stream
  117. static int32_t bt_app_a2d_data_cb(uint8_t *data, int32_t len);
  118. static void a2d_app_heart_beat(void *arg);
  119. /// A2DP application state machine
  120. static void bt_app_av_sm_hdlr(uint16_t event, void *param);
  121. /* A2DP application state machine handler for each state */
  122. static void bt_app_av_state_unconnected(uint16_t event, void *param);
  123. static void bt_app_av_state_connecting(uint16_t event, void *param);
  124. static void bt_app_av_state_connected(uint16_t event, void *param);
  125. static void bt_app_av_state_disconnecting(uint16_t event, void *param);
  126. static esp_bd_addr_t s_peer_bda = {0};
  127. static uint8_t s_peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1];
  128. static int s_a2d_state = APP_AV_STATE_IDLE;
  129. static int s_media_state = APP_AV_MEDIA_STATE_IDLE;
  130. static int s_intv_cnt = 0;
  131. static uint32_t s_pkt_cnt = 0;
  132. static TimerHandle_t s_tmr;
  133. static char *bda2str(esp_bd_addr_t bda, char *str, size_t size)
  134. {
  135. if (bda == NULL || str == NULL || size < 18) {
  136. return NULL;
  137. }
  138. uint8_t *p = bda;
  139. sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
  140. p[0], p[1], p[2], p[3], p[4], p[5]);
  141. return str;
  142. }
  143. void hal_bluetooth_init(log_level level)
  144. {
  145. /*
  146. * Bluetooth audio source init Start
  147. */
  148. loglevel = level;
  149. //running_test = false;
  150. ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_BLE));
  151. esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
  152. if (esp_bt_controller_init(&bt_cfg) != ESP_OK) {
  153. LOG_ERROR("%s initialize controller failed\n", __func__);
  154. return;
  155. }
  156. if (esp_bt_controller_enable(ESP_BT_MODE_CLASSIC_BT) != ESP_OK) {
  157. LOG_ERROR("%s enable controller failed\n", __func__);
  158. return;
  159. }
  160. if (esp_bluedroid_init() != ESP_OK) {
  161. LOG_ERROR("%s initialize bluedroid failed\n", __func__);
  162. return;
  163. }
  164. if (esp_bluedroid_enable() != ESP_OK) {
  165. LOG_ERROR("%s enable bluedroid failed\n", __func__);
  166. return;
  167. }
  168. /* create application task */
  169. bt_app_task_start_up();
  170. /* Bluetooth device name, connection mode and profile set up */
  171. bt_app_work_dispatch(bt_av_hdl_stack_evt, BT_APP_EVT_STACK_UP, NULL, 0, NULL);
  172. #if (CONFIG_BT_SSP_ENABLED == true)
  173. /* Set default parameters for Secure Simple Pairing */
  174. esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE;
  175. esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO;
  176. esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t));
  177. #endif
  178. /*
  179. * Set default parameters for Legacy Pairing
  180. * Use variable pin, input pin code when pairing
  181. */
  182. esp_bt_pin_type_t pin_type = ESP_BT_PIN_TYPE_VARIABLE;
  183. esp_bt_pin_code_t pin_code;
  184. esp_bt_gap_set_pin(pin_type, 0, pin_code);
  185. }
  186. static bool get_name_from_eir(uint8_t *eir, uint8_t *bdname, uint8_t *bdname_len)
  187. {
  188. uint8_t *rmt_bdname = NULL;
  189. uint8_t rmt_bdname_len = 0;
  190. if (!eir) {
  191. return false;
  192. }
  193. rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len);
  194. if (!rmt_bdname) {
  195. rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len);
  196. }
  197. if (rmt_bdname) {
  198. if (rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN) {
  199. rmt_bdname_len = ESP_BT_GAP_MAX_BDNAME_LEN;
  200. }
  201. if (bdname) {
  202. memcpy(bdname, rmt_bdname, rmt_bdname_len);
  203. bdname[rmt_bdname_len] = '\0';
  204. }
  205. if (bdname_len) {
  206. *bdname_len = rmt_bdname_len;
  207. }
  208. return true;
  209. }
  210. return false;
  211. }
  212. #define LOG_INFO_NO_LF(fmt, ...) if (loglevel >= lINFO) logprint(fmt, ##__VA_ARGS__)
  213. static void filter_inquiry_scan_result(esp_bt_gap_cb_param_t *param)
  214. {
  215. char bda_str[18];
  216. uint32_t cod = 0;
  217. int32_t rssi = -129; /* invalid value */
  218. uint8_t *eir = NULL;
  219. uint8_t nameLen = 0;
  220. esp_bt_gap_dev_prop_t *p;
  221. memset(s_peer_bdname, 0x00,sizeof(s_peer_bdname));
  222. LOG_INFO("\n=======================\nScanned device: %s", bda2str(param->disc_res.bda, bda_str, 18));
  223. for (int i = 0; i < param->disc_res.num_prop; i++) {
  224. p = param->disc_res.prop + i;
  225. switch (p->type) {
  226. case ESP_BT_GAP_DEV_PROP_COD:
  227. cod = *(uint32_t *)(p->val);
  228. LOG_INFO_NO_LF("\n-- Class of Device: 0x%x", cod);
  229. break;
  230. case ESP_BT_GAP_DEV_PROP_RSSI:
  231. rssi = *(int8_t *)(p->val);
  232. LOG_INFO_NO_LF("\n-- RSSI: %d", rssi);
  233. break;
  234. case ESP_BT_GAP_DEV_PROP_EIR:
  235. eir = (uint8_t *)(p->val);
  236. LOG_INFO_NO_LF("\n-- EIR: %d", eir);
  237. break;
  238. case ESP_BT_GAP_DEV_PROP_BDNAME:
  239. nameLen = (p->len > ESP_BT_GAP_MAX_BDNAME_LEN) ? ESP_BT_GAP_MAX_BDNAME_LEN : (uint8_t)p->len;
  240. memcpy(s_peer_bdname, (uint8_t *)(p->val), nameLen);
  241. s_peer_bdname[nameLen] = '\0';
  242. LOG_INFO_NO_LF("\n-- Name: %s", s_peer_bdname);
  243. break;
  244. default:
  245. break;
  246. }
  247. }
  248. if (!esp_bt_gap_is_valid_cod(cod)){
  249. /* search for device with MAJOR service class as "rendering" in COD */
  250. LOG_INFO_NO_LF("\n--Invalid class of device. Skipping.\n");
  251. return;
  252. }
  253. else if (!(esp_bt_gap_get_cod_srvc(cod) & ESP_BT_COD_SRVC_RENDERING))
  254. {
  255. LOG_INFO_NO_LF("\n--Not a rendering device. Skipping.\n");
  256. return;
  257. }
  258. /* search for device named "ESP_SPEAKER" in its extended inqury response */
  259. if (eir) {
  260. LOG_INFO_NO_LF("\n--Getting details from eir.\n");
  261. get_name_from_eir(eir, s_peer_bdname, NULL);
  262. LOG_INFO("--\nDevice name is %s",s_peer_bdname);
  263. }
  264. if (strcmp((char *)s_peer_bdname, CONFIG_A2DP_SINK_NAME) == 0) {
  265. LOG_INFO("Found a target device, address %s, name %s", bda_str, s_peer_bdname);
  266. if(esp_bt_gap_cancel_discovery()!=ESP_ERR_INVALID_STATE)
  267. {
  268. LOG_INFO("Cancel device discovery ...");
  269. memcpy(s_peer_bda, param->disc_res.bda, ESP_BD_ADDR_LEN);
  270. s_a2d_state = APP_AV_STATE_DISCOVERED;
  271. }
  272. else
  273. {
  274. LOG_ERROR("Cancel device discovery failed...");
  275. }
  276. }
  277. else
  278. {
  279. LOG_INFO("Not the device we are looking for. Continuing scan.");
  280. }
  281. }
  282. void bt_app_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
  283. {
  284. switch (event) {
  285. case ESP_BT_GAP_DISC_RES_EVT: {
  286. filter_inquiry_scan_result(param);
  287. break;
  288. }
  289. case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: {
  290. if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STOPPED)
  291. {
  292. if (s_a2d_state == APP_AV_STATE_DISCOVERED)
  293. {
  294. if(esp_a2d_source_connect(s_peer_bda)!=ESP_ERR_INVALID_STATE)
  295. {
  296. s_a2d_state = APP_AV_STATE_CONNECTING;
  297. LOG_INFO("Device discovery stopped. a2dp connecting to peer: %s", s_peer_bdname);
  298. A2DP_TIMER_INIT;
  299. }
  300. else
  301. {
  302. // not discovered, continue to discover
  303. LOG_INFO("Attempt at connecting failed, resuming discover...");
  304. esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
  305. }
  306. }
  307. else
  308. {
  309. // not discovered, continue to discover
  310. LOG_INFO("Device discovery failed, continue to discover...");
  311. esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
  312. }
  313. }
  314. else if (param->disc_st_chg.state == ESP_BT_GAP_DISCOVERY_STARTED) {
  315. LOG_INFO("Discovery started.");
  316. }
  317. else
  318. {
  319. LOG_DEBUG("This shouldn't happen. Discovery has only 2 states (for now).");
  320. }
  321. break;
  322. }
  323. case ESP_BT_GAP_RMT_SRVCS_EVT:
  324. LOG_DEBUG_EVENT(ESP_BT_GAP_RMT_SRVCS_EVT);
  325. break;
  326. case ESP_BT_GAP_RMT_SRVC_REC_EVT:
  327. LOG_DEBUG_EVENT(ESP_BT_GAP_RMT_SRVC_REC_EVT);
  328. break;
  329. case ESP_BT_GAP_AUTH_CMPL_EVT: {
  330. if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) {
  331. LOG_INFO("authentication success: %s", param->auth_cmpl.device_name);
  332. //esp_log_buffer_hex(param->auth_cmpl.bda, ESP_BD_ADDR_LEN);
  333. } else {
  334. LOG_ERROR("authentication failed, status:%d", param->auth_cmpl.stat);
  335. }
  336. break;
  337. }
  338. case ESP_BT_GAP_PIN_REQ_EVT: {
  339. LOG_INFO("ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit);
  340. if (param->pin_req.min_16_digit) {
  341. LOG_INFO("Input pin code: 0000 0000 0000 0000");
  342. esp_bt_pin_code_t pin_code = {0};
  343. esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code);
  344. } else {
  345. LOG_INFO("Input pin code: 1234");
  346. esp_bt_pin_code_t pin_code;
  347. pin_code[0] = '1';
  348. pin_code[1] = '2';
  349. pin_code[2] = '3';
  350. pin_code[3] = '4';
  351. esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code);
  352. }
  353. break;
  354. }
  355. #if (CONFIG_BT_SSP_ENABLED == true)
  356. case ESP_BT_GAP_CFM_REQ_EVT:
  357. LOG_INFO("ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %d", param->cfm_req.num_val);
  358. esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true);
  359. break;
  360. case ESP_BT_GAP_KEY_NOTIF_EVT:
  361. LOG_INFO("ESP_BT_GAP_KEY_NOTIF_EVT passkey:%d", param->key_notif.passkey);
  362. break;
  363. LOG_INFO("ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!");
  364. break;
  365. #endif
  366. default: {
  367. LOG_INFO("event: %d", event);
  368. break;
  369. }
  370. }
  371. return;
  372. }
  373. static void bt_av_hdl_stack_evt(uint16_t event, void *p_param)
  374. {
  375. switch (event) {
  376. case BT_APP_EVT_STACK_UP: {
  377. LOG_INFO("BT Stack going up.");
  378. /* set up device name */
  379. char *dev_name = CONFIG_A2DP_DEV_NAME;
  380. esp_bt_dev_set_device_name(dev_name);
  381. LOG_INFO("Preparing to connect to device: %s",CONFIG_A2DP_SINK_NAME);
  382. /* register GAP callback function */
  383. esp_bt_gap_register_callback(bt_app_gap_cb);
  384. /* initialize A2DP source */
  385. esp_a2d_register_callback(&bt_app_a2d_cb);
  386. esp_a2d_source_register_data_callback(bt_app_a2d_data_cb);
  387. esp_a2d_source_init();
  388. /* set discoverable and connectable mode */
  389. esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
  390. /* start device discovery */
  391. LOG_INFO("Starting device discovery...");
  392. s_a2d_state = APP_AV_STATE_DISCOVERING;
  393. esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
  394. /* create and start heart beat timer */
  395. do {
  396. int tmr_id = 0;
  397. s_tmr = xTimerCreate("connTmr", (CONFIG_A2DP_CONTROL_DELAY_MS / portTICK_RATE_MS),
  398. pdTRUE, (void *)tmr_id, a2d_app_heart_beat);
  399. xTimerStart(s_tmr, portMAX_DELAY);
  400. } while (0);
  401. break;
  402. }
  403. default:
  404. LOG_ERROR("%s unhandled evt %d", __func__, event);
  405. break;
  406. }
  407. }
  408. static void bt_app_a2d_cb(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
  409. {
  410. bt_app_work_dispatch(bt_app_av_sm_hdlr, event, param, sizeof(esp_a2d_cb_param_t), NULL);
  411. }
  412. static int32_t bt_app_a2d_data_cb(uint8_t *data, int32_t len)
  413. {
  414. frames_t frames;
  415. static int count = 0;
  416. static unsigned min_o = -1, max_o = 0, min_s = -1, max_s = 0;
  417. unsigned o, s;
  418. if (len < 0 || data == NULL ) {
  419. return 0;
  420. }
  421. // bail out if A2DP isn't connected
  422. LOCK;
  423. // if(s_media_state != APP_AV_MEDIA_STATE_STARTED)
  424. // {
  425. // UNLOCK;
  426. // return 0;
  427. // }
  428. //
  429. ///* Normally, we would want BT to not call us back unless we are not in BUFFERING state.
  430. // That requires BT to not start until we are > OUTPUT_BUFFER
  431. // // come back later, we are buffering (or stopped, need to handle that case ...) but we don't want silence */
  432. // if (output.state == OUTPUT_BUFFER) {
  433. // UNLOCK;
  434. // int32_t silence_bytes = (len >MAX_SILENCE_FRAMES * BYTES_PER_FRAME?MAX_SILENCE_FRAMES * BYTES_PER_FRAME:len;
  435. // memcpy(bt_optr, (u8_t *)silencebuf, silence_bytes);
  436. // return actual_len;
  437. // }
  438. // This is how the BTC layer calculates the number of bytes to
  439. // for us to send. (BTC_SBC_DEC_PCM_DATA_LEN * sizeof(OI_INT16) - availPcmBytes
  440. frames = len / BYTES_PER_FRAME;
  441. output.device_frames = 0;
  442. output.updated = gettime_ms();
  443. output.frames_played_dmp = output.frames_played;
  444. //if (output.threshold < 20) output.threshold = 20;
  445. int ret;
  446. frames_t wanted_frames=len/BYTES_PER_FRAME;
  447. bt_optr = data; // needed for the _write_frames callback
  448. do {
  449. frames = _output_frames(wanted_frames);
  450. wanted_frames -= frames;
  451. } while (wanted_frames > 0 && frames != 0);
  452. if (wanted_frames > 0) {
  453. LOG_DEBUG("need to pad with silence");
  454. memset(bt_optr, 0, wanted_frames * BYTES_PER_FRAME);
  455. }
  456. UNLOCK;
  457. o = _buf_used(outputbuf);
  458. if (o < min_o) min_o = o;
  459. if (o > max_o) max_o = o;
  460. s = _buf_used(streambuf);
  461. if (s < min_s) min_s = s;
  462. if (s > max_s) max_s = s;
  463. if (!(count++ & 0x1ff)) {
  464. LOG_INFO("frames %d (count:%d) (out:%d/%d/%d, stream:%d/%d/%d)", frames, count, max_o, min_o, o, max_s, min_s, s);
  465. min_o = min_s = -1;
  466. max_o = max_s = -0;
  467. }
  468. return frames * BYTES_PER_FRAME;
  469. }
  470. static bool running_test;
  471. bool test_open(const char *device, unsigned rates[], bool userdef_rates) {
  472. // running_test = true;
  473. // while(running_test)
  474. // {
  475. // // wait until BT playback has started
  476. // // this will allow querying the sample rate
  477. // usleep(100000);
  478. // }
  479. memset(rates, 0, MAX_SUPPORTED_SAMPLERATES * sizeof(unsigned));
  480. if (!strcmp(device, "BT")) {
  481. rates[0] = 44100;
  482. } else {
  483. unsigned _rates[] = { 96000, 88200, 48000, 44100, 32000, 0 };
  484. memcpy(rates, _rates, sizeof(_rates));
  485. }
  486. return true;
  487. }
  488. static void a2d_app_heart_beat(void *arg)
  489. {
  490. bt_app_work_dispatch(bt_app_av_sm_hdlr, BT_APP_HEART_BEAT_EVT, NULL, 0, NULL);
  491. }
  492. static void bt_app_av_sm_hdlr(uint16_t event, void *param)
  493. {
  494. //LOG_DEBUG("%s state %s, evt 0x%x, output state: %d", __func__, APP_AV_STATE_DESC[s_a2d_state], event, output.state);
  495. switch (s_a2d_state) {
  496. case APP_AV_STATE_DISCOVERING:
  497. LOG_DEBUG("state %s, evt 0x%x, output state: %d", APP_AV_STATE_DESC[s_a2d_state], event, output.state);
  498. break;
  499. case APP_AV_STATE_DISCOVERED:
  500. LOG_DEBUG("state %s, evt 0x%x, output state: %d", APP_AV_STATE_DESC[s_a2d_state], event, output.state);
  501. break;
  502. case APP_AV_STATE_UNCONNECTED:
  503. bt_app_av_state_unconnected(event, param);
  504. break;
  505. case APP_AV_STATE_CONNECTING:
  506. bt_app_av_state_connecting(event, param);
  507. break;
  508. case APP_AV_STATE_CONNECTED:
  509. bt_app_av_state_connected(event, param);
  510. break;
  511. case APP_AV_STATE_DISCONNECTING:
  512. bt_app_av_state_disconnecting(event, param);
  513. break;
  514. default:
  515. LOG_ERROR("%s invalid state %d", __func__, s_a2d_state);
  516. break;
  517. }
  518. }
  519. static void bt_app_av_state_unconnected(uint16_t event, void *param)
  520. {
  521. switch (event) {
  522. case ESP_A2D_CONNECTION_STATE_EVT:
  523. LOG_DEBUG_EVENT(ESP_A2D_CONNECTION_STATE_EVT);
  524. break;
  525. case ESP_A2D_AUDIO_STATE_EVT:
  526. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_STATE_EVT);
  527. break;
  528. case ESP_A2D_AUDIO_CFG_EVT:
  529. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_CFG_EVT);
  530. break;
  531. case ESP_A2D_MEDIA_CTRL_ACK_EVT:
  532. LOG_DEBUG_EVENT(ESP_A2D_MEDIA_CTRL_ACK_EVT);
  533. break;
  534. case BT_APP_HEART_BEAT_EVT: {
  535. uint8_t *p = s_peer_bda;
  536. LOG_INFO("BT_APP_HEART_BEAT_EVT a2dp connecting to peer: %02x:%02x:%02x:%02x:%02x:%02x",p[0], p[1], p[2], p[3], p[4], p[5]);
  537. switch (esp_bluedroid_get_status()) {
  538. case ESP_BLUEDROID_STATUS_UNINITIALIZED:
  539. LOG_INFO("BlueDroid Status is ESP_BLUEDROID_STATUS_UNINITIALIZED.");
  540. break;
  541. case ESP_BLUEDROID_STATUS_INITIALIZED:
  542. LOG_INFO("BlueDroid Status is ESP_BLUEDROID_STATUS_INITIALIZED.");
  543. break;
  544. case ESP_BLUEDROID_STATUS_ENABLED:
  545. LOG_INFO("BlueDroid Status is ESP_BLUEDROID_STATUS_ENABLED.");
  546. break;
  547. default:
  548. break;
  549. }
  550. if(esp_a2d_source_connect(s_peer_bda)!=ESP_ERR_INVALID_STATE)
  551. {
  552. s_a2d_state = APP_AV_STATE_CONNECTING;
  553. LOG_INFO("a2dp connecting to peer: %s", s_peer_bdname);
  554. A2DP_TIMER_INIT;
  555. }
  556. else
  557. {
  558. // not discovered, continue to discover
  559. LOG_INFO("Attempt at connecting failed, resuming discover...");
  560. esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, 10, 0);
  561. }
  562. break;
  563. }
  564. default:
  565. LOG_ERROR("%s unhandled evt %d", __func__, event);
  566. break;
  567. }
  568. }
  569. static void bt_app_av_state_connecting(uint16_t event, void *param)
  570. {
  571. esp_a2d_cb_param_t *a2d = NULL;
  572. switch (event) {
  573. case ESP_A2D_CONNECTION_STATE_EVT: {
  574. a2d = (esp_a2d_cb_param_t *)(param);
  575. if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED) {
  576. LOG_INFO("a2dp connected! Stopping scan. ");
  577. s_a2d_state = APP_AV_STATE_CONNECTED;
  578. s_media_state = APP_AV_MEDIA_STATE_IDLE;
  579. esp_bt_gap_set_scan_mode(ESP_BT_NON_CONNECTABLE, ESP_BT_NON_DISCOVERABLE);
  580. } else if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
  581. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  582. }
  583. break;
  584. }
  585. case ESP_A2D_AUDIO_STATE_EVT:
  586. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_STATE_EVT);
  587. break;
  588. case ESP_A2D_AUDIO_CFG_EVT:
  589. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_CFG_EVT);
  590. break;
  591. case ESP_A2D_MEDIA_CTRL_ACK_EVT:
  592. LOG_DEBUG_EVENT(ESP_A2D_MEDIA_CTRL_ACK_EVT);
  593. break;
  594. case BT_APP_HEART_BEAT_EVT:
  595. if (IS_A2DP_TIMER_OVER)
  596. {
  597. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  598. LOG_DEBUG("Connect timed out. Setting state to Unconnected. ");
  599. }
  600. LOG_SDEBUG("BT_APP_HEART_BEAT_EVT");
  601. break;
  602. default:
  603. LOG_ERROR("%s unhandled evt %d", __func__, event);
  604. break;
  605. }
  606. }
  607. static void bt_app_av_media_proc(uint16_t event, void *param)
  608. {
  609. esp_a2d_cb_param_t *a2d = NULL;
  610. switch (s_media_state) {
  611. case APP_AV_MEDIA_STATE_IDLE: {
  612. if (event == BT_APP_HEART_BEAT_EVT) {
  613. if(output.state < OUTPUT_STOPPED )
  614. {
  615. // TODO: anything to do while we are waiting? Should we check if we're still connected?
  616. }
  617. else if(output.state >= OUTPUT_BUFFER )
  618. {
  619. LOG_INFO("buffering output, a2dp media ready and connected. Starting checking if ready...");
  620. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
  621. }
  622. // else if(running_test)
  623. // {
  624. // LOG_INFO("buffering output, a2dp media ready and connected. Starting checking if ready...");
  625. //
  626. // esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY);
  627. // }
  628. } else if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
  629. a2d = (esp_a2d_cb_param_t *)(param);
  630. if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY &&
  631. a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS
  632. ) {
  633. LOG_INFO("a2dp media ready, starting media playback ...");
  634. s_media_state = APP_AV_MEDIA_STATE_STARTING;
  635. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_START);
  636. }
  637. }
  638. break;
  639. }
  640. case APP_AV_MEDIA_STATE_STARTING: {
  641. if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
  642. a2d = (esp_a2d_cb_param_t *)(param);
  643. if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_START &&
  644. a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
  645. LOG_INFO("a2dp media started successfully.");
  646. s_intv_cnt = 0;
  647. s_media_state = APP_AV_MEDIA_STATE_STARTED;
  648. } else {
  649. // not started succesfully, transfer to idle state
  650. LOG_INFO("a2dp media start failed.");
  651. s_media_state = APP_AV_MEDIA_STATE_IDLE;
  652. }
  653. }
  654. break;
  655. }
  656. case APP_AV_MEDIA_STATE_STARTED: {
  657. if (event == BT_APP_HEART_BEAT_EVT) {
  658. if(output.state <= OUTPUT_STOPPED) {
  659. LOG_INFO("Output state is stopped. Stopping a2dp media ...");
  660. s_media_state = APP_AV_MEDIA_STATE_STOPPING;
  661. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP);
  662. s_intv_cnt = 0;
  663. }
  664. }
  665. break;
  666. }
  667. case APP_AV_MEDIA_STATE_STOPPING: {
  668. LOG_DEBUG_EVENT(APP_AV_MEDIA_STATE_STOPPING);
  669. if (event == ESP_A2D_MEDIA_CTRL_ACK_EVT) {
  670. a2d = (esp_a2d_cb_param_t *)(param);
  671. if (a2d->media_ctrl_stat.cmd == ESP_A2D_MEDIA_CTRL_STOP &&
  672. a2d->media_ctrl_stat.status == ESP_A2D_MEDIA_CTRL_ACK_SUCCESS) {
  673. LOG_INFO("a2dp media stopped successfully...");
  674. //s_media_state = APP_AV_MEDIA_STATE_WAIT_DISCONNECT;
  675. s_media_state = APP_AV_MEDIA_STATE_IDLE;
  676. // todo: should we disconnect?
  677. // esp_a2d_source_disconnect(s_peer_bda);
  678. // s_a2d_state = APP_AV_STATE_DISCONNECTING;
  679. } else {
  680. LOG_INFO("a2dp media stopping...");
  681. esp_a2d_media_ctrl(ESP_A2D_MEDIA_CTRL_STOP);
  682. }
  683. }
  684. break;
  685. }
  686. }
  687. }
  688. static void bt_app_av_state_connected(uint16_t event, void *param)
  689. {
  690. esp_a2d_cb_param_t *a2d = NULL;
  691. switch (event) {
  692. case ESP_A2D_CONNECTION_STATE_EVT: {
  693. a2d = (esp_a2d_cb_param_t *)(param);
  694. if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
  695. LOG_INFO("a2dp disconnected");
  696. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  697. esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
  698. }
  699. break;
  700. }
  701. case ESP_A2D_AUDIO_STATE_EVT: {
  702. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_STATE_EVT);
  703. a2d = (esp_a2d_cb_param_t *)(param);
  704. if (ESP_A2D_AUDIO_STATE_STARTED == a2d->audio_stat.state) {
  705. s_pkt_cnt = 0;
  706. }
  707. break;
  708. }
  709. case ESP_A2D_AUDIO_CFG_EVT:
  710. // not suppposed to occur for A2DP source
  711. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_CFG_EVT);
  712. break;
  713. case ESP_A2D_MEDIA_CTRL_ACK_EVT:{
  714. LOG_DEBUG_EVENT(ESP_A2D_MEDIA_CTRL_ACK_EVT);
  715. bt_app_av_media_proc(event, param);
  716. break;
  717. }
  718. case BT_APP_HEART_BEAT_EVT: {
  719. LOG_SDEBUG_EVENT(BT_APP_HEART_BEAT_EVT);
  720. bt_app_av_media_proc(event, param);
  721. break;
  722. }
  723. default:
  724. LOG_ERROR("%s unhandled evt %d", __func__, event);
  725. break;
  726. }
  727. }
  728. static void bt_app_av_state_disconnecting(uint16_t event, void *param)
  729. {
  730. esp_a2d_cb_param_t *a2d = NULL;
  731. switch (event) {
  732. case ESP_A2D_CONNECTION_STATE_EVT: {
  733. LOG_DEBUG_EVENT(ESP_A2D_CONNECTION_STATE_EVT);
  734. a2d = (esp_a2d_cb_param_t *)(param);
  735. if (a2d->conn_stat.state == ESP_A2D_CONNECTION_STATE_DISCONNECTED) {
  736. LOG_INFO("a2dp disconnected");
  737. s_a2d_state = APP_AV_STATE_UNCONNECTED;
  738. esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE);
  739. }
  740. break;
  741. }
  742. case ESP_A2D_AUDIO_STATE_EVT:
  743. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_STATE_EVT);
  744. break;
  745. case ESP_A2D_AUDIO_CFG_EVT:
  746. LOG_DEBUG_EVENT(ESP_A2D_AUDIO_CFG_EVT);
  747. break;
  748. case ESP_A2D_MEDIA_CTRL_ACK_EVT:
  749. LOG_DEBUG_EVENT(ESP_A2D_MEDIA_CTRL_ACK_EVT);
  750. break;
  751. case BT_APP_HEART_BEAT_EVT:
  752. LOG_DEBUG_EVENT(BT_APP_HEART_BEAT_EVT);
  753. break;
  754. default:
  755. LOG_ERROR("%s unhandled evt %d", __func__, event);
  756. break;
  757. }
  758. }