必威体育Betway必威体育官网
当前位置:首页 > IT技术

关于视频H264编解码的应用实现

时间:2019-09-29 01:43:16来源:IT技术作者:seo实验室小编阅读:70次「手机版」
 

h264编码

http://blog.csdn.net/scalerzhangjie/article/details/8273410

项目要用到视频编解码,最近半个月都在搞,说实话真是走了很多弯路,浪费了很多时间。将自己的最终成果记录于此,期望会给其他人提供些许帮助。

参考教程

http://ffmpeg.org/trac/ffmpeg/wiki/ubuntuCompilationGuide安装ffmpeg和x264,官方权威教程(注意不要用命令行安装,会少很多库的。编译安装最保险)

http://blog.csdn.net/zgyulongfei/article/details/7526249采集与编码的教程

http://www.cnblogs.com/fojian/archive/2012/09/01/2666627.html编码的好文章

http://my.oschina.net/u/555701/blog/56616?p=2#comments-解码的好文章

整体过程流程如下:

显而易见,整个过程分为三个部分:采集、编码、解码。

1.采集视频

我是利用USB摄像头采集视频的,我的摄像头只支持YUV422格式的图像采集,因为x264编码库只能编码YUV420P(planar)格式,因此在采集到yuv422格式的图像数据后要变换成yuv420p格式。

采集视频使用官方的那个采集程序,稍加修改即可,具体点说就是修改

static void process_image (const char * p) ;函数

参数p指向一帧采集图像的yuv数据。

关于YUV格式和RGB格式,网上有很多教程。

在这儿,我讲一下自己的理解。

假设有一幅4*4分辨率的图片,如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

每个像素是由YUV数据构成,假设如下:

Y1

U1

V1

Y2

U2

V2

Y3

U3

V3

Y4

U4

V4

Y5

U5

V5

Y6

U6

V6

Y7

U7

V7

Y8

U8

V8

Y9

U9

V9

Y10

U10

V10

Y11

U11

V11

Y12

U12

V12

Y13

U13

V13

Y14

U14

V14

Y15

U15

V15

Y16

U16

V16

YUV422图像是这样的,每个像素采集Y,UV每隔两个像素采集一次:

Packed格式的YUV420是这样的,每个像素采集Y,UV隔行采集,每行是每两个像素采集一次:

以上几种格式存储就是按照从左到右,从上到下顺序存储的。

我想要得到是planar格式的YUV420,即在一段连续的内存中,先存储所有的Y,接着是所有的U,最后是所有的V。

修改后的process_image函数如下:

[cpp]view plaincopy 在CODE上查看代码片派生到我的代码片

  1. staticvoid
  2. process_image(constchar*p)
  3. {
  4. //fputc('.',stdout);
  5. //convertyuv422toyuv420p
  6. char*y=yuv420p;
  7. char*u=&yuv420p[IMAGE_WIDTH*IMAGE_HEIGHT];
  8. char*v=&yuv420p[IMAGE_WIDTH*IMAGE_HEIGHT+IMAGE_WIDTH*IMAGE_HEIGHT/4];
  9. inti=0,j=0,l=0;
  10. for(j=0;j<IMAGE_HEIGHT;j++)
  11. for(i=0;i<IMAGE_WIDTH*2;i++,l++){
  12. if(j%2==0){//evenlinetosampleU-Chriminance
  13. if(l==1){//sampleU-Chriminance
  14. *u=p[j*IMAGE_WIDTH*2+i];
  15. u++;
  16. }
  17. elseif(l==3){//abandonV-Chroma
  18. l=-1;
  19. continue;
  20. }
  21. else{
  22. *y=p[j*IMAGE_WIDTH*2+i];
  23. ++y;
  24. }
  25. }
  26. elseif(j%2==1){//oddlinestosampleV-Chroma
  27. if(l==1){
  28. continue;
  29. }
  30. elseif(l==3){
  31. l=-1;
  32. *v=p[j*IMAGE_WIDTH*2+i];
  33. ++v;
  34. }
  35. else{
  36. *y=p[j*IMAGE_WIDTH*2+i];
  37. ++y;
  38. }
  39. }
  40. }
  41. fwrite(yuv420p,IMAGE_WIDTH*IMAGE_HEIGHT*3>>1,1,fp_yuv420p);
  42. fflush(stdout);
  43. }

2.编码

采用x264编码库编码yuv420p文件。

程序如下:

