请选择 进入手机版 | 继续访问电脑版

北南南北论坛

 找回密码
 立即注册
查看: 28|回复: 2

使用ffmpeg实现转码样例(代码实现)

[复制链接]

448

主题

760

帖子

2163

积分

金牌会员

Rank: 6Rank: 6

积分
2163
发表于 2017-11-13 20:05:35 | 显示全部楼层 |阅读模式
使用ffmpeg实现转码样例(代码实现)

使用ffmpeg转码主要工作如下:
Demux -> Decoding -> Encoding -> Muxing

其中接口调用如下:

  1. av_register_all();
  2. avformat_open_input
  3. avformat_find_stream_info
  4. open_codec_context
  5. av_image_alloc
  6. avcodec_alloc_frame
  7. avformat_alloc_output_context2
  8. avcodec_open2
  9. avcodec_alloc_frame
  10. avpicture_alloc
  11. avpicture_alloc
  12. avformat_write_header
  13. av_init_packet
  14. av_read_frame
  15. avcodec_decode_video2
  16. av_image_copy
  17. avcodec_encode_video2
  18. av_interleaved_write_frame
  19. av_write_trailer
复制代码


下面的代码为主要将视频转码,封装为h264编码格式的mp4文件,音频为mp3,但是主要操作并不处理音频文件。代码如下

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <math.h>

  5. #include <libavutil/opt.h>
  6. #include <libavutil/mathematics.h>
  7. #include <libavformat/avformat.h>
  8. #include <libswscale/swscale.h>
  9. #include <libswresample/swresample.h>

  10. /* 5 seconds stream duration */
  11. #define STREAM_DURATION 200.0
  12. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  13. #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
  14. #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */

  15. static AVFormatContext *input_fmt_ctx = NULL;
  16. static int sws_flags = SWS_BICUBIC;
  17. static AVPacket input_pkt;
  18. static int video_stream_idx = -1;
  19. static uint8_t *video_dst_data[4] = {NULL};
  20. static int video_dst_linesize[4];
  21. static AVStream *input_video_stream;
  22. static AVFrame *input_frame;
  23. static AVCodecContext *video_dec_ctx = NULL;
  24. static int video_dst_bufsize;


  25. static int open_codec_context(int *stream_idx,
  26. AVFormatContext *fmt_ctx, enum AVMediaType type)
  27. {
  28. int ret;
  29. AVStream *st;
  30. AVCodecContext *dec_ctx = NULL;
  31. AVCodec *dec = NULL;

  32. ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  33. if (ret < 0) {
  34. return ret;
  35. } else {
  36. *stream_idx = ret;
  37. st = fmt_ctx->streams[*stream_idx];

  38. /* find decoder for the stream */
  39. dec_ctx = st->codec;
  40. dec = avcodec_find_decoder(dec_ctx->codec_id);
  41. if (!dec) {
  42. fprintf(stderr, "Failed to find %s codec\n",
  43. av_get_media_type_string(type));
  44. return ret;
  45. }

  46. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  47. fprintf(stderr, "Failed to open %s codec\n",
  48. av_get_media_type_string(type));
  49. return ret;
  50. }
  51. }

  52. return 0;
  53. }

  54. /* Add an output stream. */
  55. static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,
  56. enum AVCodecID codec_id)
  57. {
  58. AVCodecContext *c;
  59. AVStream *st;

  60. /* find the encoder */
  61. *codec = avcodec_find_encoder(codec_id);
  62. if (!(*codec)) {
  63. fprintf(stderr, "Could not find encoder for '%s'\n",
  64. avcodec_get_name(codec_id));
  65. exit(1);
  66. }

  67. st = avformat_new_stream(oc, *codec);
  68. if (!st) {
  69. fprintf(stderr, "Could not allocate stream\n");
  70. exit(1);
  71. }
  72. st->id = oc->nb_streams-1;
  73. c = st->codec;

  74. switch ((*codec)->type) {
  75. case AVMEDIA_TYPE_AUDIO:
  76. c->sample_fmt = AV_SAMPLE_FMT_FLTP;
  77. c->bit_rate = 64000;
  78. c->sample_rate = 44100;
  79. c->channels = 2;
  80. break;

  81. case AVMEDIA_TYPE_VIDEO:
  82. c->codec_id = codec_id;

  83. c->bit_rate = 400000;
  84. c->time_base.den = STREAM_FRAME_RATE;
  85. c->time_base.num = 1;
  86. c->gop_size = 12;
  87. c->pix_fmt = STREAM_PIX_FMT;
  88. break;

  89. default:
  90. break;
  91. }

  92. /* Some formats want stream headers to be separate. */
  93. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  94. c->flags |= CODEC_FLAG_GLOBAL_HEADER;

  95. return st;
  96. }

  97. /**************************************************************/
  98. /* audio output */

  99. static float t, tincr, tincr2;

  100. static uint8_t **src_samples_data;
  101. static int src_samples_linesize;
  102. static int src_nb_samples;

  103. static int max_dst_nb_samples;
  104. uint8_t **dst_samples_data;
  105. int dst_samples_linesize;
  106. int dst_samples_size;

  107. struct SwrContext *swr_ctx = NULL;

  108. static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
  109. {
  110. AVCodecContext *c;
  111. int ret;

  112. c = st->codec;

  113. /* open it */
  114. ret = avcodec_open2(c, codec, NULL);
  115. if (ret < 0) {
  116. fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
  117. exit(1);
  118. }

  119. /* init signal generator */
  120. t = 0;
  121. tincr = 2 * M_PI * 110.0 / c->sample_rate;
  122. /* increment frequency by 110 Hz per second */
  123. tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;

  124. src_nb_samples = c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
  125. 10000 : c->frame_size;

  126. ret = av_samples_alloc_array_and_samples(&src_samples_data, &src_samples_linesize, c->channels,
  127. src_nb_samples, c->sample_fmt, 0);
  128. if (ret < 0) {
  129. fprintf(stderr, "Could not allocate source samples\n");
  130. exit(1);
  131. }

  132. /* create resampler context */
  133. if (c->sample_fmt != AV_SAMPLE_FMT_S16) {
  134. swr_ctx = swr_alloc();
  135. if (!swr_ctx) {
  136. fprintf(stderr, "Could not allocate resampler context\n");
  137. exit(1);
  138. }

  139. /* set options */
  140. av_opt_set_int (swr_ctx, "in_channel_count", c->channels, 0);
  141. av_opt_set_int (swr_ctx, "in_sample_rate", c->sample_rate, 0);
  142. av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
  143. av_opt_set_int (swr_ctx, "out_channel_count", c->channels, 0);
  144. av_opt_set_int (swr_ctx, "out_sample_rate", c->sample_rate, 0);
  145. av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", c->sample_fmt, 0);

  146. /* initialize the resampling context */
  147. if ((ret = swr_init(swr_ctx)) < 0) {
  148. fprintf(stderr, "Failed to initialize the resampling context\n");
  149. exit(1);
  150. }
  151. }

  152. /* compute the number of converted samples: buffering is avoided
  153.   * ensuring that the output buffer will contain at least all the
  154.   * converted input samples */
  155. max_dst_nb_samples = src_nb_samples;
  156. ret = av_samples_alloc_array_and_samples(&dst_samples_data, &dst_samples_linesize, c->channels,
  157. max_dst_nb_samples, c->sample_fmt, 0);
  158. if (ret < 0) {
  159. fprintf(stderr, "Could not allocate destination samples\n");
  160. exit(1);
  161. }
  162. dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, max_dst_nb_samples,
  163. c->sample_fmt, 0);
  164. }

  165. /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
  166. * 'nb_channels' channels. */
  167. static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
  168. {
  169. int j, i, v;
  170. int16_t *q;

  171. q = samples;
  172. for (j = 0; j < frame_size; j++) {
  173. v = (int)(sin(t) * 10000);
  174. for (i = 0; i < nb_channels; i++)
  175. *q++ = v;
  176. t += tincr;
  177. tincr += tincr2;
  178. }
  179. }

  180. static void write_audio_frame(AVFormatContext *oc, AVStream *st)
  181. {
  182. AVCodecContext *c;
  183. AVPacket pkt = { 0 }; // data and size must be 0;
  184. AVFrame *frame = avcodec_alloc_frame();
  185. int got_packet, ret, dst_nb_samples;

  186. av_init_packet(&pkt);
  187. c = st->codec;

  188. get_audio_frame((int16_t *)src_samples_data[0], src_nb_samples, c->channels);

  189. /* convert samples from native format to destination codec format, using the resampler */
  190. if (swr_ctx) {
  191. /* compute destination number of samples */
  192. dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, c->sample_rate) + src_nb_samples,
  193. c->sample_rate, c->sample_rate, AV_ROUND_UP);
  194. if (dst_nb_samples > max_dst_nb_samples) {
  195. av_free(dst_samples_data[0]);
  196. ret = av_samples_alloc(dst_samples_data, &dst_samples_linesize, c->channels,
  197. dst_nb_samples, c->sample_fmt, 0);
  198. if (ret < 0)
  199. exit(1);
  200. max_dst_nb_samples = dst_nb_samples;
  201. dst_samples_size = av_samples_get_buffer_size(NULL, c->channels, dst_nb_samples,
  202. c->sample_fmt, 0);
  203. }

  204. /* convert to destination format */
  205. ret = swr_convert(swr_ctx,
  206. dst_samples_data, dst_nb_samples,
  207. (const uint8_t **)src_samples_data, src_nb_samples);
  208. if (ret < 0) {
  209. fprintf(stderr, "Error while converting\n");
  210. exit(1);
  211. }
  212. } else {
  213. dst_samples_data[0] = src_samples_data[0];
  214. dst_nb_samples = src_nb_samples;
  215. }

  216. frame->nb_samples = dst_nb_samples;
  217. avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
  218. dst_samples_data[0], dst_samples_size, 0);

  219. ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
  220. if (ret < 0) {
  221. fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
  222. exit(1);
  223. }

  224. if (!got_packet)
  225. return;

  226. pkt.stream_index = st->index;

  227. /* Write the compressed frame to the media file. */
  228. ret = av_interleaved_write_frame(oc, &pkt);
  229. if (ret != 0) {
  230. fprintf(stderr, "Error while writing audio frame: %s\n",
  231. av_err2str(ret));
  232. exit(1);
  233. }
  234. avcodec_free_frame(&frame);
  235. }

  236. static void close_audio(AVFormatContext *oc, AVStream *st)
  237. {
  238. avcodec_close(st->codec);
  239. av_free(src_samples_data[0]);
  240. av_free(dst_samples_data[0]);
  241. }

