audiomicspkpulse.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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, "%s:%d couldn't apr_pcalloc audio context.", __FUNCTION__, __LINE__);
  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, "%s:%d audio init pulse audio failed.", __FUNCTION__, __LINE__);
  327. }
  328. else{
  329. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio init pulse audio success.", __FUNCTION__, __LINE__);
  330. }
  331. *audio_ctx = actx;
  332. return APR_SUCCESS;
  333. }
  334. uint64_t ns_time_monotonic()
  335. {
  336. struct timespec now;
  337. if (clock_gettime(CLOCK_MONOTONIC, &now) != 0)
  338. {
  339. return 0;
  340. }
  341. return ((uint64_t)now.tv_sec * NSEC_PER_SEC + (uint64_t)now.tv_nsec);
  342. }
  343. static void get_latency(pa_stream* s)
  344. {
  345. pa_usec_t l;
  346. int negative;
  347. pa_stream_get_timing_info(s);
  348. if (pa_stream_get_latency(s, &l, &negative) != 0)
  349. {
  350. return;
  351. }
  352. latency = l;
  353. }
  354. static void get_play_latency(pa_stream* s)
  355. {
  356. pa_usec_t l;
  357. int negative;
  358. pa_stream_get_timing_info(s);
  359. if (pa_stream_get_latency(s, &l, &negative) != 0) {
  360. return;
  361. }
  362. play_latency = l;
  363. }
  364. static void stream_write_request_cb(pa_stream* s, size_t length, void* data)
  365. {
  366. audio_context_t* audio_ctx = (audio_context_t*)data;
  367. if (0 == audio_ctx->play_channels || 0 == audio_ctx->play_samprate) {
  368. return;
  369. }
  370. size_t nbytes = 0;
  371. void* audiodata;
  372. while ((nbytes = pa_stream_writable_size(s)) != (size_t)-1)
  373. {
  374. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_writable_size nbytes = %d.", __FUNCTION__, __LINE__, nbytes);
  375. get_play_latency(s);
  376. if (0 == nbytes){
  377. return;
  378. }
  379. /*write to stream*/
  380. if (PA_OK == pa_stream_begin_write(s, &audiodata, &nbytes))
  381. {
  382. //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);
  383. while (audio_ctx->uaudio_len < nbytes)
  384. {
  385. char delaybuffer[RVC_DELAY_AUDIO_LEN] = { 0 };
  386. if (audio_ctx->bstart_get_flag && audio_ctx->micspkpulse_parent && audio_ctx->play_stream_flag) {
  387. audiomicspkpulse_t* audio_micspk = (audiomicspkpulse_t*)audio_ctx->micspkpulse_parent;
  388. if (0 == audio_micspk->ply_buf_cnt) {
  389. int iget = delay_buf_get((delay_buf*)audio_micspk->ply_dbuf, (short*)delaybuffer);
  390. if (0 == iget){
  391. //char audionsbuffer[RVC_DELAY_AUDIO_LEN] = { 0 };
  392. if (NULL != audio_micspk->on_audio_playing) {
  393. audio_micspk->on_audio_playing((void*)delaybuffer, RVC_DELAY_AUDIO_LEN, audio_micspk->user_data);
  394. }
  395. else {
  396. audio_log_v(AUDIO_LOG_LEVEL_DEBUG, "%s:%d on_audio_playing is NULL.", __FUNCTION__, __LINE__);
  397. }
  398. //if (0 == audio_micspk->on_audio_play_ns(audionsbuffer, RVC_DELAY_AUDIO_LEN, delaybuffer, RVC_DELAY_AUDIO_LEN, audio_micspk->user_data)) {
  399. if (audio_ctx->uaudio_len + RVC_DELAY_AUDIO_LEN <= RVC_MAX_AUDIO_BUFFER_LEN) {
  400. memcpy(audio_ctx->paudio_buffer + audio_ctx->uaudio_len, delaybuffer, RVC_DELAY_AUDIO_LEN);
  401. audio_ctx->uaudio_len += RVC_DELAY_AUDIO_LEN;
  402. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio_ctx->uaudio_len = %d.", __FUNCTION__, __LINE__, audio_ctx->uaudio_len);
  403. }
  404. else {
  405. memcpy(audio_ctx->paudio_buffer + audio_ctx->uaudio_len, delaybuffer, RVC_MAX_AUDIO_BUFFER_LEN - audio_ctx->uaudio_len);
  406. audio_ctx->uaudio_len = RVC_MAX_AUDIO_BUFFER_LEN;
  407. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio_ctx->uaudio_len = %d and break.", __FUNCTION__, __LINE__, audio_ctx->uaudio_len);
  408. break;
  409. }
  410. //}
  411. }
  412. }
  413. }
  414. }
  415. int ileft = audio_ctx->uaudio_len - nbytes;
  416. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d ileft = %d.", __FUNCTION__, __LINE__, ileft);
  417. if (ileft >= 0) {
  418. memcpy(audiodata, audio_ctx->paudio_buffer, nbytes);
  419. if (ileft > 0) {
  420. memcpy(audio_ctx->paudio_buffer, audio_ctx->paudio_buffer + nbytes, ileft);
  421. }
  422. audio_ctx->uaudio_len = ileft;
  423. }
  424. else {
  425. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_begin_write nbytes(%d) > max buffer length.", __FUNCTION__, __LINE__, nbytes);
  426. memcpy(audiodata, audio_ctx->paudio_buffer, audio_ctx->uaudio_len);
  427. nbytes = audio_ctx->uaudio_len;
  428. audio_ctx->uaudio_len = 0;
  429. }
  430. if (PA_OK != pa_stream_write(s, audiodata, nbytes, NULL, 0, PA_SEEK_RELATIVE)) {
  431. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_write failed.", __FUNCTION__, __LINE__);
  432. break;
  433. }
  434. //else {
  435. // audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_write(%d) success.", __FUNCTION__, __LINE__, nbytes);
  436. //}
  437. }
  438. else {
  439. 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)));
  440. }
  441. }
  442. }
  443. static void stream_request_cb(pa_stream* s, size_t length, void* data)
  444. {
  445. audio_context_t* audio_ctx = (audio_context_t*)data;
  446. if (0 == audio_ctx->channels || 0 == audio_ctx->samprate){
  447. return;
  448. }
  449. int64_t ts = 0;
  450. while (pa_stream_readable_size(s) > 0){
  451. const void* inputBuffer;
  452. size_t length = 0;
  453. int icount = 0;
  454. bool bhasput = false;
  455. size_t ucopy = 0;
  456. size_t uleft = 0;
  457. /*read from stream*/
  458. if (pa_stream_peek(s, &inputBuffer, &length) < 0){
  459. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: pulse audio pa_stream_peek failed.");
  460. return;
  461. }
  462. //else {
  463. // audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pa_stream_peek audio length is %d.", __FUNCTION__, __LINE__, length);
  464. //}
  465. if (length == 0){
  466. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) empty buffer!");
  467. return; /*buffer is empty*/
  468. }
  469. get_latency(s);
  470. ts = ns_time_monotonic() - (latency * 1000);
  471. if (audio_ctx->last_ts <= 0) {
  472. audio_ctx->last_ts = ts;
  473. }
  474. if (audio_ctx->uaudio_inlen + length <= RVC_MAX_AUDIO_BUFFER_LEN){
  475. memcpy(audio_ctx->paudio_in + audio_ctx->uaudio_inlen, inputBuffer, length);
  476. audio_ctx->uaudio_inlen += length;
  477. }
  478. else{
  479. if (RVC_MAX_AUDIO_BUFFER_LEN >= audio_ctx->uaudio_inlen){
  480. ucopy = RVC_MAX_AUDIO_BUFFER_LEN - audio_ctx->uaudio_inlen;
  481. memcpy(audio_ctx->paudio_in + audio_ctx->uaudio_inlen, inputBuffer, ucopy);
  482. audio_ctx->uaudio_inlen = RVC_MAX_AUDIO_BUFFER_LEN;
  483. uleft = length - ucopy;
  484. }
  485. else{
  486. audio_ctx->uaudio_inlen = 0;
  487. }
  488. }
  489. icount = 0;
  490. while (audio_ctx->uaudio_inlen > RVC_DELAY_AUDIO_LEN) {
  491. if (audio_ctx->bstart_put_flag && audio_ctx->micspkpulse_parent && audio_ctx->stream_flag) {
  492. audiomicspkpulse_t* audio_micspk = audio_ctx->micspkpulse_parent;
  493. char paudions[RVC_DELAY_AUDIO_LEN] = { 0 };
  494. 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)){
  495. delay_buf_put((delay_buf*)audio_micspk->rec_dbuf, paudions);
  496. }
  497. icount++;
  498. audio_ctx->uaudio_inlen -= RVC_DELAY_AUDIO_LEN;
  499. bhasput = true;
  500. }
  501. else{
  502. break;
  503. }
  504. }
  505. if (bhasput && audio_ctx->uaudio_inlen > 0){
  506. if (icount * RVC_DELAY_AUDIO_LEN < RVC_MAX_AUDIO_BUFFER_LEN){
  507. memcpy(audio_ctx->paudio_in, (short*)audio_ctx->paudio_in + icount * RVC_DELAY_AUDIO_LEN / sizeof(short), audio_ctx->uaudio_inlen);
  508. }
  509. }
  510. if (uleft > 0 && audio_ctx->uaudio_inlen >= 0){
  511. if (audio_ctx->uaudio_inlen + uleft <= RVC_MAX_AUDIO_BUFFER_LEN){
  512. memcpy(audio_ctx->paudio_in + audio_ctx->uaudio_inlen, inputBuffer+ ucopy, uleft);
  513. audio_ctx->uaudio_inlen += uleft;
  514. }
  515. }
  516. pa_stream_drop(s); /*clean the samples*/
  517. }
  518. }
  519. void* pulse_read_audio(void* data)
  520. {
  521. audio_context_t* audio_ctx = (audio_context_t*)data;
  522. /*assertions*/
  523. assert(audio_ctx != NULL);
  524. pa_mainloop* pa_ml;
  525. pa_mainloop_api* pa_mlapi;
  526. pa_context* pa_ctx;
  527. pa_buffer_attr bufattr;
  528. pa_sample_spec ss;
  529. pa_stream_flags_t flags = PA_STREAM_NOFLAGS;
  530. int32_t pastream_flag = (int32_t)PA_STREAM_NOFLAGS;
  531. int r;
  532. int pa_ready = 0;
  533. char* dev = NULL;
  534. /* Create a mainloop API and connection to the default server */
  535. pa_ml = pa_mainloop_new();
  536. pa_mlapi = pa_mainloop_get_api(pa_ml);
  537. pa_ctx = pa_context_new(pa_mlapi, "rvc pulse api");
  538. if (pa_context_connect(pa_ctx, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0){
  539. audio_log_v(AUDIO_LOG_LEVEL_INFO,"AUDIO: PULSE - unable to connect to server: pa_context_connect failed");
  540. finish(pa_ctx, pa_ml);
  541. return ((void*)-1);
  542. }
  543. /*
  544. * This function defines a callback so the server will tell us it's state.
  545. * Our callback will wait for the state to be ready. The callback will
  546. * modify the variable to 1 so we know when we have a connection and it's
  547. * ready.
  548. * If there's an error, the callback will set pa_ready to 2
  549. */
  550. pa_context_set_state_callback(pa_ctx, pa_state_cb, &pa_ready);
  551. /*
  552. * This function defines a time event callback (called every TIME_EVENT_USEC)
  553. */
  554. //pa_context_rttime_new(pa_ctx, pa_rtclock_now() + TIME_EVENT_USEC, time_event_callback, NULL);
  555. /*
  556. * We can't do anything until PA is ready, so just iterate the mainloop
  557. * and continue
  558. */
  559. while (pa_ready == 0){
  560. pa_mainloop_iterate(pa_ml, 1, NULL);
  561. }
  562. if (pa_ready == 2){
  563. finish(pa_ctx, pa_ml);
  564. return ((void*)-1);
  565. }
  566. /* set the sample spec (frame rate, channels and format) */
  567. ss.rate = audio_ctx->samprate;
  568. ss.channels = audio_ctx->channels;
  569. ss.format = audio_ctx->eformat; /*for PCM -> PA_SAMPLE_S16LE*/
  570. pa_stream* recordstream = pa_stream_new(pa_ctx, "Record", &ss, NULL);
  571. if (!recordstream){
  572. audio_log_v(AUDIO_LOG_LEVEL_INFO, "pulse audio pa_stream_new failed (chan:%d rate:%d)", ss.channels, ss.rate);
  573. }
  574. /* define the callbacks */
  575. pa_stream_set_read_callback(recordstream, stream_request_cb, (void*)audio_ctx);
  576. // Set properties of the record buffer
  577. pa_zero(bufattr);
  578. /* optimal value for all is (uint32_t)-1 ~= 2 sec */
  579. bufattr.maxlength = (uint32_t)-1;
  580. bufattr.prebuf = (uint32_t)-1;
  581. bufattr.minreq = (uint32_t)-1;
  582. if (audio_ctx->latency > 0) {
  583. bufattr.fragsize = bufattr.tlength = pa_usec_to_bytes((audio_ctx->latency * 1000) * PA_USEC_PER_MSEC, &ss);
  584. pastream_flag |= PA_STREAM_ADJUST_LATENCY;
  585. }
  586. else {
  587. bufattr.fragsize = bufattr.tlength = (uint32_t)-1;
  588. }
  589. pastream_flag |= PA_STREAM_INTERPOLATE_TIMING;
  590. pastream_flag |= PA_STREAM_AUTO_TIMING_UPDATE;
  591. dev = audio_ctx->list_input_devices[audio_ctx->device].name;
  592. audio_log_v(AUDIO_LOG_LEVEL_INFO,"pulse audio connecting to device %s (channels %d rate %d)",dev, ss.channels, ss.rate);
  593. r = pa_stream_connect_record(recordstream, dev, &bufattr, (pa_stream_flags_t)pastream_flag);
  594. if (r < 0){
  595. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) skip latency adjustment");
  596. /*
  597. * Old pulse audio servers don't like the ADJUST_LATENCY flag,
  598. * so retry without that
  599. */
  600. r = pa_stream_connect_record(recordstream, dev, &bufattr, ((int32_t)PA_STREAM_INTERPOLATE_TIMING | (int32_t)PA_STREAM_AUTO_TIMING_UPDATE));
  601. }
  602. if (r < 0){
  603. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) pa_stream_connect_record failed for %d.", pa_context_errno(pa_ctx));
  604. finish(pa_ctx, pa_ml);
  605. return ((void*)-1);
  606. }
  607. get_latency(recordstream);
  608. /*
  609. * Iterate the main loop while streaming. The second argument is whether
  610. * or not the iteration should block until something is ready to be
  611. * done. Set it to zero for non-blocking.
  612. */
  613. while (audio_ctx->stream_flag == AUDIO_STRM_ON){
  614. pa_mainloop_iterate(pa_ml, 1, NULL);
  615. }
  616. usleep(10000);
  617. pa_stream_set_read_callback(recordstream, NULL, NULL);
  618. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: pulse audio stream terminated(%i)", audio_ctx->stream_flag);
  619. pa_stream_disconnect(recordstream);
  620. pa_stream_unref(recordstream);
  621. finish(pa_ctx, pa_ml);
  622. return ((void*)0);
  623. }
  624. int audio_start_pulseaudio(audio_context_t* audio_ctx)
  625. {
  626. /*assertions*/
  627. assert(audio_ctx != NULL);
  628. audio_ctx->stream_flag = AUDIO_STRM_ON;
  629. /* start audio capture thread */
  630. if (pthread_create(&audio_ctx->readthreadid, NULL, pulse_read_audio, (void*)audio_ctx)) {
  631. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) read thread creation failed.");
  632. audio_ctx->stream_flag = AUDIO_STRM_OFF;
  633. return (-1);
  634. }
  635. else {
  636. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) read thread create success, and thread id is %u.", audio_ctx->readthreadid);
  637. }
  638. return 0;
  639. }
  640. static void stream_latency_cb(pa_stream* p, void* userdata)
  641. {
  642. pa_operation* o;
  643. o = pa_stream_update_timing_info(p, NULL, NULL);
  644. pa_operation_unref(o);
  645. }
  646. void* pulse_write_audio(void* data)
  647. {
  648. audio_context_t* audio_ctx = (audio_context_t*)data;
  649. /*assertions*/
  650. assert(audio_ctx != NULL);
  651. pa_mainloop* pa_ml;
  652. pa_mainloop_api* pa_mlapi;
  653. pa_buffer_attr bufattr;
  654. pa_sample_spec ss;
  655. pa_stream_flags_t flags = PA_STREAM_NOFLAGS;
  656. int32_t pastream_flag = (int32_t)PA_STREAM_NOFLAGS;
  657. int r;
  658. int pa_ready = 0;
  659. char* dev = NULL;
  660. /* Create a mainloop API and connection to the default server */
  661. pa_ml = pa_mainloop_new();
  662. pa_mlapi = pa_mainloop_get_api(pa_ml);
  663. pa_context* play_pa_ctx = pa_context_new(pa_mlapi, "rvc play api");
  664. if (PA_OK != pa_context_connect(play_pa_ctx, NULL, PA_CONTEXT_NOFLAGS, NULL)) {
  665. 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));
  666. finish(play_pa_ctx, pa_ml);
  667. return ((void*)-1);
  668. }
  669. /*
  670. * This function defines a callback so the server will tell us it's state.
  671. * Our callback will wait for the state to be ready. The callback will
  672. * modify the variable to 1 so we know when we have a connection and it's
  673. * ready.
  674. * If there's an error, the callback will set pa_ready to 2
  675. */
  676. pa_context_set_state_callback(play_pa_ctx, pa_state_cb, &pa_ready);
  677. /*
  678. * We can't do anything until PA is ready, so just iterate the mainloop
  679. * and continue
  680. */
  681. while (pa_ready == 0) {
  682. pa_mainloop_iterate(pa_ml, 1, NULL);
  683. }
  684. if (pa_ready == 2) {
  685. finish(play_pa_ctx, pa_ml);
  686. return ((void*)-1);
  687. }
  688. /* set the sample spec (frame rate, channels and format) */
  689. ss.rate = audio_ctx->play_samprate;
  690. ss.channels = audio_ctx->play_channels;
  691. ss.format = audio_ctx->play_eformat;
  692. pa_stream* playstream = pa_stream_new(play_pa_ctx, "playStream", &ss, NULL);
  693. if (!playstream) {
  694. 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));
  695. }
  696. audio_log_v(AUDIO_LOG_LEVEL_INFO, "play audio stream state is %d.", pa_stream_get_state(playstream));
  697. /* define the callbacks */
  698. pa_stream_set_write_callback(playstream, stream_write_request_cb, (void*)audio_ctx);
  699. //pa_stream_set_latency_update_callback(playstream, stream_latency_cb, NULL);
  700. // Set properties of the record buffer
  701. pa_zero(bufattr);
  702. /* optimal value for all is (uint32_t)-1 ~= 2 sec */
  703. bufattr.maxlength = (uint32_t)-1;
  704. bufattr.prebuf = (uint32_t)-1;
  705. bufattr.minreq = (uint32_t)-1;
  706. if (audio_ctx->play_latency > 0) {
  707. bufattr.fragsize = bufattr.tlength = pa_usec_to_bytes((audio_ctx->play_latency * 1000) * PA_USEC_PER_MSEC, &ss);
  708. pastream_flag |= PA_STREAM_ADJUST_LATENCY;
  709. }
  710. else{
  711. bufattr.fragsize = bufattr.tlength = (uint32_t)-1;
  712. }
  713. pastream_flag |= PA_STREAM_INTERPOLATE_TIMING;
  714. pastream_flag |= PA_STREAM_AUTO_TIMING_UPDATE;
  715. dev = audio_ctx->list_output_devices[audio_ctx->play_device].name;
  716. 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);
  717. // Connect the stream to a sink
  718. r = pa_stream_connect_playback(playstream, dev, &bufattr, (pa_stream_flags_t)pastream_flag, NULL, NULL);
  719. if (PA_OK != r)
  720. {
  721. audio_log_v(AUDIO_LOG_LEVEL_INFO, "play stream connected failed for %d.", pa_context_errno(play_pa_ctx));
  722. finish(play_pa_ctx, pa_ml);
  723. return ((void*)-1);
  724. }
  725. else {
  726. audio_log_v(AUDIO_LOG_LEVEL_INFO, "play stream connected.");
  727. const pa_sample_spec* spec = pa_stream_get_sample_spec(playstream);
  728. audio_log_v(AUDIO_LOG_LEVEL_INFO, "play stream spec->format = %d, spec->channels = %d, spec->rate = %d.", spec->format, spec->channels, spec->rate);
  729. }
  730. get_play_latency(playstream);
  731. /*
  732. * Iterate the main loop while streaming. The second argument is whether
  733. * or not the iteration should block until something is ready to be
  734. * done. Set it to zero for non-blocking.
  735. */
  736. while (audio_ctx->play_stream_flag == AUDIO_STRM_ON) {
  737. pa_mainloop_iterate(pa_ml, 1, NULL);
  738. }
  739. usleep(10000);
  740. pa_stream_set_write_callback(playstream, NULL, NULL);
  741. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: play audio stream terminated(%i)", audio_ctx->play_stream_flag);
  742. pa_stream_disconnect(playstream);
  743. pa_stream_unref(playstream);
  744. finish(play_pa_ctx, pa_ml);
  745. return ((void*)0);
  746. }
  747. int audio_start_audioplay(audio_context_t* audio_ctx)
  748. {
  749. /*assertions*/
  750. assert(audio_ctx != NULL);
  751. audio_ctx->play_stream_flag = AUDIO_STRM_ON;
  752. /* start audio capture thread */
  753. if (pthread_create(&audio_ctx->writethreadid, NULL, pulse_write_audio, (void*)audio_ctx)) {
  754. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) write thread creation failed.");
  755. audio_ctx->play_stream_flag = AUDIO_STRM_OFF;
  756. return -1;
  757. }
  758. else {
  759. audio_log_v(AUDIO_LOG_LEVEL_INFO, "AUDIO: (pulse audio) write thread create success, and thread id is %u.", audio_ctx->writethreadid);
  760. }
  761. return 0;
  762. }
  763. int audio_stop_playaudio(audio_context_t* audio_ctx)
  764. {
  765. /*assertions*/
  766. assert(audio_ctx != NULL);
  767. if (AUDIO_STRM_ON == audio_ctx->play_stream_flag){
  768. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d set play_stream_flag to off.", __FUNCTION__, __LINE__);
  769. audio_ctx->play_stream_flag = AUDIO_STRM_OFF;
  770. if (0 != audio_ctx->writethreadid) {
  771. if (0 == pthread_join(audio_ctx->writethreadid, NULL)) {
  772. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio write thread %u joined success.", __FUNCTION__, __LINE__, audio_ctx->writethreadid);
  773. audio_ctx->writethreadid = 0;
  774. }
  775. else {
  776. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio write thread joined failed for %s.", __FUNCTION__, __LINE__, strerror(errno));
  777. }
  778. }
  779. }
  780. else {
  781. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio play stream flag is alreay off.", __FUNCTION__, __LINE__);
  782. }
  783. return 0;
  784. }
  785. int audio_stop_pulseaudio(audio_context_t* audio_ctx)
  786. {
  787. /*assertions*/
  788. assert(audio_ctx != NULL);
  789. if (AUDIO_STRM_ON == audio_ctx->stream_flag){
  790. audio_ctx->stream_flag = AUDIO_STRM_OFF;
  791. if (0 != audio_ctx->readthreadid){
  792. if (0 == pthread_join(audio_ctx->readthreadid, NULL)) {
  793. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio read thread %u joined success.", __FUNCTION__, __LINE__, audio_ctx->readthreadid);
  794. audio_ctx->readthreadid = 0;
  795. }
  796. else {
  797. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d pulse audio read thread joined failed for %s.", __FUNCTION__, __LINE__, strerror(errno));
  798. }
  799. }
  800. }
  801. else {
  802. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio read stream flag is alreay off.", __FUNCTION__, __LINE__);
  803. }
  804. return 0;
  805. }
  806. void audio_close_pulseaudio(audio_context_t* audio_ctx)
  807. {
  808. if (audio_ctx == NULL) {
  809. return;
  810. }
  811. if (audio_ctx->play_stream_flag == AUDIO_STRM_ON) {
  812. audio_stop_playaudio(audio_ctx);
  813. }
  814. if (audio_ctx->stream_flag == AUDIO_STRM_ON) {
  815. audio_stop_pulseaudio(audio_ctx);
  816. }
  817. if (NULL != audio_ctx->list_input_devices) {
  818. free(audio_ctx->list_input_devices);
  819. audio_ctx->list_input_devices = NULL;
  820. }
  821. if (NULL != audio_ctx->list_output_devices) {
  822. free(audio_ctx->list_output_devices);
  823. audio_ctx->list_output_devices = NULL;
  824. }
  825. if (NULL != audio_ctx->paudio_buffer){
  826. free(audio_ctx->paudio_buffer);
  827. audio_ctx->paudio_buffer = NULL;
  828. audio_ctx->uaudio_len = 0;
  829. }
  830. if (NULL != audio_ctx->paudio_in) {
  831. free(audio_ctx->paudio_in);
  832. audio_ctx->paudio_in = NULL;
  833. audio_ctx->uaudio_inlen = 0;
  834. }
  835. }
  836. void audio_set_latency(audio_context_t* audio_ctx, double latency)
  837. {
  838. /*assertions*/
  839. assert(audio_ctx != NULL);
  840. audio_ctx->latency = latency;
  841. }
  842. void audio_set_play_latency(audio_context_t* audio_ctx, double latency)
  843. {
  844. /*assertions*/
  845. assert(audio_ctx != NULL);
  846. audio_ctx->play_latency = latency;
  847. }
  848. void audio_set_samprate(audio_context_t* audio_ctx, int samprate)
  849. {
  850. /*assertions*/
  851. assert(audio_ctx != NULL);
  852. audio_ctx->samprate = samprate;
  853. }
  854. void audio_set_play_samprate(audio_context_t* audio_ctx, int samprate)
  855. {
  856. /*assertions*/
  857. assert(audio_ctx != NULL);
  858. audio_ctx->play_samprate = samprate;
  859. }
  860. void audio_set_channels(audio_context_t* audio_ctx, int channels)
  861. {
  862. /*assertions*/
  863. assert(audio_ctx != NULL);
  864. audio_ctx->channels = channels;
  865. }
  866. void audio_set_play_channels(audio_context_t* audio_ctx, int channels)
  867. {
  868. /*assertions*/
  869. assert(audio_ctx != NULL);
  870. audio_ctx->play_channels = channels;
  871. }
  872. void audio_set_capformat(audio_context_t* audio_ctx, pa_sample_format_t eformat)
  873. {
  874. /*assertions*/
  875. assert(audio_ctx != NULL);
  876. audio_ctx->eformat = eformat;
  877. }
  878. void audio_set_playformat(audio_context_t* audio_ctx, pa_sample_format_t eformat)
  879. {
  880. /*assertions*/
  881. assert(audio_ctx != NULL);
  882. audio_ctx->play_eformat = eformat;
  883. }
  884. void audio_set_capdeviceid(audio_context_t* audio_ctx, int ideviceid)
  885. {
  886. /*assertions*/
  887. assert(audio_ctx != NULL);
  888. audio_ctx->device = ideviceid;
  889. }
  890. void audio_set_playdeviceid(audio_context_t* audio_ctx, int ideviceid)
  891. {
  892. /*assertions*/
  893. assert(audio_ctx != NULL);
  894. audio_ctx->play_device = ideviceid;
  895. }
  896. static int initialize_speaker(audiomicspkpulse_t* micspk)
  897. {
  898. int iret = -1;
  899. int ply_dev_id = micspk->ply_dev_id;
  900. if (-1 == ply_dev_id) {
  901. audio_log_v(AUDIO_LOG_LEVEL_ERROR, "audio speaker create error, cannot find output device.");
  902. return APR_EGENERAL;
  903. }
  904. audio_set_playdeviceid(micspk->audio_ctx, ply_dev_id);
  905. //audio_set_play_latency(micspk->audio_ctx, 0.01325);
  906. audio_set_play_latency(micspk->audio_ctx, 0.02);
  907. audio_set_play_samprate(micspk->audio_ctx, 8000);
  908. audio_set_play_channels(micspk->audio_ctx, 1);
  909. audio_set_playformat(micspk->audio_ctx, PA_SAMPLE_S16LE);
  910. if (0 == audio_start_audioplay(micspk->audio_ctx)) {
  911. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio speaker create success, audio output device start play audio success!");
  912. iret = 0;
  913. }
  914. else {
  915. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio speaker create success, audio output device start play audio failed!");
  916. }
  917. return iret;
  918. }
  919. static int initialize_micro(audiomicspkpulse_t* micspk)
  920. {
  921. int iret = -1;
  922. int micro_dev_id = micspk->rec_dev_id;
  923. if (-1 == micro_dev_id) {
  924. audio_log_v(AUDIO_LOG_LEVEL_ERROR, "audio micro create error, cannot find input device.");
  925. return APR_EGENERAL;
  926. }
  927. audio_set_capdeviceid(micspk->audio_ctx, micro_dev_id);
  928. audio_set_latency(micspk->audio_ctx, 0.01);
  929. audio_set_samprate(micspk->audio_ctx, 8000);
  930. audio_set_channels(micspk->audio_ctx, 1);
  931. audio_set_capformat(micspk->audio_ctx, PA_SAMPLE_S16LE);
  932. if (0 == audio_start_pulseaudio(micspk->audio_ctx)) {
  933. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio micro create success, audio input device start pulse audio success!");
  934. iret = 0;
  935. }
  936. else {
  937. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio micro create success, audio input device start pulse audio failed!");
  938. }
  939. return iret;
  940. }
  941. static void uninitialize_speaker(audiomicspkpulse_t* micspk)
  942. {
  943. if (micspk->baudio_device_started_flag) {
  944. if (micspk->audio_ctx) {
  945. audio_stop_playaudio(micspk->audio_ctx);
  946. }
  947. }
  948. if (micspk->ply_dbuf) {
  949. delay_buf_destroy((delay_buf*)micspk->ply_dbuf);
  950. micspk->ply_dbuf = NULL;
  951. }
  952. audio_log_v(AUDIO_LOG_LEVEL_INFO, "uninitialize_speaker success!");
  953. }
  954. static void uninitialize_micro(audiomicspkpulse_t* micspk)
  955. {
  956. if (micspk->baudio_device_started_flag) {
  957. if (micspk->audio_ctx) {
  958. audio_stop_pulseaudio(micspk->audio_ctx);
  959. }
  960. }
  961. if (micspk->rec_dbuf) {
  962. delay_buf_destroy((delay_buf*)micspk->rec_dbuf);
  963. micspk->rec_dbuf = NULL;
  964. }
  965. audio_log_v(AUDIO_LOG_LEVEL_INFO, "uninitialize_micro success!");
  966. }
  967. void* APR_THREAD_FUNC* audiowork_proc(apr_thread_t* threadhandle, void* param)
  968. {
  969. audiomicspkpulse_t* micspk = (audiomicspkpulse_t*)param;
  970. int rc;
  971. //
  972. // record need play because of AEC, so
  973. // record <---> record and play
  974. // play <---> play
  975. // record and play <---> record and play
  976. //
  977. 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");
  978. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d micspk->opt = %d.", __FUNCTION__, __LINE__, micspk->opt);
  979. if (micspk->opt & AMS_OPT_RECPLAY) {
  980. rc = initialize_speaker(micspk);
  981. if (rc != 0) {
  982. micspk->on_audio_device_event(true, -1, false, micspk->dev_type, "recplay mode initialize speaker louder param failed, goto error.", micspk);
  983. goto on_error;
  984. }
  985. else {
  986. micspk->on_audio_device_event(true, 0, false, micspk->dev_type, "recplay mode initialize speaker louder param success!", micspk);
  987. }
  988. usleep(100 * 1000); // play before record
  989. rc = initialize_micro(micspk);
  990. if (0 != rc) {
  991. micspk->on_audio_device_event(true, -1, true, micspk->dev_type, "recplay mode initialize micro capture param failed, goto error.", micspk);
  992. goto on_error;
  993. }
  994. else {
  995. micspk->on_audio_device_event(true, 0, true, micspk->dev_type, "recplay mode initialize micro capture param success!", micspk);
  996. }
  997. }
  998. else if (micspk->opt & AMS_OPT_PLAY) {
  999. rc = initialize_speaker(micspk);
  1000. if (rc != 0) {
  1001. micspk->on_audio_device_event(true, -1, false, micspk->dev_type, "play mode initialize speaker louder param failed, goto error!", micspk);
  1002. goto on_error;
  1003. }
  1004. else {
  1005. micspk->on_audio_device_event(true, 0, false, micspk->dev_type, "play mode initialize speaker louder param success!", micspk);
  1006. }
  1007. }
  1008. else if (micspk->opt & AMS_OPT_RECORD)
  1009. {
  1010. rc = initialize_micro(micspk);
  1011. if (0 != rc) {
  1012. micspk->on_audio_device_event(true, -1, true, micspk->dev_type, "record mode initialize micro capture param failed, goto error!", micspk);
  1013. goto on_error;
  1014. }
  1015. else {
  1016. micspk->on_audio_device_event(true, 0, true, micspk->dev_type, "record mode initialize micro capture param success!", micspk);
  1017. }
  1018. }
  1019. micspk->baudio_device_started_flag = true;
  1020. 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);
  1021. sem_wait(micspk->audio_device_started_sem);
  1022. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d after post audio_device_started_sem.", __FUNCTION__, __LINE__);
  1023. on_error:
  1024. if (micspk->opt & AMS_OPT_RECPLAY) {
  1025. uninitialize_micro(micspk);
  1026. micspk->on_audio_device_event(false, 0, true, micspk->dev_type, "recplay mode uninitialize micro!", micspk);
  1027. uninitialize_speaker(micspk);
  1028. micspk->on_audio_device_event(false, 0, false, micspk->dev_type, "recplay mode uninitialize speaker!", micspk);
  1029. }
  1030. else if (micspk->opt & AMS_OPT_PLAY) {
  1031. uninitialize_speaker(micspk);
  1032. micspk->on_audio_device_event(false, 0, false, micspk->dev_type, "play mode uninitialize speaker!", micspk);
  1033. }
  1034. else if (micspk->opt & AMS_OPT_RECORD){
  1035. uninitialize_micro(micspk);
  1036. micspk->on_audio_device_event(false, 0, true, micspk->dev_type, "record mode uninitialize micro!", micspk);
  1037. }
  1038. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audiowork_proc exit.");
  1039. return 0;
  1040. }
  1041. apr_status_t audiomicspkpulse_create(apr_pool_t* pool,
  1042. audioengine_t* engine,
  1043. int opt,
  1044. int clock,
  1045. const char* rec_dev_key,
  1046. const char* ply_dev_key,
  1047. int idev_type,
  1048. lpfn_audio_device_event lpevent,
  1049. audiomicspkpulse_t** p_micspk)
  1050. {
  1051. audiomicspkpulse_t* micspk;
  1052. unsigned long play_frame_samples;
  1053. unsigned long capture_frame_samples;
  1054. micspk = (audiomicspkpulse_t*)apr_palloc(pool, sizeof(audiomicspkpulse_t));
  1055. memset(micspk, 0, sizeof(audiomicspkpulse_t));
  1056. micspk->audio_device_started_sem = (sem_t*)apr_palloc(pool, sizeof(sem_t));
  1057. if (APR_SUCCESS != audio_context_create(pool, &micspk->audio_ctx)){
  1058. return APR_EGENERAL;
  1059. }
  1060. micspk->rec_dev_id = get_device_id(micspk->audio_ctx, 1, rec_dev_key);
  1061. micspk->ply_dev_id = get_device_id(micspk->audio_ctx, 0, ply_dev_key);
  1062. micspk->on_audio_device_event = lpevent;
  1063. micspk->dev_type = idev_type;
  1064. if (-1 == micspk->rec_dev_id || -1 == micspk->ply_dev_id) {
  1065. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d, get device id failed!", __FUNCTION__, __LINE__);
  1066. return APR_EGENERAL;
  1067. }
  1068. else {
  1069. 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);
  1070. }
  1071. play_frame_samples = FRAME_TIME * clock / 1000;
  1072. capture_frame_samples = FRAME_TIME * CAPTURE_AUDIO_CLOCK / 1000;
  1073. micspk->opt = opt;
  1074. micspk->play_frame_samples = play_frame_samples;
  1075. micspk->capture_frame_samples = capture_frame_samples;
  1076. audiostream_init(engine, &g_stream_vtbl, &micspk->base);
  1077. micspk->base.direction = 0;
  1078. if (opt & AMS_OPT_PLAY) {
  1079. micspk->base.direction |= STREAM_DIR_WRITE;
  1080. delay_buf_create(clock, play_frame_samples, 1, MAX_DELAY, 0, (delay_buf * *)& micspk->ply_dbuf);
  1081. micspk->ply_buf = (short*)apr_palloc(pool, play_frame_samples << 1);
  1082. micspk->ply_buf_cnt = 0;
  1083. }
  1084. if (opt & AMS_OPT_RECORD) {
  1085. micspk->base.direction |= STREAM_DIR_READ;
  1086. delay_buf_create(clock, play_frame_samples, 1, MAX_DELAY, 0, (delay_buf * *)& micspk->rec_dbuf);
  1087. micspk->rec_buf = (short*)apr_palloc(pool, capture_frame_samples << 1);
  1088. micspk->rec_buf_cnt = 0;
  1089. }
  1090. micspk->baudio_device_started_flag = false;
  1091. sem_init(micspk->audio_device_started_sem, 0, 0);
  1092. 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);
  1093. apr_status_t err = apr_thread_create(&micspk->audio_work_thread, NULL, &audiowork_proc, micspk, pool);
  1094. if (APR_SUCCESS == err) {
  1095. bool baudio_work_thread_exit = false;
  1096. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio_work_thread id is %u.", __FUNCTION__, __LINE__, micspk->audio_work_thread);
  1097. do {
  1098. struct timespec ts;
  1099. //int ivalue = -1;
  1100. clock_gettime(CLOCK_REALTIME, &ts);
  1101. long unsec = ts.tv_nsec + (1000 * 1000 * 10);
  1102. ts.tv_sec += (unsec / 1000000000);
  1103. ts.tv_nsec = (unsec % 1000000000);
  1104. //sem_getvalue(micspk->audio_device_started_sem, &ivalue);
  1105. //audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d current sem value is %d.", __FUNCTION__, __LINE__, ivalue);
  1106. if (-1 == sem_timedwait(micspk->audio_device_started_sem, &ts)) {
  1107. if (ETIMEDOUT == errno) {
  1108. if (micspk->baudio_device_started_flag) {
  1109. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio device is already started.", __FUNCTION__, __LINE__);
  1110. break;
  1111. }
  1112. }
  1113. }
  1114. else {
  1115. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d audio device work thread has exit.", __FUNCTION__, __LINE__);
  1116. baudio_work_thread_exit = true;
  1117. }
  1118. } while (!baudio_work_thread_exit);
  1119. if (baudio_work_thread_exit) {
  1120. audiomicspkpulse_destroy(micspk);
  1121. audio_log_v(AUDIO_LOG_LEVEL_INFO, "audio work thread has exit, audiomicspk_destroy success!");
  1122. return APR_EGENERAL;
  1123. }
  1124. }
  1125. else {
  1126. audiomicspkpulse_destroy(micspk);
  1127. audio_log_v(AUDIO_LOG_LEVEL_INFO, "create audio micspk work thread failed, audiomicspk_destroy success!");
  1128. return APR_EGENERAL;
  1129. }
  1130. micspk->audio_ctx->micspkpulse_parent = (void*)micspk;
  1131. micspk->audio_ctx->bstart_put_flag = true;
  1132. micspk->audio_ctx->bstart_get_flag = true;
  1133. *p_micspk = micspk;
  1134. return APR_SUCCESS;
  1135. }
  1136. void audiomicspkpulse_destroy(audiomicspkpulse_t* micspk)
  1137. {
  1138. assert(NULL != micspk);
  1139. if (micspk->audio_ctx){
  1140. audio_close_pulseaudio(micspk->audio_ctx);
  1141. }
  1142. audio_log_v(AUDIO_LOG_LEVEL_INFO, "%s:%d sem post audio_device_started_sem.", __FUNCTION__, __LINE__);
  1143. sem_post(micspk->audio_device_started_sem);
  1144. if (NULL != micspk->audio_work_thread){
  1145. apr_status_t status;
  1146. apr_thread_join(&status, micspk->audio_work_thread);
  1147. micspk->audio_work_thread = NULL;
  1148. }
  1149. if (micspk->ply_dbuf) {
  1150. delay_buf_destroy((delay_buf*)micspk->ply_dbuf);
  1151. micspk->ply_dbuf = NULL;
  1152. }
  1153. if (micspk->rec_dbuf) {
  1154. delay_buf_destroy((delay_buf*)micspk->rec_dbuf);
  1155. micspk->rec_dbuf = NULL;
  1156. }
  1157. if (micspk->opt & AMS_OPT_AS_ENGINE) {
  1158. //DeleteCriticalSection(&micspk->engine_lock);
  1159. }
  1160. sem_destroy(micspk->audio_device_started_sem);
  1161. }