[cpp]view plaincopy 在CODE上查看代码片派生到我的代码片

  1. #include<stdint.h>
  2. #include<x264.h>
  3. #include<stdio.h>
  4. #include<unistd.h>
  5. #include<fcntl.h>
  6. #include<stdlib.h>
  7. #include<string.h>
  8. #definedEBUG0
  9. #defineCLEAR(x)(memset((&x),0,sizeof(x)))
  10. #defineIMAGE_WIDTH320
  11. #defineIMAGE_HEIGHT240
  12. #defineENCODER_PRESET"veryfast"
  13. #defineENCODER_TUNE"zerolatency"
  14. #defineENCODER_profile"baseline"
  15. #defineENCODER_colorSPACEX264_CSP_I420
  16. typedefstructmy_x264_encoder{
  17. x264_param_t*x264_parameter;
  18. charparameter_preset[20];
  19. charparameter_tune[20];
  20. charparameter_profile[20];
  21. x264_t*x264_encoder;
  22. x264_picture_t*yuv420p_picture;
  23. longcolorspace;
  24. unsignedchar*yuv;
  25. x264_nal_t*nal;
  26. }my_x264_encoder;
  27. char*read_filename="yuv420p.yuv";
  28. char*write_filename="encode.h264";
  29. int
  30. main(intargc,char**argv){
  31. intret;
  32. intfd_read,fd_write;
  33. my_x264_encoder*encoder=(my_x264_encoder*)malloc(sizeof(my_x264_encoder));
  34. if(!encoder){
  35. printf("cannotmallocmy_x264_encoder!\n");
  36. exit(EXIT_FAILURE);
  37. }
  38. CLEAR(*encoder);
  39. /****************************************************************************
  40. *Advancedparameterhandlingfunctions
  41. ****************************************************************************/
  42. /*Thesefunctionsexposethefullpowerofx264'spreset-tune-profilesystemfor
  43. *easyadjustmentoflargenumbers//free(encoder->yuv420p_picture);ofinternalparameters.
  44. *
  45. *Inordertoreplicatex264CLI'soptionhandling,thesefunctionsMUSTbecalled
  46. *inthefollowingorder:
  47. *1)x264_param_default_preset
  48. *2)Customuseroptions(viaparam_parseordirectlyassignedvariables)
  49. *3)x264_param_APPly_fastfirstpass
  50. *4)x264_param_apply_profile
  51. *
  52. *Additionally,x264CLIdoesnotapplystep3ifthepresetchosenis"placebo"
  53. *or--slow-firstpassisset.*/
  54. strcpy(encoder->parameter_preset,ENCODER_PRESET);
  55. strcpy(encoder->parameter_tune,ENCODER_TUNE);
  56. encoder->x264_parameter=(x264_param_t*)malloc(sizeof(x264_param_t));
  57. if(!encoder->x264_parameter){
  58. printf("mallocx264_parameterERROR!\n");
  59. exit(EXIT_FAILURE);
  60. }
  61. CLEAR(*(encoder->x264_parameter));
  62. x264_param_default(encoder->x264_parameter);
  63. if((ret=x264_param_default_preset(encoder->x264_parameter,encoder->parameter_preset,encoder->parameter_tune))<0){
  64. printf("x264_param_default_preseterror!\n");
  65. exit(EXIT_FAILURE);
  66. }
  67. encoder->x264_parameter->i_fps_den=1;
  68. encoder->x264_parameter->i_fps_num=25;
  69. encoder->x264_parameter->i_width=IMAGE_WIDTH;
  70. encoder->x264_parameter->i_height=IMAGE_HEIGHT;
  71. encoder->x264_parameter->i_threads=1;
  72. encoder->x264_parameter->i_keyint_max=25;
  73. encoder->x264_parameter->b_intra_refresh=1;
  74. encoder->x264_parameter->b_annexb=1;
  75. strcpy(encoder->parameter_profile,ENCODER_PROFILE);
  76. if((ret=x264_param_apply_profile(encoder->x264_parameter,encoder->parameter_profile))<0){
  77. printf("x264_param_apply_profileerror!\n");
  78. exit(EXIT_FAILURE);
  79. }
  80. #ifDEBUG
  81. printf("Line--------%d\n",__LINE__);
  82. #endif
  83. encoder->x264_encoder=x264_encoder_open(encoder->x264_parameter);
  84. encoder->colorspace=ENCODER_COLORSPACE;
  85. #ifDEBUG
  86. printf("Line--------%d\n",__LINE__);
  87. #endif
  88. encoder->yuv420p_picture=(x264_picture_t*)malloc(sizeof(x264_picture_t));
  89. if(!encoder->yuv420p_picture){
  90. printf("mallocencoder->yuv420p_pictureerror!\n");
  91. exit(EXIT_FAILURE);
  92. }
  93. if((ret=x264_picture_alloc(encoder->yuv420p_picture,encoder->colorspace,IMAGE_WIDTH,IMAGE_HEIGHT))<0){
  94. printf("ret=%d\n",ret);
  95. printf("x264_picture_allocerror!\n");
  96. exit(EXIT_FAILURE);
  97. }
  98. encoder->yuv420p_picture->img.i_csp=encoder->colorspace;
  99. encoder->yuv420p_picture->img.i_plane=3;
  100. encoder->yuv420p_picture->i_type=X264_TYPE_AUTO;
  101. #ifDEBUG
  102. printf("Line--------%d\n",__LINE__);
  103. #endif
  104. encoder->yuv=(uint8_t*)malloc(IMAGE_WIDTH*IMAGE_HEIGHT*3/2);
  105. if(!encoder->yuv){
  106. printf("mallocyuverror!\n");
  107. exit(EXIT_FAILURE);
  108. }
  109. CLEAR(*(encoder->yuv));
  110. #ifDEBUG
  111. printf("Line--------%d\n",__LINE__);
  112. #endif
  113. encoder->yuv420p_picture->img.plane[0]=encoder->yuv;
  114. encoder->yuv420p_picture->img.plane[1]=encoder->yuv+IMAGE_WIDTH*IMAGE_HEIGHT;
  115. encoder->yuv420p_picture->img.plane[2]=encoder->yuv+IMAGE_WIDTH*IMAGE_HEIGHT+IMAGE_WIDTH*IMAGE_HEIGHT/4;
  116. if((fd_read=open(read_filename,O_RDONLY))<0){
  117. printf("cannotopeninputfile!\n");
  118. exit(EXIT_FAILURE);
  119. }
  120. if((fd_write=open(write_filename,O_WRONLY|O_append|O_CREAT,0777))<0){
  121. printf("cannotopenoutputfile!\n");
  122. exit(EXIT_FAILURE);
  123. }
  124. #ifDEBUG
  125. printf("Line--------%d\n",__LINE__);
  126. #endif
  127. intn_nal;
  128. x264_picture_tpic_out;
  129. x264_nal_t*my_nal;
  130. encoder->nal=(x264_nal_t*)malloc(sizeof(x264_nal_t));
  131. if(!encoder->nal){
  132. printf("mallocx264_nal_terror!\n");
  133. exit(EXIT_FAILURE);
  134. }
  135. CLEAR(*(encoder->nal));
  136. while(read(fd_read,encoder->yuv,IMAGE_WIDTH*IMAGE_HEIGHT*3/2)>0){
  137. encoder->yuv420p_picture->i_pts++;
  138. if((ret=x264_encoder_encode(encoder->x264_encoder,&encoder->nal,&n_nal,encoder->yuv420p_picture,&pic_out))<0){
  139. printf("x264_encoder_encodeerror!\n");
  140. exit(EXIT_FAILURE);
  141. }
  142. unsignedintlength=0;
  143. for(my_nal=encoder->nal;my_nal<encoder->nal+n_nal;++my_nal){
  144. write(fd_write,my_nal->p_payload,my_nal->i_payload);
  145. length+=my_nal->i_payload;
  146. }
  147. printf("length=%d\n",length);
  148. }
  149. /*clean_upfunctions*/
  150. //x264_picture_clean(encoder->yuv420p_picture);
  151. //free(encoder->nal);//????confusedconflictwithx264_encoder_close(encoder->x264_encoder);
  152. free(encoder->yuv);
  153. free(encoder->yuv420p_picture);
  154. free(encoder->x264_parameter);
  155. x264_encoder_close(encoder->x264_encoder);
  156. free(encoder);
  157. close(fd_read);
  158. close(fd_write);
  159. return0;
  160. }

