h264起始碼格式轉換

音視頻應用開發系列文章目錄

h264起始碼

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

 

代碼實現

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章