FFMpeg写MP4文件例子分析

  • Post author:
  • Post category:其他



http://blog.csdn.net/eightdegree/article/details/7425811

这段时间看了FFMpeg提供的例子muxing.c,我略微修改了下源代码,使其生成一个MP4文件,音频使用AAC编码,视频使用H.264编码。代码很简单,我就不做说明了,代码如下。

以后我们继续写如何将DirectShow中采集的音视频数据编码并生成MP4文件。



  1. /* 5 seconds stream duration */





  2. #define STREAM_DURATION   5.0





  3. #define STREAM_FRAME_RATE 25 /* 25 images/s */





  4. #define STREAM_NB_FRAMES  ((int)(STREAM_DURATION * STREAM_FRAME_RATE))





  5. #define STREAM_PIX_FMT PIX_FMT_YUV420P /* default pix_fmt */






  6. static




    int


    sws_flags = SWS_BICUBIC;




  7. /**************************************************************/





  8. /* audio output */






  9. static




    float


    t, tincr, tincr2;



  10. static


    int16_t *samples;



  11. static


    uint8_t *audio_outbuf;



  12. static




    int


    audio_outbuf_size;



  13. static




    int


    audio_input_frame_size;




  14. /*



  15. * add an audio output stream



  16. */





  17. static


    AVStream *add_audio_stream(AVFormatContext *oc,


    enum


    CodecID codec_id)


  18. {

  19. AVCodecContext *c;

  20. AVStream *st;


  21. st = avformat_new_stream(oc, NULL);


  22. if


    (!st) {


  23. fprintf(stderr,

    “Could not alloc stream\n”


    );


  24. exit(1);

  25. }

  26. st->id = 1;


  27. c = st->codec;

  28. c->codec_id = codec_id;

  29. c->codec_type = AVMEDIA_TYPE_AUDIO;



  30. /* put sample parameters */




  31. c->sample_fmt = AV_SAMPLE_FMT_S16;

  32. c->bit_rate = 64000;

  33. c->sample_rate = 44100;

  34. c->channels = 2;



  35. // some formats want stream headers to be separate





  36. if


    (oc->oformat->flags & AVFMT_GLOBALHEADER)


  37. c->flags |= CODEC_FLAG_GLOBAL_HEADER;



  38. return


    st;


  39. }



  40. static




    void


    open_audio(AVFormatContext *oc, AVStream *st)


  41. {

  42. AVCodecContext *c;

  43. AVCodec *codec;


  44. c = st->codec;



  45. /* find the audio encoder */




  46. codec = avcodec_find_encoder(c->codec_id);


  47. if


    (!codec) {


  48. fprintf(stderr,

    “codec not found\n”


    );


  49. exit(1);

  50. }



  51. /* open it */





  52. if


    (avcodec_open(c, codec) < 0) {


  53. fprintf(stderr,

    “could not open codec\n”


    );


  54. exit(1);

  55. }



  56. /* init signal generator */




  57. t = 0;

  58. tincr = 2 * M_PI * 110.0 / c->sample_rate;


  59. /* increment frequency by 110 Hz per second */




  60. tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;


  61. audio_outbuf_size = 10000;

  62. audio_outbuf = (uint8_t *)av_malloc(audio_outbuf_size);



  63. /* ugly hack for PCM codecs (will be removed ASAP with new PCM



  64. support to compute the input frame size in samples */





  65. if


    (c->frame_size <= 1) {


  66. audio_input_frame_size = audio_outbuf_size / c->channels;


  67. switch


    (st->codec->codec_id) {



  68. case


    CODEC_ID_PCM_S16LE:



  69. case


    CODEC_ID_PCM_S16BE:



  70. case


    CODEC_ID_PCM_U16LE:



  71. case


    CODEC_ID_PCM_U16BE:


  72. audio_input_frame_size >>= 1;


  73. break


    ;



  74. default


    :



  75. break


    ;


  76. }

  77. }

    else


    {


  78. audio_input_frame_size = c->frame_size;

  79. }

  80. samples = (int16_t *)av_malloc(audio_input_frame_size * 2 * c->channels);

  81. }



  82. /* prepare a 16 bit dummy audio frame of ‘frame_size’ samples and



  83. ‘nb_channels’ channels */





  84. static




    void


    get_audio_frame(int16_t *samples,


    int


    frame_size,


    int


    nb_channels)


  85. {


  86. int


    j, i, v;


  87. int16_t *q;


  88. q = samples;


  89. for


    (j = 0; j < frame_size; j++) {


  90. v = (

    int


    )(sin(t) * 10000);



  91. for


    (i = 0; i < nb_channels; i++)


  92. *q++ = v;

  93. t += tincr;

  94. tincr += tincr2;

  95. }

  96. }



  97. static




    void


    write_audio_frame(AVFormatContext *oc, AVStream *st)


  98. {

  99. AVCodecContext *c;

  100. AVPacket pkt;

  101. av_init_packet(&pkt);


  102. c = st->codec;


  103. get_audio_frame(samples, audio_input_frame_size, c->channels);


  104. pkt.size = avcodec_encode_audio(c, audio_outbuf, audio_outbuf_size, samples);



  105. if


    (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)


  106. pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);

  107. pkt.flags |= AV_PKT_FLAG_KEY;

  108. pkt.stream_index = st->index;

  109. pkt.data = audio_outbuf;



  110. /* write the compressed frame in the media file */





  111. if


    (av_interleaved_write_frame(oc, &pkt) != 0) {


  112. fprintf(stderr,

    “Error while writing audio frame\n”


    );


  113. exit(1);

  114. }

  115. }



  116. static




    void


    close_audio(AVFormatContext *oc, AVStream *st)


  117. {

  118. avcodec_close(st->codec);


  119. av_free(samples);

  120. av_free(audio_outbuf);

  121. }



  122. /**************************************************************/





  123. /* video output */






  124. static


    AVFrame *picture, *tmp_picture;



  125. static


    uint8_t *video_outbuf;



  126. static




    int


    frame_count, video_outbuf_size;




  127. /* add a video output stream */





  128. static


    AVStream *add_video_stream(AVFormatContext *oc,


    enum


    CodecID codec_id)


  129. {

  130. AVCodecContext *c;

  131. AVStream *st;

  132. AVCodec *codec;


  133. st = avformat_new_stream(oc, NULL);


  134. if


    (!st) {


  135. fprintf(stderr,

    “Could not alloc stream\n”


    );


  136. exit(1);

  137. }


  138. c = st->codec;



  139. /* find the video encoder */




  140. codec = avcodec_find_encoder(codec_id);


  141. if


    (!codec) {


  142. fprintf(stderr,

    “codec not found\n”


    );


  143. exit(1);

  144. }

  145. avcodec_get_context_defaults3(c, codec);


  146. c->codec_id = codec_id;



  147. /* put sample parameters */




  148. c->bit_rate =

    /*400000*/


    3000000;



  149. /* resolution must be a multiple of two */




  150. c->width =

    /*352*/


    640;


  151. c->height =

    /*288*/


    480;



  152. /* time base: this is the fundamental unit of time (in seconds) in terms



  153. of which frame timestamps are represented. for fixed-fps content,



  154. timebase should be 1/framerate and timestamp increments should be



  155. identically 1. */




  156. c->time_base.den = STREAM_FRAME_RATE;

  157. c->time_base.num = 1;

  158. c->gop_size = 12;

    /* emit one intra frame every twelve frames at most */




  159. c->pix_fmt = STREAM_PIX_FMT;


  160. if


    (c->codec_id == CODEC_ID_MPEG2VIDEO) {



  161. /* just for testing, we also add B frames */




  162. c->max_b_frames = 2;

  163. }


  164. if


    (c->codec_id == CODEC_ID_MPEG1VIDEO){



  165. /* Needed to avoid using macroblocks in which some coeffs overflow.



  166. This does not happen with normal video, it just happens here as



  167. the motion of the chroma plane does not match the luma plane. */




  168. c->mb_decision=2;

  169. }


  170. // some formats want stream headers to be separate





  171. if


    (oc->oformat->flags & AVFMT_GLOBALHEADER)


  172. c->flags |= CODEC_FLAG_GLOBAL_HEADER;





  173. return


    st;


  174. }



  175. static


    AVFrame *alloc_picture(


    enum


    PixelFormat pix_fmt,


    int


    width,


    int


    height)


  176. {

  177. AVFrame *picture;

  178. uint8_t *picture_buf;


  179. int


    size;



  180. picture = avcodec_alloc_frame();


  181. if


    (!picture)



  182. return


    NULL;


  183. size = avpicture_get_size(pix_fmt, width, height);

  184. picture_buf = (uint8_t *)av_malloc(size);


  185. if


    (!picture_buf) {


  186. av_free(picture);


  187. return


    NULL;


  188. }

  189. avpicture_fill((AVPicture *)picture, picture_buf,

  190. pix_fmt, width, height);


  191. return


    picture;


  192. }



  193. static




    void


    open_video(AVFormatContext *oc, AVStream *st)


  194. {

  195. AVCodec *codec;

  196. AVCodecContext *c;


  197. c = st->codec;



  198. /* find the video encoder */




  199. codec = avcodec_find_encoder(c->codec_id);


  200. if


    (!codec) {


  201. fprintf(stderr,

    “codec not found\n”


    );


  202. exit(1);

  203. }



  204. /* open the codec */





  205. if


    (avcodec_open(c, codec) < 0) {


  206. fprintf(stderr,

    “could not open codec\n”


    );


  207. exit(1);

  208. }


  209. video_outbuf = NULL;


  210. if


    (!(oc->oformat->flags & AVFMT_RAWPICTURE)) {



  211. /* allocate output buffer */





  212. /* XXX: API change will be done */





  213. /* buffers passed into lav* can be allocated any way you prefer,



  214. as long as they’re aligned enough for the architecture, and



  215. they’re freed appropriately (such as using av_free for buffers



  216. allocated with av_malloc) */




  217. video_outbuf_size = 200000;

  218. video_outbuf = (uint8_t *)av_malloc(video_outbuf_size);

  219. }



  220. /* allocate the encoded raw picture */




  221. picture = alloc_picture(c->pix_fmt, c->width, c->height);


  222. if


    (!picture) {


  223. fprintf(stderr,

    “Could not allocate picture\n”


    );


  224. exit(1);

  225. }



  226. /* if the output format is not YUV420P, then a temporary YUV420P



  227. picture is needed too. It is then converted to the required



  228. output format */




  229. tmp_picture = NULL;


  230. if


    (c->pix_fmt != PIX_FMT_YUV420P) {


  231. tmp_picture = alloc_picture(PIX_FMT_YUV420P, c->width, c->height);


  232. if


    (!tmp_picture) {


  233. fprintf(stderr,

    “Could not allocate temporary picture\n”


    );


  234. exit(1);

  235. }

  236. }

  237. }



  238. /* prepare a dummy image */





  239. static




    void


    fill_yuv_image(AVFrame *pict,


    int


    frame_index,


    int


    width,


    int


    height)


  240. {


  241. int


    x, y, i;



  242. i = frame_index;



  243. /* Y */





  244. for


    (y = 0; y < height; y++) {



  245. for


    (x = 0; x < width; x++) {


  246. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;

  247. }

  248. }



  249. /* Cb and Cr */





  250. for


    (y = 0; y < height/2; y++) {



  251. for


    (x = 0; x < width/2; x++) {


  252. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;

  253. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;

  254. }

  255. }

  256. }



  257. static




    void


    write_video_frame(AVFormatContext *oc, AVStream *st)


  258. {


  259. int


    out_size, ret;


  260. AVCodecContext *c;


  261. static




    struct


    SwsContext *img_convert_ctx;



  262. c = st->codec;



  263. if


    (frame_count >= STREAM_NB_FRAMES) {



  264. /* no more frame to compress. The codec has a latency of a few



  265. frames if using B frames, so we get the last frames by



  266. passing the same picture again */




  267. }

    else


    {



  268. if


    (c->pix_fmt != PIX_FMT_YUV420P) {



  269. /* as we only generate a YUV420P picture, we must convert it



  270. to the codec pixel format if needed */





  271. if


    (img_convert_ctx == NULL) {


  272. img_convert_ctx = sws_getContext(c->width, c->height,

  273. PIX_FMT_YUV420P,

  274. c->width, c->height,

  275. c->pix_fmt,

  276. sws_flags, NULL, NULL, NULL);


  277. if


    (img_convert_ctx == NULL) {


  278. fprintf(stderr,

    “Cannot initialize the conversion context\n”


    );


  279. exit(1);

  280. }

  281. }

  282. fill_yuv_image(tmp_picture, frame_count, c->width, c->height);

  283. sws_scale(img_convert_ctx, tmp_picture->data, tmp_picture->linesize,

  284. 0, c->height, picture->data, picture->linesize);

  285. }

    else


    {


  286. fill_yuv_image(picture, frame_count, c->width, c->height);

  287. }

  288. }




  289. if


    (oc->oformat->flags & AVFMT_RAWPICTURE) {



  290. /* raw video case. The API will change slightly in the near



  291. future for that. */




  292. AVPacket pkt;

  293. av_init_packet(&pkt);


  294. pkt.flags |= AV_PKT_FLAG_KEY;

  295. pkt.stream_index = st->index;

  296. pkt.data = (uint8_t *)picture;

  297. pkt.size =

    sizeof


    (AVPicture);



  298. ret = av_interleaved_write_frame(oc, &pkt);

  299. }

    else


    {



  300. /* encode the image */




  301. out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);


  302. /* if zero size, it means the image was buffered */





  303. if


    (out_size > 0) {


  304. AVPacket pkt;

  305. av_init_packet(&pkt);



  306. if


    (c->coded_frame->pts != AV_NOPTS_VALUE)


  307. pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);


  308. if


    (c->coded_frame->key_frame)


  309. pkt.flags |= AV_PKT_FLAG_KEY;

  310. pkt.stream_index = st->index;

  311. pkt.data = video_outbuf;

  312. pkt.size = out_size;



  313. //          printf(“pts %d \n”, c->coded_frame->pts);






  314. /* write the compressed frame in the media file */




  315. ret = av_interleaved_write_frame(oc, &pkt);

  316. }

    else


    {


  317. ret = 0;

  318. }

  319. }


  320. if


    (ret != 0) {


  321. fprintf(stderr,

    “Error while writing video frame\n”


    );


  322. exit(1);

  323. }

  324. frame_count++;

  325. }



  326. static




    void


    close_video(AVFormatContext *oc, AVStream *st)


  327. {

  328. avcodec_close(st->codec);

  329. av_free(picture->data[0]);

  330. av_free(picture);


  331. if


    (tmp_picture) {


  332. av_free(tmp_picture->data[0]);

  333. av_free(tmp_picture);

  334. }

  335. av_free(video_outbuf);

  336. }



  337. /**************************************************************/





  338. /* media file output */







  339. int


    main(


    int


    argc,


    char


    **argv)


  340. {


  341. const




    char


    *filename;


  342. AVOutputFormat *fmt;

  343. AVFormatContext *oc;

  344. AVStream *audio_st, *video_st;


  345. double


    audio_pts, video_pts;



  346. int


    i;




  347. /* initialize libavcodec, and register all codecs and formats */




  348. av_register_all();



  349. #if 0





  350. if


    (argc != 2) {


  351. printf(

    “usage: %s output_file\n”





  352. “API example program to output a media file with libavformat.\n”





  353. “The output format is automatically guessed according to the file extension.\n”





  354. “Raw images can also be output by using ‘%%d’ in the filename\n”





  355. “\n”


    , argv[0]);



  356. return


    1;


  357. }


  358. filename = argv[1];


  359. #endif






  360. //#define RTMP_STREAM





  361. #ifdef RTMP_STREAM




  362. filename =

    “rtmp://192.168.0.239/live/livestream”


    ;



  363. #else




  364. filename =

    “1.mp4”


    ;



  365. #endif






  366. /* allocate the output media context */




  367. avformat_alloc_output_context2(&oc, NULL, NULL, filename);


  368. if


    (!oc)


  369. {

  370. printf(

    “Could not deduce output format from file extension: using MPEG.\n”


    );


  371. avformat_alloc_output_context2(&oc, NULL,

    /*”mpeg”*/


    “flv”


    , filename);


  372. }



  373. if


    (!oc)


  374. {


  375. return


    1;


  376. }



  377. // 强制指定 264 编码




  378. oc->oformat->video_codec = CODEC_ID_H264;

  379. oc->oformat->audio_codec = CODEC_ID_AAC;


  380. fmt = oc->oformat;



  381. /* add the audio and video streams using the default format codecs



  382. and initialize the codecs */




  383. video_st = NULL;

  384. audio_st = NULL;


  385. if


    (fmt->video_codec != CODEC_ID_NONE) {


  386. video_st = add_video_stream(oc, fmt->video_codec);

  387. }


  388. if


    (fmt->audio_codec != CODEC_ID_NONE) {


  389. audio_st = add_audio_stream(oc, fmt->audio_codec);

  390. }


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



  392. /* now that all the parameters are set, we can open the audio and



  393. video codecs and allocate the necessary encode buffers */





  394. if


    (video_st)


  395. open_video(oc, video_st);


  396. if


    (audio_st)


  397. open_audio(oc, audio_st);



  398. /* open the output file, if needed */





  399. if


    (!(fmt->flags & AVFMT_NOFILE)) {



  400. if


    (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {


  401. fprintf(stderr,

    “Could not open ‘%s’\n”


    , filename);



  402. return


    1;


  403. }

  404. }



  405. /* write the stream header, if any */




  406. avformat_write_header(oc, NULL);

  407. picture->pts = 0;


  408. for


    (;;)


  409. {


  410. /* compute current audio and video time */





  411. if


    (audio_st)


  412. audio_pts = (

    double


    )audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;



  413. else




  414. audio_pts = 0.0;



  415. if


    (video_st)


  416. video_pts = (

    double


    )video_st->pts.val * video_st->time_base.num / video_st->time_base.den;



  417. else




  418. video_pts = 0.0;



  419. if


    ((!audio_st || audio_pts >= STREAM_DURATION) &&


  420. (!video_st || video_pts >= STREAM_DURATION))


  421. break


    ;




  422. /* write interleaved audio and video frames */





  423. if


    (!video_st || (video_st && audio_st && audio_pts < video_pts)) {


  424. write_audio_frame(oc, audio_st);


  425. }

    else


    {


  426. write_video_frame(oc, video_st);


  427. picture->pts++;

  428. }

  429. }



  430. /* write the trailer, if any.  the trailer must be written



  431. * before you close the CodecContexts open when you wrote the



  432. * header; otherwise write_trailer may try to use memory that



  433. * was freed on av_codec_close() */




  434. av_write_trailer(oc);



  435. /* close each codec */





  436. if


    (video_st)


  437. close_video(oc, video_st);


  438. if


    (audio_st)


  439. close_audio(oc, audio_st);



  440. /* free the streams */





  441. for


    (i = 0; i < oc->nb_streams; i++) {


  442. av_freep(&oc->streams[i]->codec);

  443. av_freep(&oc->streams[i]);

  444. }



  445. if


    (!(fmt->flags & AVFMT_NOFILE)) {



  446. /* close the output file */




  447. avio_close(oc->pb);

  448. }



  449. /* free the stream */




  450. av_free(oc);



  451. return


    0;


  452. }