1. Decode() 
  2. { 
  3. FILE * inpf; 
  4.  
  5. int nWrite; 
  6. int i,p; 
  7. int nalLen; 
  8. unsigned char* Buf; 
  9. int got_picture, consumed_bytes; 
  10. unsigned char *DisplayBuf; 
  11. DisplayBuf=(unsigned char *)malloc(60000); 
  12.  
  13. char outfile[] = "test.pgm"; 
  14.  
  15. //1.打开输入文件 
  16. inpf = fopen("test.264", "rb"); 
  17.  
  18. //outf = fopen("out.yuv", "wb"); 
  19.  
  20. if(!inpf) 
  21. { 
  22. goto Decodereturn; 
  23. } 
  24.  
  25. nalLen = 0; 
  26. Buf = (unsigned char*)calloc ( 1000000, sizeof(char)); //准备解码文件缓冲 
  27.  
  28. //2.注册解码器,并且找到H264解码器 
  29. avcodec_init(); 
  30. avcodec_register_all(); 
  31. codec = avcodec_find_decoder(CODEC_ID_H264); 
  32.  
  33. if (!codec) { 
  34. return 0; 
  35. } 
  36. //allocate codec context 
  37. //分配解码器内存 
  38. c = avcodec_alloc_context(); 
  39.  
  40. if(!c){ 
  41. return 0; 
  42. } 
  43. //open codec 
  44. //3.打开解码器 
  45. if (avcodec_open(c, codec) < 0) { 
  46. return 0; 
  47. } 
  48.  
  49. //allocate frame buffer 
  50. //分配解码器用的帧缓冲 
  51. picture = avcodec_alloc_frame(); 
  52. if(!picture){ 
  53. return 0; 
  54. } 
  55.  
  56. rgbdatanew = (unsigned char *)malloc(sizeof(unsigned char)*(3 * width * height)); 
  57.  
  58. while(!feof(inpf)) 
  59. { 
  60.  
  61. //4.获取下一个NAL的长度,并且将NAL放入Buf 
  62. nalLen = getNextNal(inpf, Buf); 
  63.  
  64. //5.对改NAL解码,解码的YUV数据存在picture中 
  65. consumed_bytes= avcodec_decode_video(c, picture, &got_picture, Buf, nalLen); 
  66.  
  67. if(consumed_bytes > 0) 
  68. { 
  69.  
  70. //6.将picture中的YUV数据显示或者保存到文件 
  71. p=0; 
  72. for(i=0; i<c->height; i++) 
  73. { 
  74. memcpy(DisplayBuf+p,picture->data[0] + i * picture->linesize[0], c->width); 
  75. p+=c->width; 
  76. } 
  77. for(i=0; i<c->height/2; i++) 
  78. { 
  79. memcpy(DisplayBuf+p,picture->data[1] + i * picture->linesize[1], c->width/2); 
  80. p+=c->width/2; 
  81. } 
  82. for(i=0; i<c->height/2; i++) 
  83. { 
  84. memcpy(DisplayBuf+p,picture->data[2] + i * picture->linesize[2], c->width/2); 
  85. p+=c->width/2; 
  86. } 
  87. //显示画面 
  88. DisplayVideo(DisplayBuf); 
  89. } 
  90. } 
  91.  
  92. //7.关闭输入文件 
  93. if(inpf) 
  94. fclose(inpf); 
  95.  
  96. Decodereturn: 
  97.  
  98. //8.关闭解码器,释放解码器内存 
  99. if(c) { 
  100. avcodec_close(c); 
  101. av_free(c); 
  102. c = NULL; 
  103. } 
  104. //9.释放解码画面内存 
  105. if(picture) { 
  106. av_free(picture); 
  107. picture = NULL; 
  108. } 
  109.  
  110. //10.释放解码文件缓冲 
  111. if(Buf) 
  112. { 
  113. free(Buf); 
  114. Buf = NULL; 
  115. } 
  116.  
  117. free(DisplayBuf); 
  118. } 
posted on 2010-06-29 15:41  物联互通  阅读(3744)  评论(3)    收藏  举报