视音频数据处理入门:H.264视频码流解析

本文介绍的程序是视频码流处理程序。视频码流在视频播放器中的位置如下所示。



本文中的程序是一个H.264码流解析程序。该程序可以从H.264码流中分析得到它的基本单元NALU,并且可以简单解析NALU首部的字段。通过修改该程序可以实现不同的H.264码流处理功能。
原理
H.264原始码流(又称为“裸流”)是由一个一个的NALU组成的。他们的结构如下图所示。



其中每个NALU之间通过startcode(起始码)进行分隔,起始码分成两种:0x000001(3Byte)或者0x00000001(4Byte)。如果NALU对应的Slice为一帧的开始就用0x00000001,否则就用0x000001。
H.264码流解析的步骤就是首先从码流中搜索0x000001和0x00000001,分离出NALU;然后再分析NALU的各个字段。本文的程序即实现了上述的两个步骤。
代码

整个程序位于simplest_h264_parser()函数中,如下所示。

/** 
 * 最简单的视音频数据处理示例 
 * Simplest MediaData Test 
 * 
 * 雷霄骅 Lei Xiaohua 
 * leixiaohua1020@126.com 
 * 中国传媒大学/数字电视技术 
 * Communication University of China / Digital TV Technology 
 * http://blog.csdn.net/leixiaohua1020 
 * 
 * 本项目包含如下几种视音频测试示例: 
 *  (1)像素数据处理程序。包含RGB和YUV像素格式处理的函数。 
 *  (2)音频采样数据处理程序。包含PCM音频采样格式处理的函数。 
 *  (3)H.264码流分析程序。可以分离并解析NALU。 
 *  (4)AAC码流分析程序。可以分离并解析ADTS帧。 
 *  (5)FLV封装格式分析程序。可以将FLV中的MP3音频码流分离出来。 
 *  (6)UDP-RTP协议分析程序。可以将分析UDP/RTP/MPEG-TS数据包。 
 * 
 * This project contains following samples to handling multimedia data: 
 *  (1) Video pixel data handling program. It contains several examples to handle RGB and YUV data. 
 *  (2) Audio sample data handling program. It contains several examples to handle PCM data. 
 *  (3) H.264 stream analysis program. It can parse H.264 bitstream and analysis NALU of stream. 
 *  (4) AAC stream analysis program. It can parse AAC bitstream and analysis ADTS frame of stream. 
 *  (5) FLV format analysis program. It can analysis FLV file and extract MP3 audio stream. 
 *  (6) UDP-RTP protocol analysis program. It can analysis UDP/RTP/MPEG-TS Packet. 
 * 
 */  
#include <stdio.h>  
#include <stdlib.h>  
#include <string.h>  
  
typedef enum {  
    NALU_TYPE_SLICE    = 1,  
    NALU_TYPE_DPA      = 2,  
    NALU_TYPE_DPB      = 3,  
    NALU_TYPE_DPC      = 4,  
    NALU_TYPE_IDR      = 5,  
    NALU_TYPE_SEI      = 6,  
    NALU_TYPE_SPS      = 7,  
    NALU_TYPE_PPS      = 8,  
    NALU_TYPE_AUD      = 9,  
    NALU_TYPE_EOSEQ    = 10,  
    NALU_TYPE_EOSTREAM = 11,  
    NALU_TYPE_FILL     = 12,  
} NaluType;  
  
typedef enum {  
    NALU_PRIORITY_DISPOSABLE = 0,  
    NALU_PRIORITY_LOW         = 1,  
    NALU_PRIORITY_HIGH       = 2,  
    NALU_PRIORITY_HIGHEST    = 3  
} NaluPriority;  
  
  
typedef struct  
{  
    int startcodeprefix_len;      //! 4 for parameter sets and first slice in picture, 3 for everything else (suggested)  
    unsigned len;                 //! Length of the NAL unit (Excluding the start code, which does not belong to the NALU)  
    unsigned max_size;            //! Nal Unit Buffer size  
    int forbidden_bit;            //! should be always FALSE  
    int nal_reference_idc;        //! NALU_PRIORITY_xxxx  
    int nal_unit_type;            //! NALU_TYPE_xxxx      
    char *buf;                    //! contains the first byte followed by the EBSP  
} NALU_t;  
  
