output_bt.c 27 KB

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