audiomicspkpulse.c 42 KB

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