3.解码

利用ffmpeg进行解码

程序如下:

[cpp]view plaincopy 在CODE上查看代码片派生到我的代码片

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. #include<fcntl.h>
  5. #include<unistd.h>
  6. #include<libavcodec/avcodec.h>
  7. #include<libavformat/avformat.h>
  8. #include<libavutil/mathematics.h>
  9. #defineDECODED_OUTPUT_FORMATAV_PIX_FMT_YUV420P
  10. #defineINPUT_FILE_NAME"encode.h264"
  11. #defineOUTPUT_FILE_NAME"decode.yuv"
  12. #defineIMAGE_WIDTH320
  13. #defineIMAGE_HEIGHT240
  14. void
  15. error_handle(constchar*errorInfo){
  16. printf("%serror!\n",errorInfo);
  17. exit(EXIT_FAILURE);
  18. }
  19. int
  20. main(intargc,char**argv){
  21. intwrite_fd,ret,videoStream;
  22. AVFormatcontext*formatContext=NULL;
  23. AVCodec*codec;
  24. AVCodecContext*codecContext;
  25. AVFrame*decodedFrame;
  26. AVPacketpacket;
  27. uint8_t*decodedBuffer;
  28. unsignedintdecodedBufferSize;
  29. intfinishedFrame;
  30. av_register_all();
  31. write_fd=open(OUTPUT_FILE_NAME,O_RDWR|O_CREAT,0666);
  32. if(write_fd<0){
  33. perror("open");
  34. exit(1);
  35. }
  36. ret=avformat_open_input(&formatContext,INPUT_FILE_NAME,NULL,NULL);
  37. if(ret<0)
  38. error_handle("avformat_open_inputerror");
  39. ret=avformat_find_stream_info(formatContext,NULL);
  40. if(ret<0)
  41. error_handle("av_find_stream_info");
  42. videoStream=0;
  43. codecContext=formatContext->streams[videoStream]->codec;
  44. codec=avcodec_find_decoder(AV_CODEC_ID_H264);
  45. if(codec==NULL)
  46. error_handle("avcodec_find_decodererror!\n");
  47. ret=avcodec_open2(codecContext,codec,NULL);
  48. if(ret<0)
  49. error_handle("avcodec_open2");
  50. decodedFrame=avcodec_alloc_frame();
  51. if(!decodedFrame)
  52. error_handle("avcodec_alloc_frame!");
  53. decodedBufferSize=avpicture_get_size(DECODED_OUTPUT_FORMAT,IMAGE_WIDTH,IMAGE_HEIGHT);
  54. decodedBuffer=(uint8_t*)malloc(decodedBufferSize);
  55. if(!decodedBuffer)
  56. error_handle("mallocdecodedBuffererror!");
  57. av_init_packet(&packet);
  58. while(av_read_frame(formatContext,&packet)>=0){
  59. ret=avcodec_decode_video2(codecContext,decodedFrame,&finishedFrame,&packet);
  60. if(ret<0)
  61. error_handle("avcodec_decode_video2error!");
  62. if(finishedFrame){
  63. avpicture_layout((AVPicture*)decodedFrame,DECODED_OUTPUT_FORMAT,IMAGE_WIDTH,IMAGE_HEIGHT,decodedBuffer,decodedBufferSize);
  64. ret=write(write_fd,decodedBuffer,decodedBufferSize);
  65. if(ret<0)
  66. error_handle("writeyuvstreamerror!");
  67. }
  68. av_free_packet(&packet);
  69. }
  70. while(1){
  71. packet.data=NULL;
  72. packet.size=0;
  73. ret=avcodec_decode_video2(codecContext,decodedFrame,&finishedFrame,&packet);
  74. if(ret<=0&&(finishedFrame<=0))
  75. break;
  76. if(finishedFrame){
  77. avpicture_layout((AVPicture*)decodedFrame,DECODED_OUTPUT_FORMAT,IMAGE_WIDTH,IMAGE_HEIGHT,decodedBuffer,decodedBufferSize);
  78. ret=write(write_fd,decodedBuffer,decodedBufferSize);
  79. if(ret<0)
  80. error_handle("writeyuvstreamerror!");
  81. }
  82. av_free_packet(&packet);
  83. }
  84. avformat_close_input(&formatContext);
  85. free(decodedBuffer);
  86. av_free(decodedFrame);
  87. avcodec_close(codecContext);
  88. return0;
  89. }

