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


    分类: C/C++

    使用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 ",
    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 ",
    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' ",
    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 ");
    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 ", 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 ");
    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 ");
    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 ");
    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 ");
    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 ");
    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 ", 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 ",
    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. }
    242. /***********************bbs.ChinaFFmpeg.com****孙悟空***********************/
    243. /* video output */
    244. static AVFrame *frame;
    245. static AVPicture src_picture, dst_picture;
    246. static int frame_count;
    247. static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
    248. {
    249.  int ret;
    250.  AVCodecContext *c = st->codec;
    251.  /* open the codec */
    252.  ret = avcodec_open2(c, codec, NULL);
    253.  if (ret < 0) {
    254.  fprintf(stderr, "Could not open video codec: %s ", av_err2str(ret));
    255.  exit(1);
    256.  }
    257.  /* allocate and init a re-usable frame */
    258.  frame = avcodec_alloc_frame();
    259.  if (!frame) {
    260.  fprintf(stderr, "Could not allocate video frame ");
    261.  exit(1);
    262.  }
    263.  /* Allocate the encoded raw picture. */
    264.  ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
    265.  if (ret < 0) {
    266.  fprintf(stderr, "Could not allocate picture: %s ", av_err2str(ret));
    267.  exit(1);
    268.  }
    269.  /* If the output format is not YUV420P, then a temporary YUV420P
    270.   * picture is needed too. It is then converted to the required
    271.   * output format. */
    272.  if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
    273.  ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
    274.  if (ret < 0) {
    275.  fprintf(stderr, "Could not allocate temporary picture: %s ",
    276.  av_err2str(ret));
    277.  exit(1);
    278.  }
    279.  }
    280.  /* copy data and linesize picture pointers to frame */
    281.  *((AVPicture *)frame) = dst_picture;
    282. }
    283. static void write_video_frame(AVFormatContext *oc, AVStream *st)
    284. {
    285.  int ret;
    286.  static struct SwsContext *sws_ctx;
    287.  AVCodecContext *c = st->codec;
    288.  // fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
    289.  if (oc->oformat->flags & AVFMT_RAWPICTURE) {
    290.  /* Raw video case - directly store the picture in the packet */
    291.  AVPacket pkt;
    292.  av_init_packet(&pkt);
    293.  pkt.flags |= AV_PKT_FLAG_KEY;
    294.  pkt.stream_index = st->index;
    295.  pkt.data = dst_picture.data[0];
    296.  pkt.size = sizeof(AVPicture);
    297.  ret = av_interleaved_write_frame(oc, &pkt);
    298.  } else {
    299.  AVPacket pkt = { 0 };
    300.  int got_packet;
    301.  av_init_packet(&pkt);
    302.  /* encode the image */
    303.  ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
    304.  if (ret < 0) {
    305.  fprintf(stderr, "Error encoding video frame: %s ", av_err2str(ret));
    306.  exit(1);
    307.  }
    308.  /* If size is zero, it means the image was buffered. */
    309.  if (!ret && got_packet && pkt.size) {
    310.  pkt.stream_index = st->index;
    311.  /* Write the compressed frame to the media file. */
    312.  ret = av_interleaved_write_frame(oc, &pkt);
    313.  } else {
    314.  ret = 0;
    315.  }
    316.  }
    317.  if (ret != 0) {
    318.  fprintf(stderr, "Error while writing video frame: %s ", av_err2str(ret));
    319.  exit(1);
    320.  }
    321.  frame_count++;
    322. }
    323. static void close_video(AVFormatContext *oc, AVStream *st)
    324. {
    325.  avcodec_close(st->codec);
    326.  av_free(src_picture.data[0]);
    327.  av_free(dst_picture.data[0]);
    328.  av_free(frame);
    329. }
    330. /**************************************************************/
    331. /* media file output */
    332. int main(int argc, char **argv)
    333. {
    334.  const char *filename;
    335.  const char *input_file;
    336.  AVOutputFormat *fmt;
    337.  AVFormatContext *oc;
    338.  AVStream *audio_st, *video_st;
    339.  AVCodec *audio_codec, *video_codec;
    340.  double audio_time, video_time;
    341.  int ret;
    342.  int decoded;
    343.  int got_frame;
    344.  /* Initialize libavcodec, and register all codecs and formats. */
    345.  av_register_all();
    346.  if (argc != 3) {
    347.  printf("usage: %s output_file inputfile "
    348.  "API example program to output a media file with libavformat. "
    349.  "This program generates a synthetic audio and video stream, encodes and "
    350.  "muxes them into a file named output_file. "
    351.  "The output format is automatically guessed according to the file extension. "
    352.  "Raw images can also be output by using '%%d' in the filename. "
    353.  " ", argv[0]);
    354.  return 1;
    355.  }
    356.  input_file = argv[2];
    357.  filename = argv[1];
    358.  if (avformat_open_input( &input_fmt_ctx, input_file, NULL, NULL) < 0) {
    359.  fprintf(stderr, "Could not open source file %s ", input_file);
    360.  exit(-1);
    361.  }
    362.  /* retrieve stream information */
    363.  if (avformat_find_stream_info(input_fmt_ctx, NULL) < 0) {
    364.  fprintf(stderr, "Could not find stream information ");
    365.  exit(1);
    366.  }
    367.  if (open_codec_context(&video_stream_idx, input_fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
    368.  input_video_stream = input_fmt_ctx->streams[video_stream_idx];
    369.  video_dec_ctx = input_video_stream->codec;
    370.  ret = av_image_alloc(video_dst_data, video_dst_linesize,
    371.  video_dec_ctx->width, video_dec_ctx->height,
    372.  video_dec_ctx->pix_fmt, 1);
    373.  if (ret < 0) {
    374.  fprintf(stderr, "Could not allocate raw video buffer ");
    375.  }
    376.  video_dst_bufsize = ret;
    377.  }
    378.  input_frame = avcodec_alloc_frame();
    379.  if (!input_frame) {
    380.  fprintf(stderr, "Could not allocate frame ");
    381.  ret = AVERROR(ENOMEM);
    382.  exit(-1);
    383.  }
    384.  /* allocate the output media context */
    385.  avformat_alloc_output_context2(&oc, NULL, NULL, filename);
    386.  if (!oc) {
    387.  printf("Could not deduce output format from file extension: using MPEG. ");
    388.  avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
    389.  }
    390.  if (!oc) {
    391.  return 1;
    392.  }
    393.  fmt = oc->oformat;
    394.  video_st = NULL;
    395.  audio_st = NULL;
    396.  fmt->video_codec = AV_CODEC_ID_H264;
    397.  if (fmt->video_codec != AV_CODEC_ID_NONE) {
    398.  video_st = add_stream(oc, &video_codec, AV_CODEC_ID_H264);
    399.  }
    400.  if (video_st->codec) {
    401.  video_st->codec->width = video_dec_ctx->width;
    402.  video_st->codec->height = video_dec_ctx->height;
    403.  }
    404.  fmt->audio_codec = AV_CODEC_ID_MP3;
    405.  if (fmt->audio_codec != AV_CODEC_ID_NONE) {
    406.  audio_st = add_stream(oc, &audio_codec, AV_CODEC_ID_MP3);
    407.  }
    408.  /* Now that all the parameters are set, we can open the audio and
    409.   * video codecs and allocate the necessary encode buffers. */
    410.  if (video_st)
    411.  open_video(oc, video_codec, video_st);
    412.  if (audio_st)
    413.  open_audio(oc, audio_codec, audio_st);
    414.  av_dump_format(oc, 0, filename, 1);
    415.  /* open the output file, if needed */
    416.  if (!(fmt->flags & AVFMT_NOFILE)) {
    417.  ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
    418.  if (ret < 0) {
    419.  fprintf(stderr, "Could not open '%s': %s ", filename,
    420.  av_err2str(ret));
    421.  return 1;
    422.  }
    423.  }
    424.  /* Write the stream header, if any. */
    425.  ret = avformat_write_header(oc, NULL);
    426.  if (ret < 0) {
    427.  fprintf(stderr, "Error occurred when opening output file: %s ",
    428.  av_err2str(ret));
    429.  return 1;
    430.  }
    431.  av_init_packet(&input_pkt);
    432.  input_pkt.data = NULL;
    433.  input_pkt.size = 0;
    434.  if (frame)
    435.  frame->pts = 0;
    436.  for (;;) {
    437.  /* Compute current audio and video time. */
    438.  audio_time = audio_st ? audio_st->pts.val * av_q2d(audio_st->time_base) : 0.0;
    439.  video_time = video_st ? video_st->pts.val * av_q2d(video_st->time_base) : 0.0;
    440.  if ((!audio_st || audio_time >= STREAM_DURATION) &&
    441.  (!video_st || video_time >= STREAM_DURATION))
    442.  break;
    443.  /* write interleaved audio and video frames */
    444.  if (!video_st || (video_st && audio_st && audio_time < video_time)) {
    445.  write_audio_frame(oc, audio_st);
    446.  } else {
    447.  av_read_frame(input_fmt_ctx, &input_pkt);
    448.  decoded = input_pkt.size;
    449.  if (input_pkt.stream_index == video_stream_idx) {
    450.  /* decode video frame */
    451.  ret = avcodec_decode_video2(video_dec_ctx, input_frame, &got_frame, &input_pkt);
    452.  if (ret < 0) {
    453.  fprintf(stderr, "Error decoding video frame ");
    454.  return ret;
    455.  }
    456.  if (got_frame) {
    457.  av_image_copy(&dst_picture, video_dst_linesize,
    458.  (const uint8_t **)(input_frame->data), input_frame->linesize,
    459.  video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
    460.  }
    461.  } 
    462.  write_video_frame(oc, video_st);
    463.  frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base);
    464.  }
    465.  }
    466.  av_write_trailer(oc);
    467.  /* Close each codec. */
    468.  if (video_st)
    469.  close_video(oc, video_st);
    470.  if (audio_st)
    471.  close_audio(oc, audio_st);
    472.  if (!(fmt->flags & AVFMT_NOFILE))
    473.  avio_close(oc->pb);
    474.  avformat_free_context(oc);
    475.  av_free(input_frame);
    476.  av_free(video_dst_data[0]);
    477.  avcodec_close(video_dec_ctx);
    478.  return 0;
    479. }

    以上代码为从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
    执行命令如下:

    点击(此处)折叠或打开

    执行后效果如下:

    查看转码完成后的多媒体文件的信息:

    查看转码后的文件的视频:




  • 相关阅读:
    Cf的一些总结
    Goodbye 2019
    牛客多校第8场 A题
    19牛客多校第二场 H题
    Hihocoder1673
    记一次根据图片原尺寸设置样式,并进行缩放和拖拽
    鱼骨时间轴案例(转自CSDN,原文链接附于文中)
    jQuery横向上下排列鱼骨图形式信息展示代码时光轴样式(转自CSDN,原文链接附于文中)
    mxGraph实现鱼骨图(因果图)(转自CSDN,链接附于文中)
    erlang win64位包下载链接
  • 原文地址:https://www.cnblogs.com/android-blogs/p/5663149.html
Copyright © 2020-2023  润新知