将H.264封装生成mp4文件

本项目需要用到mp4v2库,首先编译mp4v2库
以海思平台,交叉编译libmp4v2
MP4v2下载地址
1.编译mp4v2库

./configure --host=aarch64-himix100-linux CC=aarch64-himix100-linux-gcc CXX=aarch64-himix100-linux-g++ --disable-debug
make
make install

2.使用mp4v2库

int first_enter= 0;
char isSyncSample = 0;
#define _NALU_Iframe 0
#define _NALU_Pframe 1

#include "mp4v2/mp4v2.h"

MP4TrackId video = 0;
MP4FileHandle hMP4File = NULL;

void mp4write(char *_naluData,int size,int width,int height)
{
        int index = -1;
        if(_naluData[0]==0 && _naluData[1]==0 && _naluData[2]==0 && _naluData[3]==1 && _naluData[4]==0x67)
        {
		index = _NALU_Iframe;
                isSyncSample = 1;
	}
	
	if(_naluData[0]==0 && _naluData[1]==0 && _naluData[2]==0 && _naluData[3]==1 && _naluData[4]==0x61)
        {
		index = _NALU_Pframe;
                isSyncSample = 0;
	}

        switch(index)
        {
		case _NALU_Iframe:
                  if(first_enter ==0)
                  {
                  	 	 video = MP4AddH264VideoTrack(hMP4File, 90000, 90000 / 60, width, height, _naluData[4+1], _naluData[4+2], _naluData[4+3],3);
                 		 printf("_naluData[4+1]=%2x\n",_naluData[4+1]);
                         if (video == MP4_INVALID_TRACK_ID)  
                  	     {
                     		 printf("add video track failed.\n");
                     		 return;
                  	     }
                 	     MP4SetVideoProfileLevel(hMP4File, 0X7F);
                 	     MP4AddH264SequenceParameterSet(hMP4File, video, _naluData+4, 15);//sps
   		 	             MP4AddH264PictureParameterSet(hMP4File, video, _naluData+23, 4);//pps
			             first_enter =1;
                  }

		          _naluData[36] = ((size- 36 - 4) >> 24) &0xff;
		          _naluData[37] = ((size- 36 - 4) >> 16) &0xff;
	              _naluData[38] = ((size- 36 - 4) >> 8) &0xff;
		          _naluData[39] = (size- 36 - 4) & 0XFF;
                  MP4WriteSample(hMP4File, video, _naluData+36, size-36,MP4_INVALID_DURATION, 0, isSyncSample);
                  break;
                  
        case _NALU_Pframe:
                  _naluData[0] = ((size - 4) >> 24) &0xff;
                  _naluData[1] = ((size - 4) >> 16) &0xff;
                  _naluData[2] = ((size - 4) >> 8) &0xff;
                  _naluData[3] = (size - 4) & 0Xff;
                  MP4WriteSample(hMP4File, video, _naluData, size,MP4_INVALID_DURATION, 0, isSyncSample);
                  break;
	     }
}



void mp4init()
{
    char string[10]="save.mp4";   
    if(hMP4File == NULL)
    {
	    hMP4File = MP4CreateEx(string, 0, 1, 1, 0, 0, 0, 0);
        if (hMP4File == MP4_INVALID_FILE_HANDLE)	
        {   
		      printf("open file failed.\n");
		      return ;
	    }
        MP4SetTimeScale(hMP4File, 90000);
    }
}

void mp4close()
{
 	MP4Close(hMP4File,0);
	hMP4File = NULL;
	video = 0;
}

调用方式:
初始化: mp4init();
循环写帧:mp4write(char *_naluData,int size,int width,int height);
关闭: mp4close();一定要关闭

你可能感兴趣的:(音视频开发)