复制代码
回复

使用道具 举报

448

主题

760

帖子

2163

积分

金牌会员

Rank: 6Rank: 6

积分
2163
 楼主| 发表于 2017-11-13 20:06:02 | 显示全部楼层
  1. /***********************bbs.ChinaFFmpeg.com****孙悟空***********************/
  2. /* video output */

  3. static AVFrame *frame;
  4. static AVPicture src_picture, dst_picture;
  5. static int frame_count;

  6. static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
  7. {
  8. int ret;
  9. AVCodecContext *c = st->codec;

  10. /* open the codec */
  11. ret = avcodec_open2(c, codec, NULL);
  12. if (ret < 0) {
  13. fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
  14. exit(1);
  15. }

  16. /* allocate and init a re-usable frame */
  17. frame = avcodec_alloc_frame();
  18. if (!frame) {
  19. fprintf(stderr, "Could not allocate video frame\n");
  20. exit(1);
  21. }

  22. /* Allocate the encoded raw picture. */
  23. ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
  24. if (ret < 0) {
  25. fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret));
  26. exit(1);
  27. }

  28. /* If the output format is not YUV420P, then a temporary YUV420P
  29.   * picture is needed too. It is then converted to the required
  30.   * output format. */
  31. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  32. ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
  33. if (ret < 0) {
  34. fprintf(stderr, "Could not allocate temporary picture: %s\n",
  35. av_err2str(ret));
  36. exit(1);
  37. }
  38. }

  39. /* copy data and linesize picture pointers to frame */
  40. *((AVPicture *)frame) = dst_picture;
  41. }

  42. static void write_video_frame(AVFormatContext *oc, AVStream *st)
  43. {
  44. int ret;
  45. static struct SwsContext *sws_ctx;
  46. AVCodecContext *c = st->codec;

  47. // fill_yuv_image(&dst_picture, frame_count, c->width, c->height);


  48. if (oc->oformat->flags & AVFMT_RAWPICTURE) {
  49. /* Raw video case - directly store the picture in the packet */
  50. AVPacket pkt;
  51. av_init_packet(&pkt);

  52. pkt.flags |= AV_PKT_FLAG_KEY;
  53. pkt.stream_index = st->index;
  54. pkt.data = dst_picture.data[0];
  55. pkt.size = sizeof(AVPicture);

  56. ret = av_interleaved_write_frame(oc, &pkt);
  57. } else {
  58. AVPacket pkt = { 0 };
  59. int got_packet;
  60. av_init_packet(&pkt);

  61. /* encode the image */
  62. ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
  63. if (ret < 0) {
  64. fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
  65. exit(1);
  66. }
  67. /* If size is zero, it means the image was buffered. */

  68. if (!ret && got_packet && pkt.size) {
  69. pkt.stream_index = st->index;

  70. /* Write the compressed frame to the media file. */
  71. ret = av_interleaved_write_frame(oc, &pkt);
  72. } else {
  73. ret = 0;
  74. }
  75. }
  76. if (ret != 0) {
  77. fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
  78. exit(1);
  79. }
  80. frame_count++;
  81. }

  82. static void close_video(AVFormatContext *oc, AVStream *st)
  83. {
  84. avcodec_close(st->codec);
  85. av_free(src_picture.data[0]);
  86. av_free(dst_picture.data[0]);
  87. av_free(frame);
  88. }

  89. /**************************************************************/
  90. /* media file output */

  91. int main(int argc, char **argv)
  92. {
  93. const char *filename;
  94. const char *input_file;
  95. AVOutputFormat *fmt;
  96. AVFormatContext *oc;
  97. AVStream *audio_st, *video_st;
  98. AVCodec *audio_codec, *video_codec;
  99. double audio_time, video_time;
  100. int ret;
  101. int decoded;
  102. int got_frame;

  103. /* Initialize libavcodec, and register all codecs and formats. */
  104. av_register_all();

  105. if (argc != 3) {
  106. printf("usage: %s output_file inputfile\n"
  107. "API example program to output a media file with libavformat.\n"
  108. "This program generates a synthetic audio and video stream, encodes and\n"
  109. "muxes them into a file named output_file.\n"
  110. "The output format is automatically guessed according to the file extension.\n"
  111. "Raw images can also be output by using '%%d' in the filename.\n"
  112. "\n", argv[0]);
  113. return 1;
  114. }

  115. input_file = argv[2];
  116. filename = argv[1];

  117. if (avformat_open_input( &input_fmt_ctx, input_file, NULL, NULL) < 0) {
  118. fprintf(stderr, "Could not open source file %s\n", input_file);
  119. exit(-1);
  120. }

  121. /* retrieve stream information */
  122. if (avformat_find_stream_info(input_fmt_ctx, NULL) < 0) {
  123. fprintf(stderr, "Could not find stream information\n");
  124. exit(1);
  125. }

  126. if (open_codec_context(&video_stream_idx, input_fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
  127. input_video_stream = input_fmt_ctx->streams[video_stream_idx];
  128. video_dec_ctx = input_video_stream->codec;
  129. ret = av_image_alloc(video_dst_data, video_dst_linesize,
  130. video_dec_ctx->width, video_dec_ctx->height,
  131. video_dec_ctx->pix_fmt, 1);
  132. if (ret < 0) {
  133. fprintf(stderr, "Could not allocate raw video buffer\n");
  134. }
  135. video_dst_bufsize = ret;
  136. }


  137. input_frame = avcodec_alloc_frame();
  138. if (!input_frame) {
  139. fprintf(stderr, "Could not allocate frame\n");
  140. ret = AVERROR(ENOMEM);
  141. exit(-1);
  142. }

  143. /* allocate the output media context */
  144. avformat_alloc_output_context2(&oc, NULL, NULL, filename);
  145. if (!oc) {
  146. printf("Could not deduce output format from file extension: using MPEG.\n");
  147. avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
  148. }
  149. if (!oc) {
  150. return 1;
  151. }
  152. fmt = oc->oformat;

  153. video_st = NULL;
  154. audio_st = NULL;

  155. fmt->video_codec = AV_CODEC_ID_H264;
  156. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  157. video_st = add_stream(oc, &video_codec, AV_CODEC_ID_H264);
  158. }
  159. if (video_st->codec) {
  160. video_st->codec->width = video_dec_ctx->width;
  161. video_st->codec->height = video_dec_ctx->height;
  162. }
  163. fmt->audio_codec = AV_CODEC_ID_MP3;
  164. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  165. audio_st = add_stream(oc, &audio_codec, AV_CODEC_ID_MP3);
  166. }

  167. /* Now that all the parameters are set, we can open the audio and
  168.   * video codecs and allocate the necessary encode buffers. */
  169. if (video_st)
  170. open_video(oc, video_codec, video_st);
  171. if (audio_st)
  172. open_audio(oc, audio_codec, audio_st);

  173. av_dump_format(oc, 0, filename, 1);


  174. /* open the output file, if needed */
  175. if (!(fmt->flags & AVFMT_NOFILE)) {
  176. ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
  177. if (ret < 0) {
  178. fprintf(stderr, "Could not open '%s': %s\n", filename,
  179. av_err2str(ret));
  180. return 1;
  181. }
  182. }

  183. /* Write the stream header, if any. */
  184. ret = avformat_write_header(oc, NULL);
  185. if (ret < 0) {
  186. fprintf(stderr, "Error occurred when opening output file: %s\n",
  187. av_err2str(ret));
  188. return 1;
  189. }

  190. av_init_packet(&input_pkt);
  191. input_pkt.data = NULL;
  192. input_pkt.size = 0;


  193. if (frame)
  194. frame->pts = 0;
  195. for (;;) {
  196. /* Compute current audio and video time. */
  197. audio_time = audio_st ? audio_st->pts.val * av_q2d(audio_st->time_base) : 0.0;
  198. video_time = video_st ? video_st->pts.val * av_q2d(video_st->time_base) : 0.0;

  199. if ((!audio_st || audio_time >= STREAM_DURATION) &&
  200. (!video_st || video_time >= STREAM_DURATION))
  201. break;

  202. /* write interleaved audio and video frames */
  203. if (!video_st || (video_st && audio_st && audio_time < video_time)) {
  204. write_audio_frame(oc, audio_st);
  205. } else {
  206. av_read_frame(input_fmt_ctx, &input_pkt);

  207. decoded = input_pkt.size;
  208. if (input_pkt.stream_index == video_stream_idx) {
  209. /* decode video frame */
  210. ret = avcodec_decode_video2(video_dec_ctx, input_frame, &got_frame, &input_pkt);
  211. if (ret < 0) {
  212. fprintf(stderr, "Error decoding video frame\n");
  213. return ret;
  214. }

  215. if (got_frame) {
  216. av_image_copy(&dst_picture, video_dst_linesize,
  217. (const uint8_t **)(input_frame->data), input_frame->linesize,
  218. video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
  219. }
  220. }

  221. write_video_frame(oc, video_st);
  222. frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base);
  223. }
  224. }

  225. av_write_trailer(oc);

  226. /* Close each codec. */
  227. if (video_st)
  228. close_video(oc, video_st);
  229. if (audio_st)
  230. close_audio(oc, audio_st);

  231. if (!(fmt->flags & AVFMT_NOFILE))
  232. avio_close(oc->pb);

  233. avformat_free_context(oc);
  234. av_free(input_frame);
  235. av_free(video_dst_data[0]);
  236. avcodec_close(video_dec_ctx);
  237. return 0;
  238. }
复制代码


回复 支持 反对

使用道具 举报

448

主题

760

帖子

2163

积分

金牌会员

Rank: 6Rank: 6

积分
2163
 楼主| 发表于 2017-11-13 20:07:15 | 显示全部楼层
以上代码为从dox/example/muxing.c中修改得到
编译命令如下:

  1. gcc -g doc/examples/muxing.c -o muxing -lavcodec -lavdevice -lavfilter -lavformat -lavutil -lswscale -lswresample -lpostproc -lx264 -lmp3lame -lz -liconv -lbz2
复制代码


执行命令如下:

  1. ./muxing output.mp4 ~/Movies/input.avi
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则


手机版|北南南北论坛  

GMT+8, 2017-12-16 17:16 , Processed in 0.095447 second(s), 30 queries .

© 2001-2016 VxWorks6 Inc.

快速回复 返回顶部 返回列表