结果:

1.利用USB摄像头采集的YUV420P,大小11.0MB,可以用pyuv播放器正常播放。

2.编码后的文件encode.h264,大小262.4kb,可用vlc播放器正常播放。

3.解码后的文件decode.yuv,大小11.0MB,可以用pyuv播放器正常播放。

相关文件在我的资源里,里面包含:

1.采集、编码、解码程序、对应的可执行程序和makefile文件;

2.Pyuv播放器(用于XP)

3. 实验文件-yuv420p.yuv 、encode.h264、 decode.yuv

4. 相关参考文档pdf版本

欢迎批评指正!

相关阅读

【人人早报】568期:多亏李世石的不懈努力,AlphaGo 的命

导读香港科技大学计算机科学硕士,中国科学技术大学科技与战略风云学会研究员,新浪围棋 6D。本文首发于“观察者”,原标题为“ 陈经:

Python 方法重载

python的方法重载有些特殊,在python中,如下的代码并不能实现方法重载: def Aa():     pass def Aa(a):     print(1) def

如何解决浏览网页出现http404错误问题

我最近发现一个问题,在浏览我经常浏览的一些网站时,浏览器总是提示http 404错误,无法找到文件。起初,以为是该网站在进行日常维护,打开

What is CRA?

What is CRA? 什么是CRA? 众所周知,sensor的效能与sensor

x264源码分析-threads参数

sprintf( s, " threads=%d", p->i_threads );最大值128 X264_THREAD_MAX。如果没有设置threads参数,x264根据当前CPU核数以及slice

分享到:

栏目导航

推荐阅读

热门阅读