运用ffmpeg生成MP4文件

来源:互联网 发布:物品识别软件 编辑:程序博客网 时间:2024/06/05 15:46

生成的MP4文件,用播放器看见的视频如下,同时你可以听到一种呼叫的音频声音


生成的MP4文件音频为(aac)、视频为H264
由于生成的H264需要依赖x264开源库【因为需要将普通的原始数据编码成H264,而ffmpeg默认是按x264进行编码】,在生产x264库过程中,一般我们默认生成静态库即可。

编译ffmpeg并安装


代码如下:

[cpp] view plain copy
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <string.h>  
  4. #include <math.h>  
  5.   
  6. #include "libavutil/mathematics.h"  
  7. #include "libavformat/avformat.h"  
  8. #include "libswscale/swscale.h"  
  9.   
  10. #undef exit  
  11.   
  12. /* 5 seconds stream duration */  
  13. #define STREAM_DURATION   200.0  
  14. #define STREAM_FRAME_RATE 25 /* 25 images/s */  
  15. #define STREAM_NB_FRAMES  ((int)(STREAM_DURATION * STREAM_FRAME_RATE))  
  16. #define STREAM_PIX_FMT PIX_FMT_YUV420P /* default pix_fmt */  
  17.   
  18. static int sws_flags = SWS_BICUBIC;  
  19.   
  20. /**************************************************************/  
  21. /* audio output */  
  22.   
  23. static float t, tincr, tincr2;  
  24. static int16_t *samples;  
  25. static uint8_t *audio_outbuf;  
  26. static int audio_outbuf_size;  
  27. static int audio_input_frame_size;  
  28.   
  29. /* 
  30.  * add an audio output stream 
  31.  */  
  32. static AVStream *add_audio_stream(AVFormatContext *oc, enum CodecID codec_id)  
  33. {  
  34.     AVCodecContext *c;  
  35.     AVStream *st;  
  36.   
  37.     st = avformat_new_stream(oc, NULL);  
  38.     if (!st) {  
  39.         fprintf(stderr, "Could not alloc stream\n");  
  40.         exit(1);  
  41.     }  
  42.     st->id = 1;  
  43.   
  44.     c = st->codec;  
  45.     c->codec_id = codec_id;  
  46.     c->codec_type = AVMEDIA_TYPE_AUDIO;  
  47.   
  48.     /* put sample parameters */  
  49.     c->sample_fmt = AV_SAMPLE_FMT_S16;  
  50.     c->bit_rate = 64000;  
  51.     c->sample_rate = 44100;  
  52.     c->channels = 2;  
  53.   
  54.     // some formats want stream headers to be separate  
  55.     if (oc->oformat->flags & AVFMT_GLOBALHEADER)  
  56.         c->flags |= CODEC_FLAG_GLOBAL_HEADER;  
  57.   
  58.     return st;  
  59. }  
  60.   
  61. static void open_audio(AVFormatContext *oc, AVStream *st)  
  62. {  
  63.     AVCodecContext *c;  
  64.     AVCodec *codec;  
  65.   
  66.     c = st->codec;  
  67.   
  68.     /* find the audio encoder */  
  69.     codec = avcodec_find_encoder(c->codec_id);  
  70.     if (!codec) {  
  71.         fprintf(stderr, "codec not found\n");  
  72.         exit(1);  
  73.     }  
  74.   
  75.     /* open it */  
  76.     if (avcodec_open(c, codec) < 0) {  
  77.         fprintf(stderr, "could not open codec\n");  
  78.         exit(1);  
  79.     }  
  80.   
  81.     /* init signal generator */  
  82.     t = 0;  
  83.     tincr = 2 * M_PI * 110.0 / c->sample_rate;  
  84.     /* increment frequency by 110 Hz per second */  
  85.     tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;  
  86.   
  87.     audio_outbuf_size = 10000;  
  88.     audio_outbuf = av_malloc(audio_outbuf_size);  
  89.   
  90.   
  91.     if (c->frame_size <= 1) {  
  92.         audio_input_frame_size = audio_outbuf_size / c->channels;  
  93.         switch(st->codec->codec_id) {  
  94.         case CODEC_ID_PCM_S16LE:  
  95.         case CODEC_ID_PCM_S16BE:  
  96.         case CODEC_ID_PCM_U16LE:  
  97.         case CODEC_ID_PCM_U16BE:  
  98.             audio_input_frame_size >>= 1;  
  99.             break;  
  100.         default:  
  101.             break;  
  102.         }  
  103.     } else {  
  104.         audio_input_frame_size = c->frame_size;  
  105.     }  
  106.     samples = av_malloc(audio_input_frame_size * 2 * c->channels);  
  107. }  
  108.   
  109.   
  110. static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)  
  111. {  
  112.     int j, i, v;  
  113.     int16_t *q;  
  114.   
  115.     q = samples;  
  116.     for (j = 0; j < frame_size; j++) {  
  117.         v = (int)(sin(t) * 10000);  
  118.         for(i = 0; i < nb_channels; i++)  
  119.             *q++ = v;  
  120.         t += tincr;  
  121.         tincr += tincr2;  
  122.     }  
  123. }  
  124.   
  125. static void write_audio_frame(AVFormatContext *oc, AVStream *st)  
  126. {  
  127.     AVCodecContext *c;  
  128.     AVPacket pkt;  
  129.     av_init_packet(&pkt);  
  130.   
  131.     c = st->codec;  
  132.   
  133.     get_audio_frame(samples, audio_input_frame_size, c->channels);  
  134.   
  135.     pkt.size = avcodec_encode_audio(c, audio_outbuf, audio_outbuf_size, samples);  
  136.   
  137.     if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)  
  138.         pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);  
  139.     pkt.flags |= AV_PKT_FLAG_KEY;  
  140.     pkt.stream_index = st->index;  
  141.     pkt.data = audio_outbuf;  
  142.   
  143.     /* write the compressed frame in the media file */  
  144.     if (av_interleaved_write_frame(oc, &pkt) != 0) {  
  145.         fprintf(stderr, "Error while writing audio frame\n");  
  146.         exit(1);  
  147.     }  
  148. }  
  149.   
  150. static void close_audio(AVFormatContext *oc, AVStream *st)  
  151. {  
  152.     avcodec_close(st->codec);  
  153.   
  154.     av_free(samples);  
  155.     av_free(audio_outbuf);  
  156. }  
  157.   
  158. /**************************************************************/  
  159. /* video output */  
  160.   
  161. static AVFrame *picture, *tmp_picture;  
  162. static uint8_t *video_outbuf;  
  163. static int frame_count, video_outbuf_size;  
  164.   
  165. /* add a video output stream */  
  166. static AVStream *add_video_stream(AVFormatContext *oc, enum CodecID codec_id)  
  167. {  
  168.     AVCodecContext *c;  
  169.     AVStream *st;  
  170.     AVCodec *codec;  
  171.   
  172.     st = avformat_new_stream(oc, NULL);  
  173.     if (!st) {  
  174.         fprintf(stderr, "Could not alloc stream\n");  
  175.         exit(1);  
  176.     }  
  177.   
  178.     c = st->codec;  
  179.   
  180.     /* find the video encoder */  
  181.     codec = avcodec_find_encoder(codec_id);  
  182.     if (!codec) {  
  183.         fprintf(stderr, "codec not found\n");  
  184.         exit(1);  
  185.     }  
  186.     avcodec_get_context_defaults3(c, codec);  
  187.   
  188.     c->codec_id = codec_id;  
  189.   
  190.     /* put sample parameters */  
  191.     c->bit_rate = 400000;  
  192.     /* resolution must be a multiple of two */  
  193.     c->width = 352;  
  194.     c->height = 288;  
  195.     /* time base: this is the fundamental unit of time (in seconds) in terms 
  196.        of which frame timestamps are represented. for fixed-fps content, 
  197.        timebase should be 1/framerate and timestamp increments should be 
  198.        identically 1. */  
  199.     c->time_base.den = STREAM_FRAME_RATE;  
  200.     c->time_base.num = 1;  
  201.     c->gop_size = 12; /* emit one intra frame every twelve frames at most */  
  202.     c->pix_fmt = STREAM_PIX_FMT;  
  203.     if (c->codec_id == CODEC_ID_MPEG2VIDEO) {  
  204.         /* just for testing, we also add B frames */  
  205.         c->max_b_frames = 2;  
  206.     }  
  207.     if (c->codec_id == CODEC_ID_MPEG1VIDEO){  
  208.         /* Needed to avoid using macroblocks in which some coeffs overflow. 
  209.            This does not happen with normal video, it just happens here as 
  210.            the motion of the chroma plane does not match the luma plane. */  
  211.         c->mb_decision=2;  
  212.     }  
  213.     // some formats want stream headers to be separate  
  214.     if (oc->oformat->flags & AVFMT_GLOBALHEADER)  
  215.         c->flags |= CODEC_FLAG_GLOBAL_HEADER;  
  216.   
  217.     return st;  
  218. }  
  219.   
  220. static AVFrame *alloc_picture(enum PixelFormat pix_fmt, int width, int height)  
  221. {  
  222.     AVFrame *picture;  
  223.     uint8_t *picture_buf;  
  224.     int size;  
  225.   
  226.     picture = avcodec_alloc_frame();  
  227.     if (!picture)  
  228.         return NULL;  
  229.     size = avpicture_get_size(pix_fmt, width, height);  
  230.     picture_buf = av_malloc(size);  
  231.     if (!picture_buf) {  
  232.         av_free(picture);  
  233.         return NULL;  
  234.     }  
  235.     avpicture_fill((AVPicture *)picture, picture_buf,  
  236.                    pix_fmt, width, height);  
  237.     return picture;  
  238. }  
  239.   
  240. static void open_video(AVFormatContext *oc, AVStream *st)  
  241. {  
  242.     AVCodec *codec;  
  243.     AVCodecContext *c;  
  244.   
  245.     c = st->codec;  
  246.   
  247.     /* find the video encoder */  
  248.     codec = avcodec_find_encoder(c->codec_id);  
  249.     if (!codec) {  
  250.         fprintf(stderr, "codec not found\n");  
  251.         exit(1);  
  252.     }  
  253.   
  254.     /* open the codec */  
  255.     if (avcodec_open(c, codec) < 0) {  
  256.         fprintf(stderr, "could not open codec\n");  
  257.         exit(1);  
  258.     }  
  259.   
  260.     video_outbuf = NULL;  
  261.     if (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {  
  262.         video_outbuf_size = 200000;  
  263.         video_outbuf = av_malloc(video_outbuf_size);  
  264.     }  
  265.   
  266.     /* allocate the encoded raw picture */  
  267.     picture = alloc_picture(c->pix_fmt, c->width, c->height);  
  268.     if (!picture) {  
  269.         fprintf(stderr, "Could not allocate picture\n");  
  270.         exit(1);  
  271.     }  
  272.   
  273.     /* if the output format is not YUV420P, then a temporary YUV420P 
  274.        picture is needed too. It is then converted to the required 
  275.        output format */  
  276.     tmp_picture = NULL;  
  277.     if (c->pix_fmt != PIX_FMT_YUV420P) {  
  278.         tmp_picture = alloc_picture(PIX_FMT_YUV420P, c->width, c->height);  
  279.         if (!tmp_picture) {  
  280.             fprintf(stderr, "Could not allocate temporary picture\n");  
  281.             exit(1);  
  282.         }  
  283.     }  
  284. }  
  285.   
  286. /* prepare a dummy image */  
  287. static void fill_yuv_image(AVFrame *pict, int frame_index, int width, int height)  
  288. {  
  289.     int x, y, i;  
  290.   
  291.     i = frame_index;  
  292.   
  293.     /* Y */  
  294.     for (y = 0; y < height; y++) {  
  295.         for (x = 0; x < width; x++) {  
  296.             pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;  
  297.         }  
  298.     }  
  299.   
  300.     /* Cb and Cr */  
  301.     for (y = 0; y < height/2; y++) {  
  302.         for (x = 0; x < width/2; x++) {  
  303.             pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;  
  304.             pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;  
  305.         }  
  306.     }  
  307. }  
  308.   
  309. static void write_video_frame(AVFormatContext *oc, AVStream *st)  
  310. {  
  311.     int out_size, ret;  
  312.     AVCodecContext *c;  
  313.     static struct SwsContext *img_convert_ctx;  
  314.   
  315.     c = st->codec;  
  316.   
  317.     if (frame_count >= STREAM_NB_FRAMES) {  
  318.         /* no more frame to compress. The codec has a latency of a few 
  319.            frames if using B frames, so we get the last frames by 
  320.            passing the same picture again */  
  321.     } else {  
  322.         if (c->pix_fmt != PIX_FMT_YUV420P) {  
  323.             /* as we only generate a YUV420P picture, we must convert it 
  324.                to the codec pixel format if needed */  
  325.             if (img_convert_ctx == NULL) {  
  326.                 img_convert_ctx = sws_getContext(c->width, c->height,  
  327.                                                  PIX_FMT_YUV420P,  
  328.                                                  c->width, c->height,  
  329.                                                  c->pix_fmt,  
  330.                                                  sws_flags, NULL, NULL, NULL);  
  331.                 if (img_convert_ctx == NULL) {  
  332.                     fprintf(stderr, "Cannot initialize the conversion context\n");  
  333.                     exit(1);  
  334.                 }  
  335.             }  
  336.             fill_yuv_image(tmp_picture, frame_count, c->width, c->height);  
  337.             sws_scale(img_convert_ctx, tmp_picture->data, tmp_picture->linesize,  
  338.                       0, c->height, picture->data, picture->linesize);  
  339.         } else {  
  340.             fill_yuv_image(picture, frame_count, c->width, c->height);  
  341.         }  
  342.     }  
  343.   
  344.   
  345.     if (oc->oformat->flags & AVFMT_RAWPICTURE) {  
  346.         /* raw video case. The API will change slightly in the near 
  347.            future for that. */  
  348.         AVPacket pkt;  
  349.         av_init_packet(&pkt);  
  350.   
  351.         pkt.flags |= AV_PKT_FLAG_KEY;  
  352.         pkt.stream_index = st->index;  
  353.         pkt.data = (uint8_t *)picture;  
  354.         pkt.size = sizeof(AVPicture);  
  355.   
  356.         ret = av_interleaved_write_frame(oc, &pkt);  
  357.     } else {  
  358.         /* encode the image */  
  359.         out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);  
  360.         /* if zero size, it means the image was buffered */  
  361.         if (out_size > 0) {  
  362.             AVPacket pkt;  
  363.             av_init_packet(&pkt);  
  364.   
  365.             if (c->coded_frame->pts != AV_NOPTS_VALUE)  
  366.                 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);  
  367.             if(c->coded_frame->key_frame)  
  368.                 pkt.flags |= AV_PKT_FLAG_KEY;  
  369.             pkt.stream_index = st->index;  
  370.             pkt.data = video_outbuf;  
  371.             pkt.size = out_size;  
  372.   
  373.             /* write the compressed frame in the media file */  
  374.             ret = av_interleaved_write_frame(oc, &pkt);  
  375.         } else {  
  376.             ret = 0;  
  377.         }  
  378.     }  
  379.     if (ret != 0) {  
  380.         fprintf(stderr, "Error while writing video frame\n");  
  381.         exit(1);  
  382.     }  
  383.     frame_count++;  
  384. }  
  385.   
  386. static void close_video(AVFormatContext *oc, AVStream *st)  
  387. {  
  388.     avcodec_close(st->codec);  
  389.     av_free(picture->data[0]);  
  390.     av_free(picture);  
  391.     if (tmp_picture) {  
  392.         av_free(tmp_picture->data[0]);  
  393.         av_free(tmp_picture);  
  394.     }  
  395.     av_free(video_outbuf);  
  396. }  
  397.   
  398. /**************************************************************/  
  399. /* media file output */  
  400.   
  401. int main(int argc, char **argv)  
  402. {  
  403.     const char *filename;  
  404.     AVOutputFormat *fmt;  
  405.     AVFormatContext *oc;  
  406.     AVStream *audio_st, *video_st;  
  407.     double audio_pts, video_pts;  
  408.     int i;  
  409.   
  410.     /* initialize libavcodec, and register all codecs and formats */  
  411.     av_register_all();  
  412.   
  413.     if (argc != 2) {  
  414.         printf("usage: %s output_file\n"  
  415.                "API example program to output a media file with libavformat.\n"  
  416.                "The output format is automatically guessed according to the file extension.\n"  
  417.                "Raw images can also be output by using '%%d' in the filename\n"  
  418.                "\n", argv[0]);  
  419.         return 1;  
  420.     }  
  421.   
  422.     filename = argv[1];  
  423.   
  424.     /* allocate the output media context */  
  425.     avformat_alloc_output_context2(&oc, NULL, NULL, filename);  
  426.     if (!oc) {  
  427.         printf("Could not deduce output format from file extension: using MPEG.\n");  
  428.         avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);  
  429.     }  
  430.     if (!oc) {  
  431.         return 1;  
  432.     }  
  433.     fmt = oc->oformat;  
  434.   
  435.     /* add the audio and video streams using the default format codecs 
  436.        and initialize the codecs */  
  437.     video_st = NULL;  
  438.     audio_st = NULL;  
  439.     if (fmt->video_codec != CODEC_ID_NONE) {  
  440.         video_st = add_video_stream(oc, fmt->video_codec);  
  441.     }  
  442.     if (fmt->audio_codec != CODEC_ID_NONE) {  
  443.         audio_st = add_audio_stream(oc, fmt->audio_codec);  
  444.     }  
  445.   
  446.     av_dump_format(oc, 0, filename, 1);  
  447.   
  448.     /* now that all the parameters are set, we can open the audio and 
  449.        video codecs and allocate the necessary encode buffers */  
  450.     if (video_st)  
  451.         open_video(oc, video_st);  
  452.     if (audio_st)  
  453.         open_audio(oc, audio_st);  
  454.   
  455.     /* open the output file, if needed */  
  456.     if (!(fmt->flags & AVFMT_NOFILE)) {  
  457.         if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {  
  458.             fprintf(stderr, "Could not open '%s'\n", filename);  
  459.             return 1;  
  460.         }  
  461.     }  
  462.   
  463.     /* write the stream header, if any */  
  464.     av_write_header(oc);  
  465.     picture->pts = 0;  
  466.     for(;;) {  
  467.         /* compute current audio and video time */  
  468.         if (audio_st)  
  469.             audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;  
  470.         else  
  471.             audio_pts = 0.0;  
  472.   
  473.         if (video_st)  
  474.             video_pts = (double)video_st->pts.val * video_st->time_base.num / video_st->time_base.den;  
  475.         else  
  476.             video_pts = 0.0;  
  477.   
  478.         if ((!audio_st || audio_pts >= STREAM_DURATION) &&  
  479.             (!video_st || video_pts >= STREAM_DURATION))  
  480.             break;  
  481.   
  482.         /* write interleaved audio and video frames */  
  483.         if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {  
  484.             write_audio_frame(oc, audio_st);  
  485.         } else {  
  486.             write_video_frame(oc, video_st);  
  487.             picture->pts++;  
  488.         }  
  489.     }  
  490.   
  491.   
  492.     av_write_trailer(oc);  
  493.   
  494.     /* close each codec */  
  495.     if (video_st)  
  496.         close_video(oc, video_st);  
  497.     if (audio_st)  
  498.         close_audio(oc, audio_st);  
  499.   
  500.     /* free the streams */  
  501.     for(i = 0; i < oc->nb_streams; i++) {  
  502.         av_freep(&oc->streams[i]->codec);  
  503.         av_freep(&oc->streams[i]);  
  504.     }  
  505.   
  506.     if (!(fmt->flags & AVFMT_NOFILE)) {  
  507.         /* close the output file */  
  508.         avio_close(oc->pb);  
  509.     }  
  510.   
  511.     /* free the stream */  
  512.     av_free(oc);  
  513.   
  514.     return 0;  
  515. }  


参考:http://www.ylmf.net/ubuntu/tips/2010122919090_3.html

            http://hi.baidu.com/ccqi0000/blog/item/d39fb21f1d5157a84aedbcb1.html

0 0
原创粉丝点击