h264起始码格式转换

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

h264起始码

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

h264起始码格式转换_第1张图片

h264起始码格式转换_第2张图片

 

代码实现

以下通过代码功能可以格式化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;
}

 

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