FILE *h264bitstream = NULL;                //!< the bit stream file  
  
int info2=0, info3=0;  
//判断是否为0x000001
static int FindStartCode2 (unsigned char *Buf){  
    if(Buf[0]!=0 || Buf[1]!=0 || Buf[2] !=1) return 0; 
    else return 1;  
}  
//判断是否为0x00000001  
static int FindStartCode3 (unsigned char *Buf){  
    if(Buf[0]!=0 || Buf[1]!=0 || Buf[2] !=0 || Buf[3] !=1) return 0;//0x00000001?  
    else return 1;  
}  
  
  
int GetAnnexbNALU (NALU_t *nalu){  
    int pos = 0;  
    int StartCodeFound, rewind;  
    unsigned char *Buf;  
  
    if ((Buf = (unsigned char*)calloc (nalu->max_size , sizeof(char))) == NULL)   
        printf ("GetAnnexbNALU: Could not allocate Buf memory\n");  
  //判断开头代码0x000001还是0x00000001
    nalu->startcodeprefix_len=3;  
  
    if (3 != fread (Buf, 1, 3, h264bitstream)){  
        free(Buf);  
        return 0;  
    }  
    info2 = FindStartCode2 (Buf);  
    if(info2 != 1) {  
        if(1 != fread(Buf+3, 1, 1, h264bitstream)){  
            free(Buf);  
            return 0;  
        }  
        info3 = FindStartCode3 (Buf);  
        if (info3 != 1){   
            free(Buf);  
            return -1;  
        }  
        else {  
            pos = 4;  
            nalu->startcodeprefix_len = 4;  
        }  
    }  
    else{  
        nalu->startcodeprefix_len = 3;  
        pos = 3;  
    }  
    StartCodeFound = 0;  
    info2 = 0;  
    info3 = 0;  
  
    while (!StartCodeFound){  
        if (feof (h264bitstream)){  
            nalu->len = (pos-1)-nalu->startcodeprefix_len;  
            memcpy (nalu->buf, &Buf[nalu->startcodeprefix_len], nalu->len);       
            nalu->forbidden_bit = nalu->buf[0] & 0x80; //1 bit  
            nalu->nal_reference_idc = nalu->buf[0] & 0x60; // 2 bit  
            nalu->nal_unit_type = (nalu->buf[0]) & 0x1f;// 5 bit  
            free(Buf);  
            return pos-1;  
        }  
        Buf[pos++] = fgetc (h264bitstream);  
        info3 = FindStartCode3(&Buf[pos-4]);  
        if(info3 != 1)  
            info2 = FindStartCode2(&Buf[pos-3]);  
        StartCodeFound = (info2 == 1 || info3 == 1);  
    }  
  
    // Here, we have found another start code (and read length of startcode bytes more than we should  
    // have.  Hence, go back in the file  
    rewind = (info3 == 1)? -4 : -3;  
  
    if (0 != fseek (h264bitstream, rewind, SEEK_CUR)){  
        free(Buf);  
        printf("GetAnnexbNALU: Cannot fseek in the bit stream file");  
    }  
  
    // Here the Start code, the complete NALU, and the next start code is in the Buf.    
    // The size of Buf is pos, pos+rewind are the number of bytes excluding the next  
    // start code, and (pos+rewind)-startcodeprefix_len is the size of the NALU excluding the start code  
  
    nalu->len = (pos+rewind)-nalu->startcodeprefix_len;  
    memcpy (nalu->buf, &Buf[nalu->startcodeprefix_len], nalu->len);//  
    nalu->forbidden_bit = nalu->buf[0] & 0x80; //1 bit  
    nalu->nal_reference_idc = nalu->buf[0] & 0x60; // 2 bit  
    nalu->nal_unit_type = (nalu->buf[0]) & 0x1f;// 5 bit  
    free(Buf);  
  
    return (pos+rewind);  
}  
  
