当前位置:   article > 正文

FFmpeg 自定义IO CONTEXT实现音频解码,以及seek函数_ffmpeg hls自定义io

ffmpeg hls自定义io

 对于从音频流buffer中解码的场景中,我们需要实现自己的io context 去从buffer中解码,参考ffmepg官方实例:doc/examples/avio_reading.c

关于是否要实现avio context中的seek函数,需要看需要解码什么格式,大部分格式不需要seek,但是有些格式需要,比如apple开发的ALAC格式,这个格式的音频有的时候它的头文件moov信息是在文件的结尾,这就很坑,一般都是在开头,所以在获取音频的时候需要先seek到文件的结尾,获取moov的信息,然后再seek回来继续解析格式并解码。

关于moov格式的坑:【开发笔记】终于,我们解决了iOS播放器的一个Bug... - 哔哩哔哩

如果你不想实现seek,有没有办法直接把音频文件的moov信息从结尾提到开头呢?也是有的

ffmpeg -i ./old.mp4 -movflags faststart -c copy new.mp4

通过这个命令转换后再去解码,文件信息就在开头,就可以不用seek了。

可以通过以下命令去查看头文件信息:

ffprobe -v trace filename

直接贴代码:

  1. #include <libavcodec/avcodec.h>
  2. #include <libavformat/avformat.h>
  3. #include <libavformat/avio.h>
  4. #include <libavutil/file.h>
  5. #include <libavutil/frame.h>
  6. #include <libavutil/mem.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #define BUF_SIZE 20480
  11. FILE *in_file = NULL;
  12. struct buffer_data {
  13. uint8_t *ptr;
  14. uint8_t *ori_ptr; // for seek file stream
  15. size_t size; ///< size left in the buffer
  16. size_t file_size; ///< size of the file to decode
  17. };
  18. static char *av_get_err(int errnum) {
  19. static char err_buf[128] = {0};
  20. av_strerror(errnum, err_buf, 128);
  21. return err_buf;
  22. }
  23. static void print_sample_format(const AVFrame *frame) {
  24. printf("ar-samplerate: %uHz\n", frame->sample_rate);
  25. printf("ac-channel: %u\n", frame->channels);
  26. printf("f-format: %u\n",
  27. frame->format); // 格式需要注意,实际存储到本地文件时已经改成交错模式
  28. }
  29. /*
  30. int read_size;
  31. static int read_packet(void *opaque, uint8_t *buf, int buf_size) {
  32. // FILE *in_file = (FILE *)opaque;
  33. read_size = fread(buf, 1, buf_size, in_file);
  34. printf("read_packet read_size:%d, buf_size:%d\n", read_size, buf_size);
  35. if (read_size <= 0) {
  36. return AVERROR_EOF; // 数据读取完毕
  37. }
  38. return read_size;
  39. }
  40. */
  41. static int read_packet(void *opaque, uint8_t *buf, int buf_size) {
  42. struct buffer_data *bd = (struct buffer_data *)opaque;
  43. buf_size = FFMIN(buf_size, bd->size);
  44. if (!buf_size) return AVERROR_EOF;
  45. // printf("ptr:%p size:%zu buf_size: %d\n", bd->ptr, bd->size, buf_size);
  46. /* copy internal buffer data to buf */
  47. memcpy(buf, bd->ptr, buf_size);
  48. bd->ptr += buf_size;
  49. bd->size -= buf_size;
  50. return buf_size;
  51. }
  52. // for some format like ALAC (apple format) , which moov partten is located at
  53. // the end of file so we need to implement seek function during demux to seek to
  54. // the end of file for paring the moov info and then seek back to the front
  55. static int64_t seek_packet(void *opaque, int64_t offset, int whence) {
  56. // FILE *in_file = (FILE *)opaque;
  57. struct buffer_data *bd = (struct buffer_data *)opaque;
  58. int64_t ret = -1;
  59. printf("whence=%d , offset=%lld \n", whence, offset);
  60. switch (whence) {
  61. case AVSEEK_SIZE:
  62. printf("AVSEEK_SIZE \n");
  63. ret = bd->file_size;
  64. break;
  65. case SEEK_SET:
  66. printf("SEEK_SET \n");
  67. bd->ptr = bd->ori_ptr + offset;
  68. bd->size = bd->file_size - offset;
  69. ret = bd->ptr;
  70. break;
  71. case SEEK_CUR:
  72. printf("SEEK_cur \n");
  73. break;
  74. case SEEK_END:
  75. printf("SEEK_end \n");
  76. break;
  77. }
  78. return ret;
  79. }
  80. static void decode(AVCodecContext *dec_ctx, AVPacket *packet, AVFrame *frame,
  81. FILE *outfile) {
  82. int ret = 0;
  83. ret = avcodec_send_packet(dec_ctx, packet);
  84. if (ret == AVERROR(EAGAIN)) {
  85. printf(
  86. "Receive_frame and send_packet both returned EAGAIN, which is an API "
  87. "violation.\n");
  88. } else if (ret < 0) {
  89. printf("Error submitting the packet to the decoder, err:%s\n",
  90. av_get_err(ret));
  91. return;
  92. }
  93. while (ret >= 0) {
  94. ret = avcodec_receive_frame(dec_ctx, frame);
  95. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  96. return;
  97. } else if (ret < 0) {
  98. printf("Error during decoding\n");
  99. exit(1);
  100. }
  101. if (!packet) {
  102. printf("get flush frame\n");
  103. }
  104. int out_sample_bytes = av_get_bytes_per_sample(dec_ctx->sample_fmt);
  105. int out_sample_is_plannar = av_sample_fmt_is_planar(dec_ctx->sample_fmt);
  106. // printf("debug %d is out_sample_is_plannar : %d \n", __LINE__,
  107. // out_sample_is_plannar);
  108. // print_sample_format(frame);
  109. if (out_sample_bytes < 0) {
  110. /* This should not occur, checking just for paranoia */
  111. fprintf(stderr, "Failed to calculate data size\n");
  112. exit(1);
  113. }
  114. // printf("debug %d out_sample_bytes: %d samples: %d ch:%d\n", __LINE__,
  115. // out_sample_bytes, frame->nb_samples,
  116. // dec_ctx->ch_layout.nb_channels);
  117. if (out_sample_is_plannar) { // plannar frames
  118. /**
  119. P表示Planar(平面),其数据格式排列方式为 :
  120. LLLLLLRRRRRRLLLLLLRRRRRRLLLLLLRRRRRRL...(每个LLLLLLRRRRRR为一个音频帧)
  121. 而不带P的数据格式(即交错排列)排列方式为:
  122. LRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRLRL...(每个LR为一个音频样本)
  123. 播放范例: ffplay -ar 48000 -ac 2 -f f32le believe.pcm
  124. 并不是每一种都是这样的格式
  125. */
  126. // 这里的写法不是通用,通用要调用重采样的函数去实现
  127. // 这里只是针对解码出来是planar格式的转换
  128. for (int i = 0; i < frame->nb_samples; i++) {
  129. for (int ch = 0; ch < frame->channels; ch++) {
  130. // for(int ch = 0; ch < 1; ch++) {
  131. fwrite(frame->data[ch] + out_sample_bytes * i, 1, out_sample_bytes,
  132. outfile);
  133. }
  134. }
  135. } else // packed frame
  136. fwrite(frame->data[0],
  137. frame->nb_samples * out_sample_bytes * frame->channels, 1,
  138. outfile);
  139. }
  140. }
  141. int main(int argc, char **argv) {
  142. if (argc != 3) {
  143. printf("usage: %s <intput file> <out file>\n", argv[0]);
  144. return -1;
  145. }
  146. av_log_set_level(AV_LOG_TRACE);
  147. const char *in_file_name = argv[1];
  148. const char *out_file_name = argv[2];
  149. // FILE *in_file = NULL;
  150. FILE *out_file = NULL;
  151. // 1. 打开参数文件
  152. in_file = fopen(in_file_name, "rb");
  153. if (!in_file) {
  154. printf("open file %s failed\n", in_file_name);
  155. return -1;
  156. }
  157. out_file = fopen(out_file_name, "wb+");
  158. if (!out_file) {
  159. printf("open file %s failed\n", out_file_name);
  160. return -1;
  161. }
  162. struct buffer_data bd = {0};
  163. uint8_t *buffer = NULL;
  164. size_t buffer_size;
  165. int ret = av_file_map(in_file_name, &buffer, &buffer_size, 0, NULL);
  166. printf("file size: %d\n", buffer_size);
  167. bd.ptr = buffer;
  168. bd.ori_ptr = buffer;
  169. bd.file_size = buffer_size;
  170. bd.size = buffer_size;
  171. // AVInputFormat* in_fmt = av_find_input_format("flac");
  172. // 2自定义 io
  173. uint8_t *io_buffer = av_malloc(BUF_SIZE);
  174. // AVIOContext *avio_ctx = avio_alloc_context(io_buffer, BUF_SIZE, 0, (void
  175. // *)in_file,
  176. AVIOContext *avio_ctx = avio_alloc_context(io_buffer, BUF_SIZE, 0, &bd,
  177. read_packet, NULL, seek_packet);
  178. // avio_alloc_context(io_buffer, BUF_SIZE, 0, &bd, read_packet, NULL, NULL);
  179. AVFormatContext *format_ctx = avformat_alloc_context();
  180. format_ctx->pb = avio_ctx;
  181. format_ctx->flags = AVFMT_FLAG_CUSTOM_IO;
  182. // int ret = avformat_open_input(&format_ctx, NULL, in_fmt, NULL);
  183. // 从输入源读取封装格式文件头
  184. ret = avformat_open_input(&format_ctx, NULL, NULL, NULL);
  185. if (ret < 0) {
  186. printf("avformat_open_input failed:%s\n", av_err2str(ret));
  187. return -1;
  188. }
  189. // 从输入源读取一段数据,尝试解码,以获取流信息
  190. if ((ret = avformat_find_stream_info(format_ctx, NULL)) < 0) {
  191. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  192. return ret;
  193. }
  194. av_dump_format(format_ctx, 0, NULL, 0);
  195. int audioStreamIndex =
  196. av_find_best_stream(format_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, NULL, 0);
  197. AVStream *st = format_ctx->streams[audioStreamIndex];
  198. // 编码器查找
  199. // AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_ALAC);
  200. // set codec id from famat params
  201. AVCodec *codec = avcodec_find_decoder(st->codecpar->codec_id);
  202. if (!codec) {
  203. printf("avcodec_find_decoder failed\n");
  204. return -1;
  205. }
  206. AVCodecContext *codec_ctx = avcodec_alloc_context3(codec);
  207. if (!codec_ctx) {
  208. printf("avcodec_alloc_context3 failed\n");
  209. return -1;
  210. }
  211. // copy params from format to codec
  212. ret = avcodec_parameters_to_context(
  213. codec_ctx, format_ctx->streams[audioStreamIndex]->codecpar);
  214. if (ret < 0) {
  215. printf("Failed to copy in_stream codecpar to codec context\n");
  216. }
  217. ret = avcodec_open2(codec_ctx, codec, NULL);
  218. if (ret < 0) {
  219. printf("avcodec_open2 failed:%s\n", av_err2str(ret));
  220. return -1;
  221. }
  222. printf("%d debug codec_ctx->sample_rate: %d\n", __LINE__,
  223. codec_ctx->sample_rate);
  224. AVPacket *packet = av_packet_alloc();
  225. AVFrame *frame = av_frame_alloc();
  226. while (1) {
  227. ret = av_read_frame(format_ctx, packet);
  228. if (ret < 0) {
  229. printf("av_read_frame failed:%s\n", av_err2str(ret));
  230. break;
  231. }
  232. decode(codec_ctx, packet, frame, out_file);
  233. }
  234. printf("read file finish\n");
  235. decode(codec_ctx, NULL, frame, out_file);
  236. fclose(in_file);
  237. fclose(out_file);
  238. av_frame_free(frame);
  239. av_packet_free(packet);
  240. avformat_close_input(&format_ctx);
  241. avcodec_free_context(&codec_ctx);
  242. printf("main finish\n");
  243. return 0;
  244. }




m4a moov 格式解析:MP4格式解析---M4A是MP4中的音频部分_m4a格式解析_一个专研技术的小蜜蜂的博客-CSDN博客
mp4文件格式解析 - 知乎
参考:ffmpeg 利用AVIOContext自定义IO 输出结果写buffer - 知乎

Creating Custom FFmpeg IO-Context - CodeProject

ffmpeg AVIOContext 自定义 IO 及 seek

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/647039
推荐阅读
相关标签
  

闽ICP备14008679号