文章目錄
- MP4文件存放H264數據方式
- MP4 文件結構概述
- H.264 數據在 MP4 中的存儲
- 1. ftyp 盒子
- 2. moov 盒子
- 3. mdat 盒子
- H.264 數據在 stsd 盒子中的存儲(AVC1)
- AVC1與Annex-B 格式(裸 H.264 流)的區別
- 從MP4文件中提取H264裸流步驟:
- 完整代碼示例:
MP4文件存放H264數據方式
MP4文件是一個多媒體容器格式,它可以包含多種類型的音視頻數據,包括H.264視頻。MP4文件使用了一種稱為“盒子”(box)或“原子”(atom)的層次結構來組織數據。每個盒子都有特定的功能和用途,用于存儲文件元數據、音視頻數據以及其他信息。
MP4 文件結構概述
MP4文件由多個盒子(box)組成,每個盒子都有一個標頭(header)和內容(payload)。盒子的層次結構允許MP4文件靈活地存儲和組織數據。常見的盒子包括:
- ftyp:文件類型盒子,包含文件格式信息。
- moov:電影盒子,包含文件的全局元數據,包括trak(軌道)盒子。
- mdat:媒體數據盒子,包含實際的音視頻數據。
- moof:電影片段盒子,包含片段元數據,用于流媒體。
H.264 數據在 MP4 中的存儲
H.264視頻數據通常存儲在trak盒子中,具體在mdia(媒體)、minf(媒體信息)、stbl(示例表)子盒子中。以下是詳細的存儲方式:
1. ftyp 盒子
ftyp
盒子包含文件類型和兼容性信息,指示文件格式和版本。
2. moov 盒子
moov
盒子包含全局元數據,包括以下關鍵子盒子:
- mvhd:電影頭盒子,包含全局時間和其他信息。
- trak:軌道盒子,每個軌道對應一個媒體流(音頻、視頻、字幕等)。
- tkhd:軌道頭盒子,包含軌道的時間和其他信息。
- mdia:媒體盒子,包含特定軌道的媒體信息。
- mdhd:媒體頭盒子,包含媒體的時間和其他信息。
- hdlr:處理器引用盒子,指定該軌道的數據類型(視頻、音頻等)。
- minf:媒體信息盒子,包含媒體特定的信息。
- vmhd:視頻媒體信息頭盒子,僅用于視頻軌道。
- dinf:數據引用盒子,包含數據引用表。
- dref:數據引用表盒子,包含指向媒體數據的引用。
- stbl:示例表盒子,包含示例描述、時間、位置等信息。
- stsd:示例描述盒子,包含編碼類型和詳細信息。
- avc1:包含H.264視頻解碼信息。
- stts:時間抽樣表,包含幀時間戳信息。
- stsc:示例到塊映射表,定義示例如何映射到塊。
- stsz:示例大小表,包含每個示例的大小。
- stco:塊偏移表,包含數據塊在mdat盒子中的偏移。
- stsd:示例描述盒子,包含編碼類型和詳細信息。
3. mdat 盒子
mdat
盒子包含實際的媒體數據,包括H.264視頻數據。這點與 Annex-B 格式不同,視頻數據通常不包含NAL單元起始碼,而是使用長度字段。
H.264 數據在 stsd 盒子中的存儲(AVC1)
stsd
(示例描述盒子)中存儲了有關H.264流的詳細信息,包括SPS和PPS數據:
- avc1:視頻編碼類型描述,包含H.264視頻的詳細信息。
- AVCDecoderConfigurationRecord:包含SPS和PPS數據,以及NAL單元的長度信息。
AVC1與Annex-B 格式(裸 H.264 流)的區別
起始碼 vs 長度字段:
- AVC1 格式:每個 NAL 單元前有一個長度字段,指示該 NAL 單元的大小。長度字段的大小由
lengthSizeMinusOne
決定,通常為 4 字節。 - Annex-B 格式:每個 NAL 單元前有一個起始碼
0x00000001
或0x000001
,用于標識NAL單元的邊界。
SPS 和 PPS 數據存儲:
- AVC1 格式:SPS 和 PPS 數據存儲在
AVCDecoderConfigurationRecord
中,并且在解碼器初始化時解析。 - Annex-B 格式:SPS 和 PPS 數據直接包含在流中,通常位于關鍵幀之前,以確保解碼器能夠正確解析。
用途:
- AVC1 格式:主要用于 MP4 等封裝格式,提供高效的存儲和隨機訪問能力。
- Annex-B 格式:主要用于裸流傳輸和實時流媒體應用,便于NAL單元的識別和提取。
從MP4文件中提取H264裸流步驟:
完整代碼示例:
#include <stdio.h>
#include <libavutil/log.h>
#include <libavformat/avio.h>
#include <libavformat/avformat.h>#ifndef AV_WB32
# define AV_WB32(p, val) do { \uint32_t d = (val); \((uint8_t*)(p))[3] = (d); \((uint8_t*)(p))[2] = (d)>>8; \((uint8_t*)(p))[1] = (d)>>16; \((uint8_t*)(p))[0] = (d)>>24; \} while(0)
#endif//讀取內存中以大端字節序(big-endian)存儲的16位無符號整數
#ifndef AV_RB16
# define AV_RB16(x) \((((const uint8_t*)(x))[0] << 8) | \((const uint8_t*)(x))[1])
#endifstatic int alloc_and_copy(AVPacket *out,const uint8_t *sps_pps, uint32_t sps_pps_size,const uint8_t *in, uint32_t in_size)
{uint32_t offset = out->size;uint8_t nal_header_size = offset ? 3 : 4;int err;err = av_grow_packet(out, sps_pps_size + in_size + nal_header_size);if (err < 0)return err;if (sps_pps)memcpy(out->data + offset, sps_pps, sps_pps_size);memcpy(out->data + sps_pps_size + nal_header_size + offset, in, in_size);if (!offset) {AV_WB32(out->data + sps_pps_size, 1);} else {(out->data + offset + sps_pps_size)[0] =(out->data + offset + sps_pps_size)[1] = 0;(out->data + offset + sps_pps_size)[2] = 1;}return 0;
}//將 H.264 編碼器的 extradata (額外數據),從 MP4/AVCC 格式轉換為 Annex-B 格式,并將其存儲在 AVPacket 結構中。
int h264_extradata_to_annexb(const uint8_t *codec_extradata, const int codec_extradata_size, AVPacket *out_extradata, int padding)
{uint16_t unit_size;uint64_t total_size = 0;uint8_t *out = NULL, unit_nb, sps_done = 0,sps_seen = 0, pps_seen = 0, sps_offset = 0, pps_offset = 0;const uint8_t *extradata = codec_extradata + 4;// 跳過AVCC 格式中的前四個字節,這些信息在解析NAL單元的時候并不需要static const uint8_t nalu_header[4] = { 0, 0, 0, 1 }; //填充起始碼int length_size = (*extradata++ & 0x3) + 1; // retrieve length coded size, 用于指示表示編碼數據長度所需字節數sps_offset = pps_offset = -1;/* retrieve sps and pps unit(s) */unit_nb = *extradata++ & 0x1f; /* number of sps unit(s) */if (!unit_nb) {goto pps;}else {sps_offset = 0;sps_seen = 1;}while (unit_nb--) {int err;unit_size = AV_RB16(extradata);total_size += unit_size + 4;if (total_size > INT_MAX - padding) {av_log(NULL, AV_LOG_ERROR,"Too big extradata size, corrupted stream or invalid MP4/AVCC bitstream\n");av_free(out);return AVERROR(EINVAL);}if (extradata + 2 + unit_size > codec_extradata + codec_extradata_size) {av_log(NULL, AV_LOG_ERROR, "Packet header is not contained in global extradata, ""corrupted stream or invalid MP4/AVCC bitstream\n");av_free(out);return AVERROR(EINVAL);}if ((err = av_reallocp(&out, total_size + padding)) < 0)return err;memcpy(out + total_size - unit_size - 4, nalu_header, 4);memcpy(out + total_size - unit_size, extradata + 2, unit_size);extradata += 2 + unit_size;
pps:if (!unit_nb && !sps_done++) {unit_nb = *extradata++; /* number of pps unit(s) */if (unit_nb) {pps_offset = total_size;pps_seen = 1;}}}if (out)memset(out + total_size, 0, padding);if (!sps_seen)av_log(NULL, AV_LOG_WARNING,"Warning: SPS NALU missing or invalid. ""The resulting stream may not play.\n");if (!pps_seen)av_log(NULL, AV_LOG_WARNING,"Warning: PPS NALU missing or invalid. ""The resulting stream may not play.\n");out_extradata->data = out;out_extradata->size = total_size;return length_size;
}
//將MP4中的AVCC格式轉為annexb格式
int h264_mp4toannexb(AVFormatContext *fmt_ctx, AVPacket *in, FILE *dst_fd)
{AVPacket *out = NULL;AVPacket spspps_pkt;int len;uint8_t unit_type;int32_t nal_size;uint32_t cumul_size = 0;const uint8_t *buf;const uint8_t *buf_end;int buf_size;int ret = 0, i;out = av_packet_alloc(); // buf = in->data;buf_size = in->size;buf_end = in->data + in->size;do {ret= AVERROR(EINVAL);if (buf + 4 /*s->length_size*/ > buf_end)goto fail;for (nal_size = 0, i = 0; i<4/*s->length_size*/; i++)nal_size = (nal_size << 8) | buf[i];buf += 4; /*s->length_size;*/unit_type = *buf & 0x1f; //確定單元類型if (nal_size > buf_end - buf || nal_size < 0)goto fail;/*if (unit_type == 7)s->idr_sps_seen = s->new_idr = 1;else if (unit_type == 8) {s->idr_pps_seen = s->new_idr = 1;*//* if SPS has not been seen yet, prepend the AVCC one to PPS *//*if (!s->idr_sps_seen) {if (s->sps_offset == -1)av_log(ctx, AV_LOG_WARNING, "SPS not present in the stream, nor in AVCC, stream may be unreadable\n");else {if ((ret = alloc_and_copy(out,ctx->par_out->extradata + s->sps_offset,s->pps_offset != -1 ? s->pps_offset : ctx->par_out->extradata_size - s->sps_offset,buf, nal_size)) < 0)goto fail;s->idr_sps_seen = 1;goto next_nal;}}}*//* if this is a new IDR picture following an IDR picture, reset the idr flag.* Just check first_mb_in_slice to be 0 as this is the simplest solution.* This could be checking idr_pic_id instead, but would complexify the parsing. *//*if (!s->new_idr && unit_type == 5 && (buf[1] & 0x80))s->new_idr = 1;*//* prepend only to the first type 5 NAL unit of an IDR picture, if no sps/pps are already present */if (/*s->new_idr && */unit_type == 5 /*&& !s->idr_sps_seen && !s->idr_pps_seen*/) {//說明是個關鍵幀,需要將MP4中的SPS/PPS 填充到NAL單元之前 h264_extradata_to_annexb( fmt_ctx->streams[in->stream_index]->codec->extradata,fmt_ctx->streams[in->stream_index]->codec->extradata_size,&spspps_pkt,AV_INPUT_BUFFER_PADDING_SIZE);if ((ret=alloc_and_copy(out,spspps_pkt.data, spspps_pkt.size,buf, nal_size)) < 0)goto fail;/*s->new_idr = 0;*//* if only SPS has been seen, also insert PPS */}/*else if (s->new_idr && unit_type == 5 && s->idr_sps_seen && !s->idr_pps_seen) {if (s->pps_offset == -1) {av_log(ctx, AV_LOG_WARNING, "PPS not present in the stream, nor in AVCC, stream may be unreadable\n");if ((ret = alloc_and_copy(out, NULL, 0, buf, nal_size)) < 0)goto fail;} else if ((ret = alloc_and_copy(out,ctx->par_out->extradata + s->pps_offset, ctx->par_out->extradata_size - s->pps_offset,buf, nal_size)) < 0)goto fail;}*/ else {if ((ret=alloc_and_copy(out, NULL, 0, buf, nal_size)) < 0)goto fail;/*if (!s->new_idr && unit_type == 1) {s->new_idr = 1;s->idr_sps_seen = 0;s->idr_pps_seen = 0;}*/}len = fwrite( out->data, 1, out->size, dst_fd);if(len != out->size){av_log(NULL, AV_LOG_DEBUG, "warning, length of writed data isn't equal pkt.size(%d, %d)\n",len,out->size);}fflush(dst_fd);next_nal:buf += nal_size;cumul_size += nal_size + 4;//s->length_size;} while (cumul_size < buf_size);/*ret = av_packet_copy_props(out, in);if (ret < 0)goto fail;*/
fail:av_packet_free(&out);return ret;
}int main(int argc, char *argv[])
{int err_code;char errors[1024];char *src_filename = NULL;char *dst_filename = NULL;FILE *dst_fd = NULL;int video_stream_index = -1;//AVFormatContext *ofmt_ctx = NULL;//AVOutputFormat *output_fmt = NULL;//AVStream *out_stream = NULL;AVFormatContext *fmt_ctx = NULL;AVPacket pkt;//AVFrame *frame = NULL;av_log_set_level(AV_LOG_DEBUG);if(argc < 3){av_log(NULL, AV_LOG_DEBUG, "the count of parameters should be more than three!\n");return -1;}src_filename = argv[1];dst_filename = argv[2];if(src_filename == NULL || dst_filename == NULL){av_log(NULL, AV_LOG_ERROR, "src or dts file is null, plz check them!\n");return -1;}/*register all formats and codec*/av_register_all();dst_fd = fopen(dst_filename, "wb");if (!dst_fd) {av_log(NULL, AV_LOG_DEBUG, "Could not open destination file %s\n", dst_filename);return -1;}/*open input media file, and allocate format context*/if((err_code = avformat_open_input(&fmt_ctx, src_filename, NULL, NULL)) < 0){av_strerror(err_code, errors, 1024);av_log(NULL, AV_LOG_DEBUG, "Could not open source file: %s, %d(%s)\n",src_filename,err_code,errors);return -1;}/*dump input information*/av_dump_format(fmt_ctx, 0, src_filename, 0);/*initialize packet*/av_init_packet(&pkt);pkt.data = NULL;pkt.size = 0;/*find best video stream*/video_stream_index = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);if(video_stream_index < 0){av_log(NULL, AV_LOG_DEBUG, "Could not find %s stream in input file %s\n",av_get_media_type_string(AVMEDIA_TYPE_VIDEO),src_filename);return AVERROR(EINVAL);}/*if (avformat_write_header(ofmt_ctx, NULL) < 0) {av_log(NULL, AV_LOG_DEBUG, "Error occurred when opening output file");exit(1);}*//*read frames from media file*/while(av_read_frame(fmt_ctx, &pkt) >=0 ){if(pkt.stream_index == video_stream_index){/*pkt.stream_index = 0;av_write_frame(ofmt_ctx, &pkt);av_free_packet(&pkt);*/h264_mp4toannexb(fmt_ctx, &pkt, dst_fd);}//release pkt->dataav_packet_unref(&pkt);}//av_write_trailer(ofmt_ctx);/*close input media file*/avformat_close_input(&fmt_ctx);if(dst_fd) {fclose(dst_fd);}//avio_close(ofmt_ctx->pb);return 0;
}