/** 
 * Analysis H.264 Bitstream 
 * @param url    Location of input H.264 bitstream file. 
 */  
int simplest_h264_parser(char *url){  
  
    NALU_t *n;  
    int buffersize=100000;  
  
    //FILE *myout=fopen("output_log.txt","wb+");  
    FILE *myout=stdout;  //C语言标准话输出
  
    h264bitstream=fopen(url, "rb+");  
    if (h264bitstream==NULL){  
        printf("Open file error\n");  
        return 0;  
    }  
  
    n = (NALU_t*)calloc (1, sizeof (NALU_t));  
    if (n == NULL){  
        printf("Alloc NALU Error\n");  
        return 0;  
    }  
  
    n->max_size=buffersize;  
    n->buf = (char*)calloc (buffersize, sizeof (char));  
    if (n->buf == NULL){  
        free (n);  
        printf ("AllocNALU: n->buf");  
        return 0;  
    }  
  
    int data_offset=0;  
    int nal_num=0;  
    printf("-----+-------- NALU Table ------+---------+\n");  
    printf(" NUM |    POS  |    IDC |  TYPE |   LEN   |\n");  
    printf("-----+---------+--------+-------+---------+\n");  
  
    while(!feof(h264bitstream))   
    {  
        int data_lenth;  
        data_lenth=GetAnnexbNALU(n);  
  
        char type_str[20]={0};  
        switch(n->nal_unit_type){  
            case NALU_TYPE_SLICE:sprintf(type_str,"SLICE");break;  
            case NALU_TYPE_DPA:sprintf(type_str,"DPA");break;  
            case NALU_TYPE_DPB:sprintf(type_str,"DPB");break;  
            case NALU_TYPE_DPC:sprintf(type_str,"DPC");break;  
            case NALU_TYPE_IDR:sprintf(type_str,"IDR");break;  
            case NALU_TYPE_SEI:sprintf(type_str,"SEI");break;  
            case NALU_TYPE_SPS:sprintf(type_str,"SPS");break;  
            case NALU_TYPE_PPS:sprintf(type_str,"PPS");break;  
            case NALU_TYPE_AUD:sprintf(type_str,"AUD");break;  
            case NALU_TYPE_EOSEQ:sprintf(type_str,"EOSEQ");break;  
            case NALU_TYPE_EOSTREAM:sprintf(type_str,"EOSTREAM");break;  
            case NALU_TYPE_FILL:sprintf(type_str,"FILL");break;  
        }  
        char idc_str[20]={0};  
        switch(n->nal_reference_idc>>5){  
            case NALU_PRIORITY_DISPOSABLE:sprintf(idc_str,"DISPOS");break;  
            case NALU_PRIRITY_LOW:sprintf(idc_str,"LOW");break;  
            case NALU_PRIORITY_HIGH:sprintf(idc_str,"HIGH");break;  
            case NALU_PRIORITY_HIGHEST:sprintf(idc_str,"HIGHEST");break;  
        }  
  
        fprintf(myout,"%5d| %8d| %7s| %6s| %8d|\n",nal_num,data_offset,idc_str,type_str,n->len);  
  
        data_offset=data_offset+data_lenth;  
  
        nal_num++;  
    }  
  
    //Free  
    if (n){  
        if (n->buf){  
            free(n->buf);  
            n->buf=NULL;  
        }  
        free (n);  
    }  
    return 0;  
} 
结果

本程序的输入为一个H.264原始码流(裸流)的文件路径,输出为该码流的NALU统计数据,如下图所示。



Ps:非原创,原作者雷霄骅

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,601评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,367评论 1 305
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,249评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,539评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,967评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,929评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,098评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,825评论 0 207
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,609评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,796评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,282评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,603评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,277评论 3 242
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,159评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,959评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,079评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,874评论 2 277

推荐阅读更多精彩内容