Java h264起始码_h264起始码格式转换

《音视频应用开发系列文章目录》

h264起始码

h264文件的NALU的起始码可以是0x00 0x00 0x01或者0x00 0x00 0x00 0x01

4480793d441ab32d15d9f4f40614cefe.png

9ce01fd1cdd4c9b2a516a7017a039654.png

代码实现

以下通过代码功能可以格式化h264文件为任意一种起始码类型。

int h264_format_start_code(const char *dst, const char *src, int type /* 0 for 001, 1 for 0001 */)

dst:输出格式化后的h264文件

src:输入原始的h264文件

type:0 格式化为0x00 0x00 0x01,1 格式化为0x00 0x00 0x00 0x01

return:0 成功,1 失败

int h264_format_start_code(const char *dst, const char *src, int type /* 0 for 001, 1 for 0001 */) {

FILE *ifile = fopen(src, "rb");

FILE *ofile = fopen(dst, "wb");

if (ifile && ofile) {

fseek(ifile, 0L, SEEK_END);

int size = ftell(ifile);

rewind(ifile);

unsigned char *ibuf = (unsigned char *)malloc(size * sizeof(unsigned char));

unsigned char *obuf = (unsigned char *)malloc(size * sizeof(unsigned char) * 2);

if (!ibuf || !obuf) return -1;

int r = fread(ibuf, 1, size, ifile);

if (r != size) return -1;

int x = 0;

int t = -1;

while (x < size - 4) {

if (ibuf[x + 0] == 0x00 && ibuf[x + 1] == 0x00) {

if (ibuf[x + 2] == 0x01) {

t = 0;

break;

}

else if (ibuf[x + 2] == 0x00 && ibuf[x + 3] == 0x01) {

t = 1;

break;

}

}

++x;

}

x = 0;

int y = 0;

if (t == -1 || type < 0 || type > 1) return -1;

if (t == type) {

while (x < size) {

obuf[x] = ibuf[x];

++x;

}

}

else {

if (type == 0) { // format 001

while (x < size - 4) {

if (ibuf[x + 0] == 0x00 && ibuf[x + 1] == 0x00 &&

ibuf[x + 2] == 0x00 && ibuf[x + 3] == 0x01) {

obuf[y++] = 0x00;

obuf[y++] = 0x00;

obuf[y++] = 0x01;

x += 4;

}

else {

obuf[y++] = ibuf[x++];

}

}

for (int i = 0; i < 4; i++)

obuf[y++] = ibuf[x++];

}

else { // format 0001

while (x < size - 3) {

if (ibuf[x + 0] == 0x00 && ibuf[x + 1] == 0x00 && ibuf[x + 2] == 0x01) {

obuf[y++] = 0x00;

obuf[y++] = 0x00;

obuf[y++] = 0x00;

obuf[y++] = 0x01;

x += 3;

}

else {

obuf[y++] = ibuf[x++];

}

}

for (int i = 0; i < 3; i++)

obuf[y++] = ibuf[x++];

}

}

fwrite(obuf, 1, y - 1, ofile);

free(ibuf);

free(obuf);

fclose(ifile);

fclose(ofile);

return 0;

}

return -1;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值