audio.cpp 23 KB

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