audio.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. #include "player.h"
  2. #include "packet.h"
  3. #include "frame.h"
  4. #ifdef _WIN32
  5. #include "Windows.h"
  6. #endif
  7. static void sdl_audio_callback(void *opaque, uint8_t*stream, int len);
  8. // 从packet_queue中取一个packet,解码生成frame
  9. static int audio_decode_frame(AVCodecContext *p_codec_ctx, packet_queue_t *p_pkt_queue, AVFrame *frame, CMediaHostApi* hostapi)
  10. {
  11. int ret = -1;
  12. if (NULL == p_codec_ctx){
  13. return ret;
  14. }
  15. while (0 == p_pkt_queue->abort_flag)
  16. {
  17. AVPacket pkt = {0};
  18. while (0 == p_pkt_queue->abort_flag)
  19. {
  20. // 3.2 一个音频packet含一至多个音频frame,每次avcodec_receive_frame()返回一个frame,此函数返回。
  21. // 下次进来此函数,继续获取一个frame,直到avcodec_receive_frame()返回AVERROR(EAGAIN),
  22. // 表示解码器需要填入新的音频packet
  23. ret = avcodec_receive_frame(p_codec_ctx, frame);
  24. if (ret >= 0)
  25. {
  26. // 时基转换,从d->avctx->pkt_timebase时基转换到1/frame->sample_rate时基
  27. AVRational tb = { 1, frame->sample_rate };
  28. if (frame->pts != AV_NOPTS_VALUE)
  29. {
  30. frame->pts = av_rescale_q(frame->pts, p_codec_ctx->pkt_timebase, tb);
  31. }
  32. else
  33. {
  34. //hostapi->Debug(MEDIA_LOG_DEBUG, "frame->pts no.");
  35. }
  36. return 1;
  37. }
  38. else if (ret == AVERROR_EOF)
  39. {
  40. avcodec_flush_buffers(p_codec_ctx);
  41. return -1;
  42. }
  43. else if (ret == AVERROR(EAGAIN))
  44. {
  45. break;
  46. }
  47. else
  48. {
  49. hostapi->Debug(MEDIA_LOG_DEBUG, "audio avcodec_receive_frame(): other errors.");
  50. continue;
  51. }
  52. }
  53. // 1. 取出一个packet。使用pkt对应的serial赋值给d->pkt_serial
  54. if (packet_queue_get(p_pkt_queue, &pkt, true, hostapi) < 0)
  55. {
  56. return -1;
  57. }
  58. // packet_queue中第一个总是flush_pkt。每次seek操作会插入flush_pkt,更新serial,开启新的播放序列
  59. if (NULL == pkt.data || 0 == pkt.size)
  60. {
  61. // 复位解码器内部状态/刷新内部缓冲区。当seek操作或切换流时应调用此函数。
  62. avcodec_flush_buffers(p_codec_ctx);
  63. return -2;
  64. }
  65. else
  66. {
  67. // 2. 将packet发送给解码器
  68. // 发送packet的顺序是按dts递增的顺序,如IPBBPBB
  69. // pkt.pos变量可以标识当前packet在视频文件中的地址偏移
  70. int iresult = avcodec_send_packet(p_codec_ctx, &pkt);
  71. if (AVERROR(EAGAIN) == iresult)
  72. {
  73. hostapi->Debug(MEDIA_LOG_DEBUG, "receive_frame and send_packet both returned EAGAIN, which is an API violation.");
  74. }
  75. if (0 == iresult)
  76. {
  77. av_packet_unref(&pkt);
  78. }
  79. }
  80. }
  81. return ret;
  82. }
  83. // 音频解码线程:从音频packet_queue中取数据,解码后放入音频frame_queue
  84. static int audio_decode_thread(void *arg)
  85. {
  86. player_stat_t *is = (player_stat_t *)arg;
  87. AVFrame *p_frame = av_frame_alloc();
  88. frame_t *af;
  89. int got_frame = 0;
  90. AVRational tb;
  91. int ret = 0;
  92. if (p_frame == NULL){
  93. return AVERROR(ENOMEM);
  94. }
  95. while (false == is->buser_stop)
  96. {
  97. got_frame = audio_decode_frame(is->m_pacodec_ctx[is->m_iaudio_dec_index], &is->audio_pkt_queue, p_frame, is->rvc_hostapi);
  98. if (got_frame < 0){
  99. if(-2 == got_frame){
  100. if (is->m_icurrent_index > is->m_iaudio_dec_index) {
  101. is->m_iaudio_dec_index++;
  102. }
  103. continue;
  104. }
  105. else {
  106. goto the_end;
  107. }
  108. }
  109. if (got_frame)
  110. {
  111. tb.num = 1;
  112. tb.den = p_frame->sample_rate;
  113. //从frame队列找到一个可写的空间,若未停止则一直等待,已停止时返回NULL
  114. if (!(af = frame_queue_peek_writable(&is->audio_frm_queue))) {
  115. goto the_end;
  116. }
  117. af->pts = (p_frame->pts == AV_NOPTS_VALUE) ? NAN : p_frame->pts * av_q2d(tb);
  118. af->pos = p_frame->pkt_pos;
  119. //-af->serial = is->auddec.pkt_serial;
  120. // 当前帧包含的(单个声道)采样数/采样率就是当前帧的播放时长
  121. AVRational tbdata = { p_frame->nb_samples, p_frame->sample_rate };
  122. //af->duration = av_q2d((AVRational) { p_frame->nb_samples, p_frame->sample_rate });
  123. af->duration = av_q2d(tbdata);
  124. // 将frame数据拷入af->frame,af->frame指向音频frame队列尾部
  125. av_frame_move_ref(af->frame, p_frame);
  126. // 更新音频frame队列大小及写指针
  127. frame_queue_push(&is->audio_frm_queue);
  128. }
  129. }
  130. the_end:
  131. av_frame_free(&p_frame);
  132. is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "audio decode thread exit, thread id is %u, and user stop flag is %s.", SDL_ThreadID(), is->buser_stop ? "true":"false");
  133. is->m_baudio_decode_finished = true;
  134. return ret;
  135. }
  136. int open_audio_stream(player_stat_t *is)
  137. {
  138. AVCodecContext *p_codec_ctx = NULL;
  139. AVCodecParameters *p_codec_par = NULL;
  140. AVCodec* p_codec = NULL;
  141. int ret = -1;
  142. // 1. 为音频流构建解码器AVCodecContext
  143. for (size_t index = 0; index < is->m_uFilesCount; index++){
  144. // 1.1 获取解码器参数AVCodecParameters
  145. p_codec_par = is->m_paudio_stream[index]->codecpar;
  146. // 1.2 获取解码器
  147. p_codec = avcodec_find_decoder(p_codec_par->codec_id);
  148. if (NULL == p_codec) {
  149. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "Cann't find codec!");
  150. return ret;
  151. }
  152. // 1.3 构建解码器AVCodecContext
  153. // 1.3.1 p_codec_ctx初始化:分配结构体,使用p_codec初始化相应成员为默认值
  154. p_codec_ctx = avcodec_alloc_context3(p_codec);
  155. if (p_codec_ctx == NULL) {
  156. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "avcodec_alloc_context3() failed.");
  157. return ret;
  158. }
  159. // 1.3.2 p_codec_ctx初始化:p_codec_par ==> p_codec_ctx,初始化相应成员
  160. ret = avcodec_parameters_to_context(p_codec_ctx, p_codec_par);
  161. if (ret < 0) {
  162. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "avcodec_parameters_to_context() failed %d.", ret);
  163. avcodec_close(p_codec_ctx);
  164. avcodec_free_context(&p_codec_ctx);
  165. return ret;
  166. }
  167. // 1.3.3 p_codec_ctx初始化:使用p_codec初始化p_codec_ctx,初始化完成
  168. ret = avcodec_open2(p_codec_ctx, p_codec, NULL);
  169. if (ret < 0) {
  170. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "avcodec_open2() failed %d.", ret);
  171. avcodec_close(p_codec_ctx);
  172. avcodec_free_context(&p_codec_ctx);
  173. return ret;
  174. }
  175. p_codec_ctx->pkt_timebase = is->m_paudio_stream[index]->time_base;
  176. is->m_pacodec_ctx[index] = p_codec_ctx;
  177. }
  178. // 2. 创建音频解码线程
  179. is->m_audio_decode_tid = SDL_CreateThread(audio_decode_thread, "audio decode thread", is);
  180. if (NULL == is->m_audio_decode_tid) {
  181. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "SDL_Create audio decode thread failed: %s.", SDL_GetError());
  182. return -1;
  183. }
  184. else {
  185. ret = 0;
  186. is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "create %s success, and thread id is %u.", SDL_GetThreadName(is->m_audio_decode_tid), SDL_GetThreadID(is->m_audio_decode_tid));
  187. }
  188. return ret;
  189. }
  190. static int audio_resample(player_stat_t *is, int64_t audio_callback_time)
  191. {
  192. int data_size = 0, resampled_data_size = 0;
  193. int64_t dec_channel_layout = 0;
  194. av_unused double audio_clock0 = 0.0;
  195. int wanted_nb_samples = 0;
  196. frame_t *af = NULL;
  197. while (frame_queue_nb_remaining(&is->audio_frm_queue) == 0){
  198. if ((av_gettime_relative() - audio_callback_time) > 1000000LL * is->audio_hw_buf_size / is->m_audio_param_tgt.bytes_per_sec / 2) {
  199. return -1;
  200. }
  201. av_usleep(1000);
  202. }
  203. // 若队列头部可读,则由af指向可读帧
  204. if (!(af = frame_queue_peek_readable(&is->audio_frm_queue))) {
  205. return -1;
  206. }
  207. frame_queue_next(&is->audio_frm_queue);
  208. // 根据frame中指定的音频参数获取缓冲区的大小
  209. data_size = av_samples_get_buffer_size(NULL, af->frame->channels, // 本行两参数:linesize,声道数
  210. af->frame->nb_samples, // 本行一参数:本帧中包含的单个声道中的样本数
  211. (AVSampleFormat)af->frame->format, 1); // 本行两参数:采样格式,不对齐
  212. // 获取声道布局
  213. dec_channel_layout =
  214. (af->frame->channel_layout && af->frame->channels == av_get_channel_layout_nb_channels(af->frame->channel_layout)) ?
  215. af->frame->channel_layout : av_get_default_channel_layout(af->frame->channels);
  216. wanted_nb_samples = af->frame->nb_samples;
  217. // is->audio_param_tgt是SDL可接受的音频帧数,是audio_open()中取得的参数
  218. // 在audio_open()函数中又有“is->audio_src = is->audio_param_tgt”
  219. // 此处表示:如果frame中的音频参数 == is->audio_src == is->audio_param_tgt,那音频重采样的过程就免了(因此时is->swr_ctr是NULL)
  220. //      否则使用frame(源)和is->audio_param_tgt(目标)中的音频参数来设置is->swr_ctx,并使用frame中的音频参数来赋值is->audio_src
  221. if (af->frame->format != is->m_audio_param_src.fmt ||
  222. dec_channel_layout != is->m_audio_param_src.channel_layout ||
  223. af->frame->sample_rate != is->m_audio_param_src.freq)
  224. {
  225. swr_free(&is->m_paudio_swr_ctx);
  226. // 使用frame(源)和is->audio_param_tgt(目标)中的音频参数来设置is->audio_swr_ctx
  227. is->m_paudio_swr_ctx = swr_alloc_set_opts(NULL,
  228. is->m_audio_param_tgt.channel_layout, (AVSampleFormat)is->m_audio_param_tgt.fmt, is->m_audio_param_tgt.freq,
  229. dec_channel_layout, (AVSampleFormat)af->frame->format, af->frame->sample_rate,
  230. 0, NULL);
  231. if (!is->m_paudio_swr_ctx || swr_init(is->m_paudio_swr_ctx) < 0)
  232. {
  233. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "Cannot create sample rate converter for conversion of %d Hz %s %d channels to %d Hz %s %d channels!",
  234. af->frame->sample_rate, av_get_sample_fmt_name((AVSampleFormat)af->frame->format), af->frame->channels,
  235. is->m_audio_param_tgt.freq, av_get_sample_fmt_name((AVSampleFormat)is->m_audio_param_tgt.fmt), is->m_audio_param_tgt.channels);
  236. swr_free(&is->m_paudio_swr_ctx);
  237. return -1;
  238. }
  239. // 使用frame中的参数更新is->audio_src,第一次更新后后面基本不用执行此if分支了,因为一个音频流中各frame通用参数一样
  240. is->m_audio_param_src.channel_layout = dec_channel_layout;
  241. is->m_audio_param_src.channels = af->frame->channels;
  242. is->m_audio_param_src.freq = af->frame->sample_rate;
  243. is->m_audio_param_src.fmt = (AVSampleFormat)af->frame->format;
  244. }
  245. if (is->m_paudio_swr_ctx)
  246. {
  247. // 重采样输入参数1:输入音频样本数是af->frame->nb_samples
  248. // 重采样输入参数2:输入音频缓冲区
  249. const uint8_t **in = (const uint8_t **)af->frame->extended_data;
  250. // 重采样输出参数1:输出音频缓冲区尺寸
  251. // 重采样输出参数2:输出音频缓冲区
  252. uint8_t **out = &is->m_paudio_frm_rwr;
  253. // 重采样输出参数:输出音频样本数(多加了256个样本)
  254. int out_count = (int64_t)wanted_nb_samples * is->m_audio_param_tgt.freq / af->frame->sample_rate + 256;
  255. // 重采样输出参数:输出音频缓冲区尺寸(以字节为单位)
  256. int out_size = av_samples_get_buffer_size(NULL, is->m_audio_param_tgt.channels, out_count, (AVSampleFormat)is->m_audio_param_tgt.fmt, 0);
  257. int len2 = 0;
  258. if (out_size < 0){
  259. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "av_samples_get_buffer_size() failed.");
  260. return -1;
  261. }
  262. av_fast_malloc(&is->m_paudio_frm_rwr, &is->audio_frm_rwr_size, out_size);
  263. if (!is->m_paudio_frm_rwr) {
  264. return AVERROR(ENOMEM);
  265. }
  266. // 音频重采样:返回值是重采样后得到的音频数据中单个声道的样本数
  267. len2 = swr_convert(is->m_paudio_swr_ctx, out, out_count, in, af->frame->nb_samples);
  268. if (len2 < 0){
  269. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "swr_convert() failed.");
  270. return -1;
  271. }
  272. if (len2 == out_count){
  273. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "audio buffer is probably too small.");
  274. if (swr_init(is->m_paudio_swr_ctx) < 0)
  275. swr_free(&is->m_paudio_swr_ctx);
  276. }
  277. is->m_paudio_frm = is->m_paudio_frm_rwr;
  278. // 重采样返回的一帧音频数据大小(以字节为单位)
  279. resampled_data_size = len2 * is->m_audio_param_tgt.channels * av_get_bytes_per_sample((AVSampleFormat)is->m_audio_param_tgt.fmt);
  280. }
  281. else
  282. {
  283. // 未经重采样,则将指针指向frame中的音频数据
  284. is->m_paudio_frm = af->frame->data[0];
  285. resampled_data_size = data_size;
  286. }
  287. audio_clock0 = is->audio_clock;
  288. /* update the audio clock with the pts */
  289. if (!isnan(af->pts)){
  290. is->audio_clock = af->pts + (double)af->frame->nb_samples / af->frame->sample_rate;
  291. }
  292. else{
  293. is->audio_clock = NAN;
  294. }
  295. is->audio_clock_serial = af->serial;
  296. #ifdef DEBUG
  297. {
  298. static double last_clock;
  299. last_clock = is->audio_clock;
  300. }
  301. #endif
  302. return resampled_data_size;
  303. }
  304. #ifdef _WIN32
  305. static char* Utf8ToGB2312(const char* utf8)
  306. {
  307. int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  308. wchar_t* wstr = new wchar_t[len + 1];
  309. memset(wstr, 0, len + 1);
  310. MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
  311. len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
  312. char* str = new char[len + 1];
  313. memset(str, 0, len + 1);
  314. WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
  315. if (wstr) {
  316. delete []wstr;
  317. wstr = NULL;
  318. }
  319. return str;
  320. }
  321. #endif
  322. static int open_audio_playing(void *arg)
  323. {
  324. player_stat_t *is = (player_stat_t *)arg;
  325. SDL_AudioSpec wanted_spec = {0};
  326. SDL_AudioSpec actual_spec = {0};
  327. wanted_spec.freq = is->m_pacodec_ctx[is->m_iaudio_dec_index]->sample_rate; // 采样率
  328. wanted_spec.format = AUDIO_S16SYS; // S表带符号,16是采样深度,SYS表采用系统字节序
  329. wanted_spec.channels = is->m_pacodec_ctx[is->m_iaudio_dec_index]->channels; // 声音通道数
  330. wanted_spec.silence = 0; // 静音值
  331. // wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE; // SDL声音缓冲区尺寸,单位是单声道采样点尺寸x通道数
  332. // SDL声音缓冲区尺寸,单位是单声道采样点尺寸x声道数
  333. wanted_spec.samples = FFMAX(SDL_AUDIO_MIN_BUFFER_SIZE, 2 << av_log2(wanted_spec.freq / SDL_AUDIO_MAX_CALLBACKS_PER_SEC));
  334. wanted_spec.callback = sdl_audio_callback; // 回调函数,若为NULL,则应使用SDL_QueueAudio()机制
  335. wanted_spec.userdata = is; // 提供给回调函数的参数
  336. if (NULL == is->m_straudiodev) {
  337. int iaudioapeaker = SDL_GetNumAudioDevices(0);
  338. int i = 0;
  339. for (; i < iaudioapeaker; i++) {
  340. #ifdef _WIN32
  341. char* strdevice = Utf8ToGB2312(SDL_GetAudioDeviceName(i, 0));
  342. if (is->m_paudiodev && strstr(strdevice, is->m_paudiodev)) {
  343. const char* strdevname = SDL_GetAudioDeviceName(i, 0);
  344. is->m_straudiodev = av_strdup(strdevname);
  345. delete []strdevice;
  346. break;
  347. }
  348. else {
  349. delete[] strdevice;
  350. #else
  351. if (is->m_paudiodev && strstr(SDL_GetAudioDeviceName(i, 0), is->m_paudiodev)) {
  352. const char* strdevname = SDL_GetAudioDeviceName(i, 0);
  353. is->m_straudiodev = av_strdup(strdevname);
  354. break;
  355. #endif
  356. }
  357. }
  358. if (i == iaudioapeaker) {
  359. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "matched audio device name (%s) failed!", is->m_straudiodev ? is->m_straudiodev : "null");
  360. return -1;
  361. }
  362. }
  363. while (!(is->m_audio_dev = SDL_OpenAudioDevice(is->m_straudiodev, 0, &wanted_spec, &actual_spec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE))){
  364. is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "SDL_OpenAudio (%d channels, %d Hz): %s",wanted_spec.channels, wanted_spec.freq, SDL_GetError());
  365. if (!wanted_spec.channels) {
  366. if (!wanted_spec.freq) {
  367. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR,"No more combinations to try, audio open failed!");
  368. return -1;
  369. }
  370. }
  371. return -1;
  372. }
  373. is->m_audio_param_tgt.fmt = AV_SAMPLE_FMT_S16;
  374. is->m_audio_param_tgt.freq = actual_spec.freq;
  375. is->m_audio_param_tgt.channel_layout = av_get_default_channel_layout(actual_spec.channels);
  376. is->m_audio_param_tgt.channels = actual_spec.channels;
  377. is->m_audio_param_tgt.frame_size = av_samples_get_buffer_size(NULL, actual_spec.channels, 1, (AVSampleFormat)is->m_audio_param_tgt.fmt, 1);
  378. is->m_audio_param_tgt.bytes_per_sec = av_samples_get_buffer_size(NULL, actual_spec.channels, actual_spec.freq, (AVSampleFormat)is->m_audio_param_tgt.fmt, 1);
  379. if (is->m_audio_param_tgt.bytes_per_sec <= 0 || is->m_audio_param_tgt.frame_size <= 0){
  380. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "av_samples_get_buffer_size failed.");
  381. SDL_CloseAudioDevice(is->m_audio_dev);
  382. return -1;
  383. }
  384. is->m_audio_param_src = is->m_audio_param_tgt;
  385. is->audio_hw_buf_size = actual_spec.size; // SDL音频缓冲区大小
  386. is->audio_frm_size = 0;
  387. is->audio_cp_index = 0;
  388. SDL_PauseAudioDevice(is->m_audio_dev, 0);
  389. return 0;
  390. }
  391. // 音频处理回调函数。读队列获取音频包,解码,播放
  392. // 此函数被SDL按需调用,此函数不在用户主线程中,因此数据需要保护
  393. // \param[in] opaque 用户在注册回调函数时指定的参数
  394. // \param[out] stream 音频数据缓冲区地址,将解码后的音频数据填入此缓冲区
  395. // \param[out] len 音频数据缓冲区大小,单位字节
  396. // 回调函数返回后,stream指向的音频缓冲区将变为无效
  397. // 双声道采样点的顺序为LRLRLR
  398. static void sdl_audio_callback(void *opaque, uint8_t*stream, int len)
  399. {
  400. player_stat_t *is = (player_stat_t *)opaque;
  401. int audio_size = 0, len1 = 0;
  402. int64_t audio_callback_time = av_gettime_relative();
  403. while (len > 0 && false == is->buser_stop) // 输入参数len等于is->audio_hw_buf_size,是audio_open()中申请到的SDL音频缓冲区大小
  404. {
  405. if (is->audio_cp_index >= (int)is->audio_frm_size){
  406. // 1. 从音频frame队列中取出一个frame,转换为音频设备支持的格式,返回值是重采样音频帧的大小
  407. audio_size = audio_resample(is, audio_callback_time);
  408. if (audio_size < 0){
  409. if (-1 == audio_size) {
  410. if (is->m_baudio_decode_finished) {
  411. //is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "audio_size is -1 sdl_audio_callback return, and set abort flag to true.");
  412. is->on_audio_play_finished(is->user_data);
  413. //is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "SDL_SemPost m_audio_play_wait_sem.");
  414. SDL_SemPost(is->m_audio_play_wait_sem);
  415. return;
  416. }
  417. }
  418. /* if error, just output silence */
  419. is->m_paudio_frm = NULL;
  420. is->audio_frm_size = SDL_AUDIO_MIN_BUFFER_SIZE / is->m_audio_param_tgt.frame_size * is->m_audio_param_tgt.frame_size;
  421. }
  422. else{
  423. is->audio_frm_size = audio_size;
  424. }
  425. is->audio_cp_index = 0;
  426. }
  427. // 引入is->audio_cp_index的作用:防止一帧音频数据大小超过SDL音频缓冲区大小,这样一帧数据需要经过多次拷贝
  428. // 用is->audio_cp_index标识重采样帧中已拷入SDL音频缓冲区的数据位置索引,len1表示本次拷贝的数据量
  429. len1 = is->audio_frm_size - is->audio_cp_index;
  430. if (len1 > len){
  431. len1 = len;
  432. }
  433. // 2. 将转换后的音频数据拷贝到音频缓冲区stream中,之后的播放就是音频设备驱动程序的工作了
  434. if (is->m_paudio_frm != NULL){
  435. SDL_memset(stream, 0, len1);
  436. int ivolume = is->uVolume;
  437. if (0 == is->on_audio_volume(&ivolume,is->user_data)){
  438. //is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "on_audio_volume success.");
  439. }
  440. //is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "audio uVolume is %d.", ivolume);
  441. //SDL_MixAudio(stream, (uint8_t*)is->p_audio_frm + is->audio_cp_index, len1, ivolume);
  442. SDL_MixAudioFormat(stream, (uint8_t*)is->m_paudio_frm + is->audio_cp_index, AUDIO_S16SYS, len1, ivolume);
  443. //is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "%s:%d SDL_MixAudioFormat audio length is %d.", __FUNCTION__, __LINE__, len1);
  444. if (is->m_prvc_cb && is->m_prvc_cb->cb_playing_audiodata) {
  445. is->m_prvc_cb->cb_playing_audiodata(&(is->m_audio_param_tgt), (uint8_t*)is->m_paudio_frm + is->audio_cp_index, len1, is->m_prvc_cb->user_data);
  446. }
  447. }
  448. else{
  449. SDL_memset(stream, 0, len1);
  450. }
  451. len -= len1;
  452. stream += len1;
  453. is->audio_cp_index += len1;
  454. }
  455. // is->audio_write_buf_size是本帧中尚未拷入SDL音频缓冲区的数据量
  456. is->audio_write_buf_size = is->audio_frm_size - is->audio_cp_index;
  457. //is->rvc_hostapi->Debug("audio_write_buf_size == %d.", is->audio_write_buf_size);
  458. /* Let's assume the audio driver that is used by SDL has two periods. */
  459. // 3. 更新时钟
  460. if (!isnan(is->audio_clock))
  461. {
  462. // 更新音频时钟,更新时刻:每次往声卡缓冲区拷入数据后
  463. // 前面audio_decode_frame中更新的is->audio_clock是以音频帧为单位,所以此处第二个参数要减去未拷贝数据量占用的时间
  464. set_clock_at(&is->audio_clk,
  465. is->audio_clock - (double)(2 * is->audio_hw_buf_size + is->audio_write_buf_size) / is->m_audio_param_tgt.bytes_per_sec,
  466. is->audio_clock_serial,
  467. audio_callback_time / 1000000.0);
  468. }
  469. }
  470. int open_audio(player_stat_t *is)
  471. {
  472. int iret = -1;
  473. if (-1 == is->audio_idx[is->m_icurrent_index]){
  474. is->rvc_hostapi->Debug(MEDIA_LOG_DEBUG, "not find audio stream");
  475. }
  476. else {
  477. if (0 == open_audio_stream(is)) {
  478. iret = open_audio_playing(is);
  479. if (0 != iret) {
  480. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "open audio playing failed");
  481. }
  482. }
  483. else {
  484. is->rvc_hostapi->Debug(MEDIA_LOG_ERROR, "open audio stream failed");
  485. }
  486. }
  487. return iret;
  488. }