audiomicspkpulse.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. #include "audiomicspkpulse.h"
  2. #include "audiocontext.h"
  3. #include "audiolog.h"
  4. #include "./other/delaybuf.h"
  5. #include <assert.h>
  6. #include <time.h>
  7. #include <semaphore.h>
  8. #include <pthread.h>
  9. #include <unistd.h>
  10. #define MAX_DELAY 60
  11. #define CLOCK_PERIOD 10
  12. #define AUDIO_CLOCK 8000
  13. #define CAPTURE_AUDIO_CLOCK 8000
  14. /*Audio stream flag*/
  15. #define AUDIO_STRM_ON 1
  16. #define AUDIO_STRM_OFF 0
  17. #ifndef RVC_MAX_AUDIO_BUFFER_LEN
  18. #define RVC_MAX_AUDIO_BUFFER_LEN 1024
  19. #endif
  20. #ifndef RVC_PA_ADJUST_LATENCY_PROTOCOL_VERSION
  21. #define RVC_PA_ADJUST_LATENCY_PROTOCOL_VERSION 13
  22. #endif
  23. static uint32_t latency_ms = 10; // requested initial latency in milisec: 0 use max
  24. static pa_usec_t latency = 0; //real latency in usec (for timestamping)
  25. static pa_usec_t play_latency = 0; //real latency in usec (for timestamping)
  26. //pa_stream* recordstream; /* pulse audio stream*/
  27. //pa_context* pa_ctx; /* pulse context*/
  28. //pa_stream* playstream; /* pulse audio stream*/
  29. //pa_context* play_pa_ctx; /* pulse context*/
  30. static apr_status_t read_frame(void* self, audioframe_t* frame)
  31. {
  32. audiomicspkpulse_t* micspk = CONTAINING_RECORD(self, audiomicspkpulse_t, base);
  33. frame->size = 2 * micspk->capture_frame_samples;
  34. frame->dtmf = 0;
  35. delay_buf_get((delay_buf*)micspk->rec_dbuf, (short*)frame->buffer);
  36. return APR_SUCCESS;
  37. }
  38. static apr_status_t write_frame(void* self, const audioframe_t* frame)
  39. {
  40. audiomicspkpulse_t* micspk = CONTAINING_RECORD(self, audiomicspkpulse_t, base);
  41. assert(micspk->play_frame_samples * 2 == frame->size);
  42. delay_buf_put((delay_buf*)micspk->ply_dbuf, (short*)frame->buffer);
  43. return APR_SUCCESS;
  44. }
  45. static audiostream_vtbl_t g_stream_vtbl = {
  46. &read_frame,
  47. &write_frame,
  48. };
  49. static int get_device_id(audio_context_t* audio_ctx, int indev, const char* key)
  50. {
  51. assert(NULL != audio_ctx);
  52. assert(NULL != key);
  53. int iret = -1;
  54. int index = 0;
  55. int device_count = 1;
  56. audio_device_t* audio_device = NULL;
  57. if (1 == indev){
  58. device_count = audio_ctx->num_input_dev;
  59. }
  60. else{
  61. device_count = audio_ctx->num_output_dev;
  62. }
  63. for (index = 0; index < device_count; ++index) {
  64. if (indev) {
  65. audio_device = &audio_ctx->list_input_devices[index];
  66. }
  67. else {
  68. audio_device = &audio_ctx->list_output_devices[index];
  69. }
  70. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio_device(%d) description is %s.", __FUNCTION__, __LINE__, indev, audio_device->description);
  71. if (audio_device->description && strstr(audio_device->description, key)) {
  72. iret = index;
  73. }
  74. }
  75. return iret;
  76. }
  77. static void pa_state_cb(pa_context* c, void* data)
  78. {
  79. pa_context_state_t state;
  80. int* pa_ready = (int*)data;
  81. state = pa_context_get_state(c);
  82. switch (state)
  83. {
  84. // These are just here for reference
  85. case PA_CONTEXT_UNCONNECTED:
  86. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "unconnected");
  87. break;
  88. case PA_CONTEXT_CONNECTING:
  89. case PA_CONTEXT_AUTHORIZING:
  90. case PA_CONTEXT_SETTING_NAME:
  91. default:
  92. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "no state");
  93. break;
  94. case PA_CONTEXT_FAILED:
  95. case PA_CONTEXT_TERMINATED:
  96. *pa_ready = 2;
  97. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "failed");
  98. break;
  99. case PA_CONTEXT_READY:
  100. *pa_ready = 1;
  101. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "ready");
  102. break;
  103. }
  104. }
  105. static void pa_sinklist_cb(pa_context* c, const pa_sink_info* l, int eol, void* userdata)
  106. {
  107. audio_context_t* audio_ctx = (audio_context_t*)userdata;
  108. /*
  109. * If eol is set to a positive number,
  110. * you're at the end of the list
  111. */
  112. if (eol > 0){
  113. return;
  114. }
  115. double flatency = 0.0;
  116. if (flatency <= 0.0)
  117. flatency = (double)latency_ms / 1000;
  118. audio_ctx->num_output_dev++;
  119. /*add device to list*/
  120. audio_ctx->list_output_devices = realloc(audio_ctx->list_output_devices, audio_ctx->num_output_dev * sizeof(audio_device_t));
  121. if (audio_ctx->list_output_devices == NULL){
  122. audio_log_v(AUDIO_LOG_LEVEL_INFO, "memory allocation failure (pa_sinklist_cb): %s", strerror(errno));
  123. exit(-1);
  124. }
  125. /*fill device data*/
  126. audio_ctx->list_output_devices[audio_ctx->num_output_dev - 1].id = l->index; /*saves dev id*/
  127. strncpy(audio_ctx->list_output_devices[audio_ctx->num_output_dev - 1].name, l->name, MAX_PATH_EX-1);
  128. strncpy(audio_ctx->list_output_devices[audio_ctx->num_output_dev - 1].description, l->description, MAX_PATH-1);
  129. audio_ctx->list_output_devices[audio_ctx->num_output_dev - 1].channels = l->channel_map.channels;
  130. audio_ctx->list_output_devices[audio_ctx->num_output_dev - 1].samprate = l->sample_spec.rate;
  131. audio_ctx->list_output_devices[audio_ctx->num_output_dev - 1].low_latency = flatency; /*in seconds*/
  132. audio_ctx->list_output_devices[audio_ctx->num_output_dev - 1].high_latency = flatency; /*in seconds*/
  133. }
  134. static void pa_sourcelist_cb(pa_context* c, const pa_source_info* l, int eol, void* data)
  135. {
  136. audio_context_t* audio_ctx = (audio_context_t*)data;
  137. int channels = 1;
  138. /*
  139. * If eol is set to a positive number,
  140. * you're at the end of the list
  141. */
  142. if (eol > 0) {
  143. return;
  144. }
  145. if (l->sample_spec.channels < 1)
  146. {
  147. channels = 1;
  148. }
  149. else {
  150. channels = l->sample_spec.channels;
  151. }
  152. double ilatency = 0.0;
  153. if (ilatency <= 0.0)
  154. ilatency = (double)latency_ms / 1000;
  155. if (l->monitor_of_sink == PA_INVALID_INDEX)
  156. {
  157. audio_ctx->num_input_dev++;
  158. /*add device to list*/
  159. audio_ctx->list_input_devices = realloc(audio_ctx->list_input_devices, audio_ctx->num_input_dev * sizeof(audio_device_t));
  160. if (audio_ctx->list_input_devices == NULL){
  161. audio_log_v(AUDIO_LOG_LEVEL_INFO, "memory allocation failure (pa_sourcelist_cb): %s", strerror(errno));
  162. exit(-1);
  163. }
  164. /*fill device data*/
  165. audio_ctx->list_input_devices[audio_ctx->num_input_dev - 1].id = l->index; /*saves dev id*/
  166. strncpy(audio_ctx->list_input_devices[audio_ctx->num_input_dev - 1].name, l->name, MAX_PATH_EX-1);
  167. strncpy(audio_ctx->list_input_devices[audio_ctx->num_input_dev - 1].description, l->description, MAX_PATH-1);
  168. audio_ctx->list_input_devices[audio_ctx->num_input_dev - 1].channels = channels;
  169. audio_ctx->list_input_devices[audio_ctx->num_input_dev - 1].samprate = l->sample_spec.rate;
  170. audio_ctx->list_input_devices[audio_ctx->num_input_dev - 1].low_latency = ilatency; /*in seconds*/
  171. audio_ctx->list_input_devices[audio_ctx->num_input_dev - 1].high_latency = ilatency; /*in seconds*/
  172. }
  173. }
  174. void finish(pa_context* rvc_pa_ctx, pa_mainloop* pa_ml)
  175. {
  176. /* clean up and disconnect */
  177. pa_context_disconnect(rvc_pa_ctx);
  178. pa_context_unref(rvc_pa_ctx);
  179. pa_mainloop_free(pa_ml);
  180. }
  181. int pa_get_devicelist(audio_context_t* audio_ctx)
  182. {
  183. /*assertions*/
  184. assert(audio_ctx != NULL);
  185. /* Define our pulse audio loop and connection variables */
  186. pa_mainloop* pa_ml;
  187. pa_mainloop_api* pa_mlapi;
  188. pa_operation* pa_op = NULL;
  189. pa_context* pa_ctx;
  190. /* We'll need these state variables to keep track of our requests */
  191. int state = 0;
  192. int pa_ready = 0;
  193. /* Create a mainloop API and connection to the default server */
  194. pa_ml = pa_mainloop_new();
  195. pa_mlapi = pa_mainloop_get_api(pa_ml);
  196. pa_ctx = pa_context_new(pa_mlapi, "getDevices");
  197. /* This function connects to the pulse server */
  198. if (pa_context_connect(pa_ctx, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0)
  199. {
  200. audio_log_v(AUDIO_LOG_LEVEL_INFO, "unable to connect to server: pa_context_connect failed");
  201. finish(pa_ctx, pa_ml);
  202. return -1;
  203. }
  204. /*
  205. * This function defines a callback so the server will tell us
  206. * it's state.
  207. * Our callback will wait for the state to be ready.
  208. * The callback will modify the variable to 1 so we know when we
  209. * have a connection and it's ready.
  210. * If there's an error, the callback will set pa_ready to 2
  211. */
  212. pa_context_set_state_callback(pa_ctx, pa_state_cb, &pa_ready);
  213. /*
  214. * Now we'll enter into an infinite loop until we get the data
  215. * we receive or if there's an error
  216. */
  217. for (;;)
  218. {
  219. /*
  220. * We can't do anything until PA is ready,
  221. * so just iterate the mainloop and continue
  222. */
  223. if (pa_ready == 0)
  224. {
  225. pa_mainloop_iterate(pa_ml, 1, NULL);
  226. continue;
  227. }
  228. /* We couldn't get a connection to the server, so exit out */
  229. if (pa_ready == 2)
  230. {
  231. finish(pa_ctx, pa_ml);
  232. return -1;
  233. }
  234. /*
  235. * At this point, we're connected to the server and ready
  236. * to make requests
  237. */
  238. switch (state)
  239. {
  240. /* State 0: we haven't done anything yet */
  241. case 0:
  242. /*
  243. * This sends an operation to the server.
  244. * pa_sinklist_cb is our callback function and a pointer
  245. * o our devicelist will be passed to the callback
  246. * (audio_ctx) The operation ID is stored in the
  247. * pa_op variable
  248. */
  249. pa_op = pa_context_get_sink_info_list(
  250. pa_ctx,
  251. pa_sinklist_cb,
  252. (void*)audio_ctx);
  253. /* Update state for next iteration through the loop */
  254. state++;
  255. break;
  256. case 1:
  257. /*
  258. * Now we wait for our operation to complete.
  259. * When it's complete our pa_output_devicelist is
  260. * filled out, and we move along to the next state
  261. */
  262. if (pa_operation_get_state(pa_op) == PA_OPERATION_DONE)
  263. {
  264. pa_operation_unref(pa_op);
  265. /*
  266. * Now we perform another operation to get the
  267. * source(input device) list just like before.
  268. * This time we pass a pointer to our input structure
  269. */
  270. pa_op = pa_context_get_source_info_list(
  271. pa_ctx,
  272. pa_sourcelist_cb,
  273. (void*)audio_ctx);
  274. /* Update the state so we know what to do next */
  275. state++;
  276. }
  277. break;
  278. case 2:
  279. if (pa_operation_get_state(pa_op) == PA_OPERATION_DONE)
  280. {
  281. /*
  282. * Now we're done,
  283. * clean up and disconnect and return
  284. */
  285. pa_operation_unref(pa_op);
  286. finish(pa_ctx, pa_ml);
  287. return 0;
  288. }
  289. break;
  290. default:
  291. /* We should never see this state */
  292. audio_log_v(AUDIO_LOG_LEVEL_INFO, " pulse audio in state %d", state);
  293. return -1;
  294. }
  295. /*
  296. * Iterate the main loop and go again. The second argument is whether
  297. * or not the iteration should block until something is ready to be
  298. * done. Set it to zero for non-blocking.
  299. */
  300. pa_mainloop_iterate(pa_ml, 1, NULL);
  301. }
  302. return 0;
  303. }
  304. int audio_init_pulseaudio(audio_context_t* audio_ctx)
  305. {
  306. /*assertions*/
  307. assert(NULL != audio_ctx);
  308. if (pa_get_devicelist(audio_ctx) < 0){
  309. audio_log_v(AUDIO_LOG_LEVEL_INFO, "pulse audio failed to get audio device list from pulse server.");
  310. return -1;
  311. }
  312. return 0;
  313. }
  314. apr_status_t audio_context_create(apr_pool_t* pool, audio_context_t** audio_ctx)
  315. {
  316. audio_context_t* actx = (audio_context_t*)apr_pcalloc(pool, sizeof(audio_context_t));
  317. if (NULL == actx) {
  318. audio_log_v(AUDIO_LOG_LEVEL_INFO, "couldn't apr_pcalloc audio context.");
  319. return APR_EGENERAL;
  320. }
  321. actx->paudio_buffer = (char*)malloc(RVC_MAX_AUDIO_BUFFER_LEN*sizeof(char));
  322. actx->uaudio_len = 0;
  323. actx->paudio_in = (char*)malloc(RVC_MAX_AUDIO_BUFFER_LEN * sizeof(char));
  324. actx->uaudio_inlen = 0;
  325. if (audio_init_pulseaudio(actx)) {
  326. audio_log_v(AUDIO_LOG_LEVEL_ERROR, "audio init pulse audio failed.");
  327. }
  328. *audio_ctx = actx;
  329. return APR_SUCCESS;
  330. }
  331. uint64_t ns_time_monotonic()
  332. {
  333. struct timespec now;
  334. if (clock_gettime(CLOCK_MONOTONIC, &now) != 0)
  335. {
  336. return 0;
  337. }
  338. return ((uint64_t)now.tv_sec * NSEC_PER_SEC + (uint64_t)now.tv_nsec);
  339. }
  340. static void get_latency(pa_stream* s)
  341. {
  342. pa_usec_t l;
  343. int negative;
  344. pa_stream_get_timing_info(s);
  345. if (pa_stream_get_latency(s, &l, &negative) != 0)
  346. {
  347. return;
  348. }
  349. latency = l;
  350. }
  351. static void get_play_latency(pa_stream* s)
  352. {
  353. pa_usec_t l;
  354. int negative;
  355. pa_stream_get_timing_info(s);
  356. if (pa_stream_get_latency(s, &l, &negative) != 0) {
  357. return;
  358. }
  359. play_latency = l;
  360. }
  361. static void stream_write_request_cb(pa_stream* s, size_t length, void* data)
  362. {
  363. audio_context_t* audio_ctx = (audio_context_t*)data;
  364. if (0 == audio_ctx->play_channels || 0 == audio_ctx->play_samprate) {
  365. return;
  366. }
  367. size_t nbytes = 0;
  368. void* audiodata;
  369. while ((nbytes = pa_stream_writable_size(s)) != (size_t)-1)
  370. {
  371. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_writable_size nbytes = %d.", __FUNCTION__, __LINE__, nbytes);
  372. get_play_latency(s);
  373. if (0 == nbytes){
  374. return;
  375. }
  376. /*write to stream*/
  377. if (PA_OK == pa_stream_begin_write(s, &audiodata, &nbytes))
  378. {
  379. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_begin_write nbytes = %d, audio_ctx->uaudio_len = %d.", __FUNCTION__, __LINE__, nbytes, audio_ctx->uaudio_len);
  380. while (audio_ctx->uaudio_len < nbytes)
  381. {
  382. char delaybuffer[RVC_DELAY_AUDIO_LEN] = { 0 };
  383. if (audio_ctx->bstart_get_flag && audio_ctx->micspkpulse_parent && audio_ctx->play_stream_flag) {
  384. audiomicspkpulse_t* audio_micspk = (audiomicspkpulse_t*)audio_ctx->micspkpulse_parent;
  385. if (0 == audio_micspk->ply_buf_cnt) {
  386. int iget = delay_buf_get((delay_buf*)audio_micspk->ply_dbuf, (short*)delaybuffer);
  387. if (0 == iget){
  388. //char audionsbuffer[RVC_DELAY_AUDIO_LEN] = { 0 };
  389. if (NULL != audio_micspk->on_audio_playing) {
  390. audio_micspk->on_audio_playing((void*)delaybuffer, RVC_DELAY_AUDIO_LEN, audio_micspk->user_data);
  391. }
  392. else {
  393. audio_log_v(AUDIO_LOG_LEVEL_DEBUG, "%s:%d on_audio_playing is NULL.", __FUNCTION__, __LINE__);
  394. }
  395. //if (0 == audio_micspk->on_audio_play_ns(audionsbuffer, RVC_DELAY_AUDIO_LEN, delaybuffer, RVC_DELAY_AUDIO_LEN, audio_micspk->user_data)) {
  396. if (audio_ctx->uaudio_len + RVC_DELAY_AUDIO_LEN <= RVC_MAX_AUDIO_BUFFER_LEN) {
  397. memcpy(audio_ctx->paudio_buffer + audio_ctx->uaudio_len, delaybuffer, RVC_DELAY_AUDIO_LEN);
  398. audio_ctx->uaudio_len += RVC_DELAY_AUDIO_LEN;
  399. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio_ctx->uaudio_len = %d.", __FUNCTION__, __LINE__, audio_ctx->uaudio_len);
  400. }
  401. else {
  402. memcpy(audio_ctx->paudio_buffer + audio_ctx->uaudio_len, delaybuffer, RVC_MAX_AUDIO_BUFFER_LEN - audio_ctx->uaudio_len);
  403. audio_ctx->uaudio_len = RVC_MAX_AUDIO_BUFFER_LEN;
  404. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio_ctx->uaudio_len = %d and break.", __FUNCTION__, __LINE__, audio_ctx->uaudio_len);
  405. break;
  406. }
  407. //}
  408. }
  409. }
  410. }
  411. }
  412. int ileft = audio_ctx->uaudio_len - nbytes;
  413. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d ileft = %d.", __FUNCTION__, __LINE__, ileft);
  414. if (ileft >= 0) {
  415. memcpy(audiodata, audio_ctx->paudio_buffer, nbytes);
  416. if (ileft > 0) {
  417. memcpy(audio_ctx->paudio_buffer, audio_ctx->paudio_buffer + nbytes, ileft);
  418. }
  419. audio_ctx->uaudio_len = ileft;
  420. }
  421. else {
  422. audio_log_v(AUDIO_LOG_LEVEL_INFO, "pa_stream_begin_write nbytes(%d) > max buffer length.", nbytes);
  423. memcpy(audiodata, audio_ctx->paudio_buffer, audio_ctx->uaudio_len);
  424. nbytes = audio_ctx->uaudio_len;
  425. audio_ctx->uaudio_len = 0;
  426. }
  427. if (PA_OK != pa_stream_write(s, audiodata, nbytes, NULL, 0, PA_SEEK_RELATIVE)) {
  428. audio_log_v(AUDIO_LOG_LEVEL_INFO, "pa_stream_write failed.");
  429. break;
  430. }
  431. //else {
  432. // audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_write(%d) success.", __FUNCTION__, __LINE__, nbytes);
  433. //}
  434. }
  435. else {
  436. audio_log_v(AUDIO_LOG_LEVEL_INFO, "pa_stream_begin_write failed for %s.", pa_strerror(pa_context_errno(audio_ctx)));
  437. }
  438. }
  439. }
  440. static void stream_request_cb(pa_stream* s, size_t length, void* data)
  441. {
  442. audio_context_t* audio_ctx = (audio_context_t*)data;
  443. if (0 == audio_ctx->channels || 0 == audio_ctx->samprate){
  444. return;
  445. }
  446. int64_t ts = 0;
  447. while (pa_stream_readable_size(s) > 0){
  448. const void* inputBuffer;
  449. size_t length = 0;
  450. int icount = 0;
  451. bool bhasput = false;
  452. size_t ucopy = 0;
  453. size_t uleft = 0;
  454. /*read from stream*/
  455. if (pa_stream_peek(s, &inputBuffer, &length) < 0){
  456. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: pulse audio pa_stream_peek failed.");
  457. return;
  458. }
  459. //else {
  460. // audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_peek audio length is %d.", __FUNCTION__, __LINE__, length);
  461. //}
  462. if (length == 0){
  463. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) empty buffer!");
  464. return; /*buffer is empty*/
  465. }
  466. get_latency(s);
  467. ts = ns_time_monotonic() - (latency * 1000);
  468. if (audio_ctx->last_ts <= 0) {
  469. audio_ctx->last_ts = ts;
  470. }
  471. if (audio_ctx->uaudio_inlen + length <= RVC_MAX_AUDIO_BUFFER_LEN){
  472. memcpy(audio_ctx->paudio_in + audio_ctx->uaudio_inlen, inputBuffer, length);
  473. audio_ctx->uaudio_inlen += length;
  474. }
  475. else{
  476. if (RVC_MAX_AUDIO_BUFFER_LEN >= audio_ctx->uaudio_inlen){
  477. ucopy = RVC_MAX_AUDIO_BUFFER_LEN - audio_ctx->uaudio_inlen;
  478. memcpy(audio_ctx->paudio_in + audio_ctx->uaudio_inlen, inputBuffer, ucopy);
  479. audio_ctx->uaudio_inlen = RVC_MAX_AUDIO_BUFFER_LEN;
  480. uleft = length - ucopy;
  481. }
  482. else{
  483. audio_ctx->uaudio_inlen = 0;
  484. }
  485. }
  486. icount = 0;
  487. while (audio_ctx->uaudio_inlen > RVC_DELAY_AUDIO_LEN) {
  488. if (audio_ctx->bstart_put_flag && audio_ctx->micspkpulse_parent && audio_ctx->stream_flag) {
  489. audiomicspkpulse_t* audio_micspk = audio_ctx->micspkpulse_parent;
  490. char paudions[RVC_DELAY_AUDIO_LEN] = { 0 };
  491. if (0 == audio_micspk->on_audio_ns(paudions, RVC_DELAY_AUDIO_LEN, (short*)audio_ctx->paudio_in + icount * RVC_DELAY_AUDIO_LEN / sizeof(short), RVC_DELAY_AUDIO_LEN, audio_micspk->user_data)){
  492. delay_buf_put((delay_buf*)audio_micspk->rec_dbuf, paudions);
  493. }
  494. icount++;
  495. audio_ctx->uaudio_inlen -= RVC_DELAY_AUDIO_LEN;
  496. bhasput = true;
  497. }
  498. else{
  499. break;
  500. }
  501. }
  502. if (bhasput && audio_ctx->uaudio_inlen > 0){
  503. if (icount * RVC_DELAY_AUDIO_LEN < RVC_MAX_AUDIO_BUFFER_LEN){
  504. memcpy(audio_ctx->paudio_in, (short*)audio_ctx->paudio_in + icount * RVC_DELAY_AUDIO_LEN / sizeof(short), audio_ctx->uaudio_inlen);
  505. }
  506. }
  507. if (uleft > 0 && audio_ctx->uaudio_inlen >= 0){
  508. if (audio_ctx->uaudio_inlen + uleft <= RVC_MAX_AUDIO_BUFFER_LEN){
  509. memcpy(audio_ctx->paudio_in + audio_ctx->uaudio_inlen, inputBuffer+ ucopy, uleft);
  510. audio_ctx->uaudio_inlen += uleft;
  511. }
  512. }
  513. pa_stream_drop(s); /*clean the samples*/
  514. }
  515. }
  516. void* pulse_read_audio(void* data)
  517. {
  518. audio_context_t* audio_ctx = (audio_context_t*)data;
  519. /*assertions*/
  520. assert(audio_ctx != NULL);
  521. pa_mainloop* pa_ml;
  522. pa_mainloop_api* pa_mlapi;
  523. pa_context* pa_ctx;
  524. pa_buffer_attr bufattr;
  525. pa_sample_spec ss;
  526. pa_stream_flags_t flags = PA_STREAM_NOFLAGS;
  527. int32_t pastream_flag = (int32_t)PA_STREAM_NOFLAGS;
  528. int r;
  529. int pa_ready = 0;
  530. char* dev = NULL;
  531. /* Create a mainloop API and connection to the default server */
  532. pa_ml = pa_mainloop_new();
  533. pa_mlapi = pa_mainloop_get_api(pa_ml);
  534. pa_ctx = pa_context_new(pa_mlapi, "rvc pulse api");
  535. if (pa_context_connect(pa_ctx, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0){
  536. audio_log_v(AUDIO_LOG_LEVEL_INFO,"AUDIO: PULSE - unable to connect to server: pa_context_connect failed");
  537. finish(pa_ctx, pa_ml);
  538. return ((void*)-1);
  539. }
  540. /*
  541. * This function defines a callback so the server will tell us it's state.
  542. * Our callback will wait for the state to be ready. The callback will
  543. * modify the variable to 1 so we know when we have a connection and it's
  544. * ready.
  545. * If there's an error, the callback will set pa_ready to 2
  546. */
  547. pa_context_set_state_callback(pa_ctx, pa_state_cb, &pa_ready);
  548. /*
  549. * This function defines a time event callback (called every TIME_EVENT_USEC)
  550. */
  551. //pa_context_rttime_new(pa_ctx, pa_rtclock_now() + TIME_EVENT_USEC, time_event_callback, NULL);
  552. /*
  553. * We can't do anything until PA is ready, so just iterate the mainloop
  554. * and continue
  555. */
  556. while (pa_ready == 0){
  557. pa_mainloop_iterate(pa_ml, 1, NULL);
  558. }
  559. if (pa_ready == 2){
  560. finish(pa_ctx, pa_ml);
  561. return ((void*)-1);
  562. }
  563. /* set the sample spec (frame rate, channels and format) */
  564. ss.rate = audio_ctx->samprate;
  565. ss.channels = audio_ctx->channels;
  566. ss.format = audio_ctx->eformat; /*for PCM -> PA_SAMPLE_S16LE*/
  567. pa_stream* recordstream = pa_stream_new(pa_ctx, "Record", &ss, NULL);
  568. if (!recordstream){
  569. audio_log_v(AUDIO_LOG_LEVEL_INFO, "pulse audio pa_stream_new failed (chan:%d rate:%d)", ss.channels, ss.rate);
  570. }
  571. /* define the callbacks */
  572. pa_stream_set_read_callback(recordstream, stream_request_cb, (void*)audio_ctx);
  573. // Set properties of the record buffer
  574. pa_zero(bufattr);
  575. /* optimal value for all is (uint32_t)-1 ~= 2 sec */
  576. bufattr.maxlength = (uint32_t)-1;
  577. bufattr.prebuf = (uint32_t)-1;
  578. bufattr.minreq = (uint32_t)-1;
  579. if (audio_ctx->latency > 0) {
  580. bufattr.fragsize = bufattr.tlength = pa_usec_to_bytes((audio_ctx->latency * 1000) * PA_USEC_PER_MSEC, &ss);
  581. pastream_flag |= PA_STREAM_ADJUST_LATENCY;
  582. }
  583. else {
  584. bufattr.fragsize = bufattr.tlength = (uint32_t)-1;
  585. }
  586. pastream_flag |= PA_STREAM_INTERPOLATE_TIMING;
  587. pastream_flag |= PA_STREAM_AUTO_TIMING_UPDATE;
  588. dev = audio_ctx->list_input_devices[audio_ctx->device].name;
  589. //audio_log_v(AUDIO_LOG_LEVEL_INFO,"pulse audio connecting to device %s (channels %d rate %d)",dev, ss.channels, ss.rate);
  590. r = pa_stream_connect_record(recordstream, dev, &bufattr, (pa_stream_flags_t)pastream_flag);
  591. if (r < 0){
  592. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) skip latency adjustment");
  593. /*
  594. * Old pulse audio servers don't like the ADJUST_LATENCY flag,
  595. * so retry without that
  596. */
  597. r = pa_stream_connect_record(recordstream, dev, &bufattr, ((int32_t)PA_STREAM_INTERPOLATE_TIMING | (int32_t)PA_STREAM_AUTO_TIMING_UPDATE));
  598. }
  599. if (r < 0){
  600. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) pa_stream_connect_record failed for %d.", pa_context_errno(pa_ctx));
  601. finish(pa_ctx, pa_ml);
  602. return ((void*)-1);
  603. }
  604. get_latency(recordstream);
  605. /*
  606. * Iterate the main loop while streaming. The second argument is whether
  607. * or not the iteration should block until something is ready to be
  608. * done. Set it to zero for non-blocking.
  609. */
  610. while (audio_ctx->stream_flag == AUDIO_STRM_ON){
  611. pa_mainloop_iterate(pa_ml, 1, NULL);
  612. }
  613. usleep(10000);
  614. pa_stream_set_read_callback(recordstream, NULL, NULL);
  615. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: pulse audio stream terminated(%i)", audio_ctx->stream_flag);
  616. pa_stream_disconnect(recordstream);
  617. pa_stream_unref(recordstream);
  618. finish(pa_ctx, pa_ml);
  619. return ((void*)0);
  620. }
  621. int audio_start_pulseaudio(audio_context_t* audio_ctx)
  622. {
  623. /*assertions*/
  624. assert(audio_ctx != NULL);
  625. audio_ctx->stream_flag = AUDIO_STRM_ON;
  626. /* start audio capture thread */
  627. if (pthread_create(&audio_ctx->readthreadid, NULL, pulse_read_audio, (void*)audio_ctx)) {
  628. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) read thread creation failed.");
  629. audio_ctx->stream_flag = AUDIO_STRM_OFF;
  630. return (-1);
  631. }
  632. return 0;
  633. }
  634. static void stream_latency_cb(pa_stream* p, void* userdata)
  635. {
  636. pa_operation* o;
  637. o = pa_stream_update_timing_info(p, NULL, NULL);
  638. pa_operation_unref(o);
  639. }
  640. void* pulse_write_audio(void* data)
  641. {
  642. audio_context_t* audio_ctx = (audio_context_t*)data;
  643. /*assertions*/
  644. assert(audio_ctx != NULL);
  645. pa_mainloop* pa_ml;
  646. pa_mainloop_api* pa_mlapi;
  647. pa_buffer_attr bufattr;
  648. pa_sample_spec ss;
  649. pa_stream_flags_t flags = PA_STREAM_NOFLAGS;
  650. int32_t pastream_flag = (int32_t)PA_STREAM_NOFLAGS;
  651. int r;
  652. int pa_ready = 0;
  653. char* dev = NULL;
  654. /* Create a mainloop API and connection to the default server */
  655. pa_ml = pa_mainloop_new();
  656. pa_mlapi = pa_mainloop_get_api(pa_ml);
  657. pa_context* play_pa_ctx = pa_context_new(pa_mlapi, "rvc play api");
  658. if (PA_OK != pa_context_connect(play_pa_ctx, NULL, PA_CONTEXT_NOFLAGS, NULL)) {
  659. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: PULSE - unable to connect to server: pa_context_connect failed for %d.", pa_context_errno(play_pa_ctx));
  660. finish(play_pa_ctx, pa_ml);
  661. return ((void*)-1);
  662. }
  663. /*
  664. * This function defines a callback so the server will tell us it's state.
  665. * Our callback will wait for the state to be ready. The callback will
  666. * modify the variable to 1 so we know when we have a connection and it's
  667. * ready.
  668. * If there's an error, the callback will set pa_ready to 2
  669. */
  670. pa_context_set_state_callback(play_pa_ctx, pa_state_cb, &pa_ready);
  671. /*
  672. * We can't do anything until PA is ready, so just iterate the mainloop
  673. * and continue
  674. */
  675. while (pa_ready == 0) {
  676. pa_mainloop_iterate(pa_ml, 1, NULL);
  677. }
  678. if (pa_ready == 2) {
  679. finish(play_pa_ctx, pa_ml);
  680. return ((void*)-1);
  681. }
  682. /* set the sample spec (frame rate, channels and format) */
  683. ss.rate = audio_ctx->play_samprate;
  684. ss.channels = audio_ctx->play_channels;
  685. ss.format = audio_ctx->play_eformat;
  686. pa_stream* playstream = pa_stream_new(play_pa_ctx, "playStream", &ss, NULL);
  687. if (!playstream) {
  688. audio_log_v(AUDIO_LOG_LEVEL_INFO, "play audio pa_stream_new failed (chan:%d rate:%d) for %d.", ss.channels, ss.rate, pa_context_errno(play_pa_ctx));
  689. }
  690. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "play audio stream state is %d.", pa_stream_get_state(playstream));
  691. /* define the callbacks */
  692. pa_stream_set_write_callback(playstream, stream_write_request_cb, (void*)audio_ctx);
  693. //pa_stream_set_latency_update_callback(playstream, stream_latency_cb, NULL);
  694. // Set properties of the record buffer
  695. pa_zero(bufattr);
  696. /* optimal value for all is (uint32_t)-1 ~= 2 sec */
  697. bufattr.maxlength = (uint32_t)-1;
  698. bufattr.prebuf = (uint32_t)-1;
  699. bufattr.minreq = (uint32_t)-1;
  700. if (audio_ctx->play_latency > 0) {
  701. bufattr.fragsize = bufattr.tlength = pa_usec_to_bytes((audio_ctx->play_latency * 1000) * PA_USEC_PER_MSEC, &ss);
  702. pastream_flag |= PA_STREAM_ADJUST_LATENCY;
  703. }
  704. else{
  705. bufattr.fragsize = bufattr.tlength = (uint32_t)-1;
  706. }
  707. pastream_flag |= PA_STREAM_INTERPOLATE_TIMING;
  708. pastream_flag |= PA_STREAM_AUTO_TIMING_UPDATE;
  709. dev = audio_ctx->list_output_devices[audio_ctx->play_device].name;
  710. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "play audio connecting to device %s (channels %d rate %d buf frag size %d buf length %d)", dev, ss.channels, ss.rate, bufattr.fragsize, bufattr.tlength);
  711. // Connect the stream to a sink
  712. r = pa_stream_connect_playback(playstream, dev, &bufattr, (pa_stream_flags_t)pastream_flag, NULL, NULL);
  713. if (PA_OK != r){
  714. audio_log_v(AUDIO_LOG_LEVEL_INFO, "play stream connected failed for %d.", pa_context_errno(play_pa_ctx));
  715. finish(play_pa_ctx, pa_ml);
  716. return ((void*)-1);
  717. }
  718. else {
  719. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "play stream connected.");
  720. const pa_sample_spec* spec = pa_stream_get_sample_spec(playstream);
  721. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "play stream spec->format = %d, spec->channels = %d, spec->rate = %d.", spec->format, spec->channels, spec->rate);
  722. }
  723. get_play_latency(playstream);
  724. /*
  725. * Iterate the main loop while streaming. The second argument is whether
  726. * or not the iteration should block until something is ready to be
  727. * done. Set it to zero for non-blocking.
  728. */
  729. while (audio_ctx->play_stream_flag == AUDIO_STRM_ON) {
  730. pa_mainloop_iterate(pa_ml, 1, NULL);
  731. }
  732. usleep(10000);
  733. pa_stream_set_write_callback(playstream, NULL, NULL);
  734. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: play audio stream terminated(%i)", audio_ctx->play_stream_flag);
  735. pa_stream_disconnect(playstream);
  736. pa_stream_unref(playstream);
  737. finish(play_pa_ctx, pa_ml);
  738. return ((void*)0);
  739. }
  740. int audio_start_audioplay(audio_context_t* audio_ctx)
  741. {
  742. /*assertions*/
  743. assert(audio_ctx != NULL);
  744. audio_ctx->play_stream_flag = AUDIO_STRM_ON;
  745. /* start audio capture thread */
  746. if (pthread_create(&audio_ctx->writethreadid, NULL, pulse_write_audio, (void*)audio_ctx)) {
  747. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) write thread creation failed.");
  748. audio_ctx->play_stream_flag = AUDIO_STRM_OFF;
  749. return -1;
  750. }
  751. return 0;
  752. }
  753. int audio_stop_playaudio(audio_context_t* audio_ctx)
  754. {
  755. /*assertions*/
  756. assert(audio_ctx != NULL);
  757. if (AUDIO_STRM_ON == audio_ctx->play_stream_flag){
  758. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d set play_stream_flag to off.", __FUNCTION__, __LINE__);
  759. audio_ctx->play_stream_flag = AUDIO_STRM_OFF;
  760. if (0 != audio_ctx->writethreadid) {
  761. if (0 == pthread_join(audio_ctx->writethreadid, NULL)) {
  762. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio write thread %u joined success.", __FUNCTION__, __LINE__, audio_ctx->writethreadid);
  763. audio_ctx->writethreadid = 0;
  764. }
  765. else {
  766. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio write thread joined failed for %s.", __FUNCTION__, __LINE__, strerror(errno));
  767. }
  768. }
  769. }
  770. return 0;
  771. }
  772. int audio_stop_pulseaudio(audio_context_t* audio_ctx)
  773. {
  774. /*assertions*/
  775. assert(audio_ctx != NULL);
  776. if (AUDIO_STRM_ON == audio_ctx->stream_flag){
  777. audio_ctx->stream_flag = AUDIO_STRM_OFF;
  778. if (0 != audio_ctx->readthreadid){
  779. if (0 == pthread_join(audio_ctx->readthreadid, NULL)) {
  780. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio read thread %u joined success.", __FUNCTION__, __LINE__, audio_ctx->readthreadid);
  781. audio_ctx->readthreadid = 0;
  782. }
  783. else {
  784. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio read thread joined failed for %s.", __FUNCTION__, __LINE__, strerror(errno));
  785. }
  786. }
  787. }
  788. return 0;
  789. }
  790. void audio_close_pulseaudio(audio_context_t* audio_ctx)
  791. {
  792. if (audio_ctx == NULL) {
  793. return;
  794. }
  795. if (audio_ctx->play_stream_flag == AUDIO_STRM_ON) {
  796. audio_stop_playaudio(audio_ctx);
  797. }
  798. if (audio_ctx->stream_flag == AUDIO_STRM_ON) {
  799. audio_stop_pulseaudio(audio_ctx);
  800. }
  801. if (NULL != audio_ctx->list_input_devices) {
  802. free(audio_ctx->list_input_devices);
  803. audio_ctx->list_input_devices = NULL;
  804. }
  805. if (NULL != audio_ctx->list_output_devices) {
  806. free(audio_ctx->list_output_devices);
  807. audio_ctx->list_output_devices = NULL;
  808. }
  809. if (NULL != audio_ctx->paudio_buffer){
  810. free(audio_ctx->paudio_buffer);
  811. audio_ctx->paudio_buffer = NULL;
  812. audio_ctx->uaudio_len = 0;
  813. }
  814. if (NULL != audio_ctx->paudio_in) {
  815. free(audio_ctx->paudio_in);
  816. audio_ctx->paudio_in = NULL;
  817. audio_ctx->uaudio_inlen = 0;
  818. }
  819. }
  820. void audio_set_latency(audio_context_t* audio_ctx, double latency)
  821. {
  822. /*assertions*/
  823. assert(audio_ctx != NULL);
  824. audio_ctx->latency = latency;
  825. }
  826. void audio_set_play_latency(audio_context_t* audio_ctx, double latency)
  827. {
  828. /*assertions*/
  829. assert(audio_ctx != NULL);
  830. audio_ctx->play_latency = latency;
  831. }
  832. void audio_set_samprate(audio_context_t* audio_ctx, int samprate)
  833. {
  834. /*assertions*/
  835. assert(audio_ctx != NULL);
  836. audio_ctx->samprate = samprate;
  837. }
  838. void audio_set_play_samprate(audio_context_t* audio_ctx, int samprate)
  839. {
  840. /*assertions*/
  841. assert(audio_ctx != NULL);
  842. audio_ctx->play_samprate = samprate;
  843. }
  844. void audio_set_channels(audio_context_t* audio_ctx, int channels)
  845. {
  846. /*assertions*/
  847. assert(audio_ctx != NULL);
  848. audio_ctx->channels = channels;
  849. }
  850. void audio_set_play_channels(audio_context_t* audio_ctx, int channels)
  851. {
  852. /*assertions*/
  853. assert(audio_ctx != NULL);
  854. audio_ctx->play_channels = channels;
  855. }
  856. void audio_set_capformat(audio_context_t* audio_ctx, pa_sample_format_t eformat)
  857. {
  858. /*assertions*/
  859. assert(audio_ctx != NULL);
  860. audio_ctx->eformat = eformat;
  861. }
  862. void audio_set_playformat(audio_context_t* audio_ctx, pa_sample_format_t eformat)
  863. {
  864. /*assertions*/
  865. assert(audio_ctx != NULL);
  866. audio_ctx->play_eformat = eformat;
  867. }
  868. void audio_set_capdeviceid(audio_context_t* audio_ctx, int ideviceid)
  869. {
  870. /*assertions*/
  871. assert(audio_ctx != NULL);
  872. audio_ctx->device = ideviceid;
  873. }
  874. void audio_set_playdeviceid(audio_context_t* audio_ctx, int ideviceid)
  875. {
  876. /*assertions*/
  877. assert(audio_ctx != NULL);
  878. audio_ctx->play_device = ideviceid;
  879. }
  880. static int initialize_speaker(audiomicspkpulse_t* micspk)
  881. {
  882. int iret = -1;
  883. int ply_dev_id = micspk->ply_dev_id;
  884. if (-1 == ply_dev_id) {
  885. audio_log_v(AUDIO_LOG_LEVEL_ERROR, "audio speaker create error, cannot find output device.");
  886. return APR_EGENERAL;
  887. }
  888. audio_set_playdeviceid(micspk->audio_ctx, ply_dev_id);
  889. //audio_set_play_latency(micspk->audio_ctx, 0.01325);
  890. audio_set_play_latency(micspk->audio_ctx, 0.02);
  891. audio_set_play_samprate(micspk->audio_ctx, 8000);
  892. audio_set_play_channels(micspk->audio_ctx, 1);
  893. audio_set_playformat(micspk->audio_ctx, PA_SAMPLE_S16LE);
  894. if (0 == audio_start_audioplay(micspk->audio_ctx)) {
  895. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio speaker create success, audio output device start play audio success!");
  896. iret = 0;
  897. }
  898. else {
  899. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio speaker create success, audio output device start play audio failed!");
  900. }
  901. return iret;
  902. }
  903. static int initialize_micro(audiomicspkpulse_t* micspk)
  904. {
  905. int iret = -1;
  906. int micro_dev_id = micspk->rec_dev_id;
  907. if (-1 == micro_dev_id) {
  908. audio_log_v(AUDIO_LOG_LEVEL_ERROR, "audio micro create error, cannot find input device.");
  909. return APR_EGENERAL;
  910. }
  911. audio_set_capdeviceid(micspk->audio_ctx, micro_dev_id);
  912. audio_set_latency(micspk->audio_ctx, 0.01);
  913. audio_set_samprate(micspk->audio_ctx, 8000);
  914. audio_set_channels(micspk->audio_ctx, 1);
  915. audio_set_capformat(micspk->audio_ctx, PA_SAMPLE_S16LE);
  916. if (0 == audio_start_pulseaudio(micspk->audio_ctx)) {
  917. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio micro create success, audio input device start pulse audio success!");
  918. iret = 0;
  919. }
  920. else {
  921. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio micro create success, audio input device start pulse audio failed!");
  922. }
  923. return iret;
  924. }
  925. static void uninitialize_speaker(audiomicspkpulse_t* micspk)
  926. {
  927. if (micspk->baudio_device_started_flag) {
  928. if (micspk->audio_ctx) {
  929. audio_stop_playaudio(micspk->audio_ctx);
  930. }
  931. }
  932. if (micspk->ply_dbuf) {
  933. delay_buf_destroy((delay_buf*)micspk->ply_dbuf);
  934. micspk->ply_dbuf = NULL;
  935. }
  936. }
  937. static void uninitialize_micro(audiomicspkpulse_t* micspk)
  938. {
  939. if (micspk->baudio_device_started_flag) {
  940. if (micspk->audio_ctx) {
  941. audio_stop_pulseaudio(micspk->audio_ctx);
  942. }
  943. }
  944. if (micspk->rec_dbuf) {
  945. delay_buf_destroy((delay_buf*)micspk->rec_dbuf);
  946. micspk->rec_dbuf = NULL;
  947. }
  948. }
  949. void* APR_THREAD_FUNC* audiowork_proc(apr_thread_t* threadhandle, void* param)
  950. {
  951. audiomicspkpulse_t* micspk = (audiomicspkpulse_t*)param;
  952. int rc;
  953. //
  954. // record need play because of AEC, so
  955. // record <---> record and play
  956. // play <---> play
  957. // record and play <---> record and play
  958. //
  959. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d micspk addr is 0x%08x, current sem addr is 0x%08x.started flag is %s.", __FUNCTION__, __LINE__, param, micspk->audio_device_started_sem, micspk->baudio_device_started_flag ? "true" : "false");
  960. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d micspk->opt = %d.", __FUNCTION__, __LINE__, micspk->opt);
  961. if (micspk->opt & AMS_OPT_RECPLAY) {
  962. rc = initialize_speaker(micspk);
  963. if (rc != 0) {
  964. micspk->on_audio_device_event(true, -1, false, micspk->dev_type, "recplay mode initialize speaker louder param failed, goto error.", micspk);
  965. goto on_error;
  966. }
  967. //else {
  968. // micspk->on_audio_device_event(true, 0, false, micspk->dev_type, "recplay mode initialize speaker louder param success!", micspk);
  969. //}
  970. usleep(100 * 1000); // play before record
  971. rc = initialize_micro(micspk);
  972. if (0 != rc) {
  973. micspk->on_audio_device_event(true, -1, true, micspk->dev_type, "recplay mode initialize micro capture param failed, goto error.", micspk);
  974. goto on_error;
  975. }
  976. //else {
  977. // micspk->on_audio_device_event(true, 0, true, micspk->dev_type, "recplay mode initialize micro capture param success!", micspk);
  978. //}
  979. }
  980. else if (micspk->opt & AMS_OPT_PLAY) {
  981. rc = initialize_speaker(micspk);
  982. if (rc != 0) {
  983. micspk->on_audio_device_event(true, -1, false, micspk->dev_type, "play mode initialize speaker louder param failed, goto error!", micspk);
  984. goto on_error;
  985. }
  986. //else {
  987. // micspk->on_audio_device_event(true, 0, false, micspk->dev_type, "play mode initialize speaker louder param success!", micspk);
  988. //}
  989. }
  990. else if (micspk->opt & AMS_OPT_RECORD)
  991. {
  992. rc = initialize_micro(micspk);
  993. if (0 != rc) {
  994. micspk->on_audio_device_event(true, -1, true, micspk->dev_type, "record mode initialize micro capture param failed, goto error!", micspk);
  995. goto on_error;
  996. }
  997. //else {
  998. // micspk->on_audio_device_event(true, 0, true, micspk->dev_type, "record mode initialize micro capture param success!", micspk);
  999. //}
  1000. }
  1001. micspk->baudio_device_started_flag = true;
  1002. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d micspk addr is 0x%08x, current sem addr is 0x%08x.", __FUNCTION__, __LINE__, micspk, micspk->audio_device_started_sem);
  1003. sem_wait(micspk->audio_device_started_sem);
  1004. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d after post audio_device_started_sem.", __FUNCTION__, __LINE__);
  1005. on_error:
  1006. if (micspk->opt & AMS_OPT_RECPLAY) {
  1007. uninitialize_micro(micspk);
  1008. //micspk->on_audio_device_event(false, 0, true, micspk->dev_type, "recplay mode uninitialize micro!", micspk);
  1009. uninitialize_speaker(micspk);
  1010. //micspk->on_audio_device_event(false, 0, false, micspk->dev_type, "recplay mode uninitialize speaker!", micspk);
  1011. }
  1012. else if (micspk->opt & AMS_OPT_PLAY) {
  1013. uninitialize_speaker(micspk);
  1014. //micspk->on_audio_device_event(false, 0, false, micspk->dev_type, "play mode uninitialize speaker!", micspk);
  1015. }
  1016. else if (micspk->opt & AMS_OPT_RECORD){
  1017. uninitialize_micro(micspk);
  1018. //micspk->on_audio_device_event(false, 0, true, micspk->dev_type, "record mode uninitialize micro!", micspk);
  1019. }
  1020. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "audiowork_proc exit.");
  1021. return 0;
  1022. }
  1023. apr_status_t audiomicspkpulse_create(apr_pool_t* pool,
  1024. audioengine_t* engine,
  1025. int opt,
  1026. int clock,
  1027. const char* rec_dev_key,
  1028. const char* ply_dev_key,
  1029. int idev_type,
  1030. lpfn_audio_device_event lpevent,
  1031. audiomicspkpulse_t** p_micspk)
  1032. {
  1033. audiomicspkpulse_t* micspk;
  1034. unsigned long play_frame_samples;
  1035. unsigned long capture_frame_samples;
  1036. micspk = (audiomicspkpulse_t*)apr_palloc(pool, sizeof(audiomicspkpulse_t));
  1037. memset(micspk, 0, sizeof(audiomicspkpulse_t));
  1038. micspk->audio_device_started_sem = (sem_t*)apr_palloc(pool, sizeof(sem_t));
  1039. if (APR_SUCCESS != audio_context_create(pool, &micspk->audio_ctx)){
  1040. return APR_EGENERAL;
  1041. }
  1042. micspk->rec_dev_id = get_device_id(micspk->audio_ctx, 1, rec_dev_key);
  1043. micspk->ply_dev_id = get_device_id(micspk->audio_ctx, 0, ply_dev_key);
  1044. micspk->on_audio_device_event = lpevent;
  1045. micspk->dev_type = idev_type;
  1046. if (-1 == micspk->rec_dev_id || -1 == micspk->ply_dev_id) {
  1047. audio_log_v(AUDIO_LOG_LEVEL_INFO, "get device id failed!");
  1048. return APR_EGENERAL;
  1049. }
  1050. play_frame_samples = FRAME_TIME * clock / 1000;
  1051. capture_frame_samples = FRAME_TIME * CAPTURE_AUDIO_CLOCK / 1000;
  1052. micspk->opt = opt;
  1053. micspk->play_frame_samples = play_frame_samples;
  1054. micspk->capture_frame_samples = capture_frame_samples;
  1055. audiostream_init(engine, &g_stream_vtbl, &micspk->base);
  1056. micspk->base.direction = 0;
  1057. if (opt & AMS_OPT_PLAY) {
  1058. micspk->base.direction |= STREAM_DIR_WRITE;
  1059. delay_buf_create(clock, play_frame_samples, 1, MAX_DELAY, 0, (delay_buf * *)& micspk->ply_dbuf);
  1060. micspk->ply_buf = (short*)apr_palloc(pool, play_frame_samples << 1);
  1061. micspk->ply_buf_cnt = 0;
  1062. }
  1063. if (opt & AMS_OPT_RECORD) {
  1064. micspk->base.direction |= STREAM_DIR_READ;
  1065. delay_buf_create(clock, play_frame_samples, 1, MAX_DELAY, 0, (delay_buf * *)& micspk->rec_dbuf);
  1066. micspk->rec_buf = (short*)apr_palloc(pool, capture_frame_samples << 1);
  1067. micspk->rec_buf_cnt = 0;
  1068. }
  1069. micspk->baudio_device_started_flag = false;
  1070. sem_init(micspk->audio_device_started_sem, 0, 0);
  1071. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d micspk addr is 0x%08x, current sem addr is 0x%08x.", __FUNCTION__, __LINE__, micspk, micspk->audio_device_started_sem);
  1072. apr_status_t err = apr_thread_create(&micspk->audio_work_thread, NULL, &audiowork_proc, micspk, pool);
  1073. if (APR_SUCCESS == err) {
  1074. bool baudio_work_thread_exit = false;
  1075. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio_work_thread id is %u.", __FUNCTION__, __LINE__, micspk->audio_work_thread);
  1076. do {
  1077. struct timespec ts;
  1078. //int ivalue = -1;
  1079. clock_gettime(CLOCK_REALTIME, &ts);
  1080. long unsec = ts.tv_nsec + (1000 * 1000 * 10);
  1081. ts.tv_sec += (unsec / 1000000000);
  1082. ts.tv_nsec = (unsec % 1000000000);
  1083. //sem_getvalue(micspk->audio_device_started_sem, &ivalue);
  1084. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d current sem value is %d.", __FUNCTION__, __LINE__, ivalue);
  1085. if (-1 == sem_timedwait(micspk->audio_device_started_sem, &ts)) {
  1086. if (ETIMEDOUT == errno) {
  1087. if (micspk->baudio_device_started_flag) {
  1088. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio device is already started.", __FUNCTION__, __LINE__);
  1089. break;
  1090. }
  1091. }
  1092. }
  1093. else {
  1094. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio device work thread has exit.", __FUNCTION__, __LINE__);
  1095. baudio_work_thread_exit = true;
  1096. }
  1097. } while (!baudio_work_thread_exit);
  1098. if (baudio_work_thread_exit) {
  1099. audiomicspkpulse_destroy(micspk);
  1100. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio work thread has exit, audiomicspk_destroy success!");
  1101. return APR_EGENERAL;
  1102. }
  1103. }
  1104. else {
  1105. audiomicspkpulse_destroy(micspk);
  1106. audio_log_v(AUDIO_LOG_LEVEL_INFO, "create audio micspk work thread failed, audiomicspk_destroy success!");
  1107. return APR_EGENERAL;
  1108. }
  1109. micspk->audio_ctx->micspkpulse_parent = (void*)micspk;
  1110. micspk->audio_ctx->bstart_put_flag = true;
  1111. micspk->audio_ctx->bstart_get_flag = true;
  1112. *p_micspk = micspk;
  1113. return APR_SUCCESS;
  1114. }
  1115. void audiomicspkpulse_destroy(audiomicspkpulse_t* micspk)
  1116. {
  1117. assert(NULL != micspk);
  1118. if (micspk->audio_ctx){
  1119. audio_close_pulseaudio(micspk->audio_ctx);
  1120. }
  1121. sem_post(micspk->audio_device_started_sem);
  1122. if (NULL != micspk->audio_work_thread){
  1123. apr_status_t status;
  1124. apr_thread_join(&status, micspk->audio_work_thread);
  1125. micspk->audio_work_thread = NULL;
  1126. }
  1127. if (micspk->ply_dbuf) {
  1128. delay_buf_destroy((delay_buf*)micspk->ply_dbuf);
  1129. micspk->ply_dbuf = NULL;
  1130. }
  1131. if (micspk->rec_dbuf) {
  1132. delay_buf_destroy((delay_buf*)micspk->rec_dbuf);
  1133. micspk->rec_dbuf = NULL;
  1134. }
  1135. if (micspk->opt & AMS_OPT_AS_ENGINE) {
  1136. //DeleteCriticalSection(&micspk->engine_lock);
  1137. }
  1138. sem_destroy(micspk->audio_device_started_sem);
  1139. }