audiomicspkpulse.c 41 KB

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