音視頻開發—FFmpeg 從MP4文件中抽取視頻H264數據

文章目錄

    • 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盒子中的偏移。
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 單元前有一個起始碼 0x000000010x000001,用于標識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;
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/45049.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/45049.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/45049.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

java使用easypoi模版導出word詳細步驟

文章目錄 第一步、引入pom依賴第二步、新建導出工具類WordUtil第三步、創建模版word4.編寫接口代碼5.導出結果示例 第一步、引入pom依賴 <dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><…

怎么壓縮視頻?推薦7款必備視頻壓縮軟件免費版(強烈建議收藏)

如今&#xff0c;視頻內容日益豐富&#xff0c;并占據了許多人的日常娛樂和工作生活。然而&#xff0c;隨著高清和超高清視頻的普及&#xff0c;視頻文件的體積也越來越大&#xff0c;給存儲和傳輸帶來了挑戰。因此&#xff0c;學會如何壓縮視頻文件成為了許多人的需求之一。本…

小米官網的數據是怎么優化的?

小米PC端官網首頁的“全部商品分類”功能是用戶瀏覽和選擇商品的重要入口。為了優化這一功能的數據展示和用戶體驗&#xff0c;可以采取以下幾個步驟&#xff1a; 數據加載優化&#xff1a; 懶加載&#xff08;Lazy Loading&#xff09;&#xff1a;當鼠標劃過“全部商品分類”…

實現前端登錄注冊功能(有源碼)

引言 用戶登錄和注冊是任何現代Web應用程序的基本功能。在前端開發中&#xff0c;實現一個安全且用戶友好的登錄注冊系統至關重要。本文將介紹如何使用HTML、CSS和JavaScript&#xff08;包括Vue.js&#xff09;來實現前端的登錄和注冊功能。 1. 項目結構 首先&#xff0c;我們…

軟設之訪問者模式

設計模式中訪問者模式的意圖是&#xff1a; 表示一個作用于某對象結構中的各元素的操作&#xff0c;使得在不改變各元素的類的前提下定義作用于這些元素的新操作。 舉個例子&#xff0c;比如說有個游客想去幾個景點&#xff0c;去每個景點都想按統一的流程。但是每個景點都有…

vue3 學習筆記04 -- axios的使用及封裝

vue3 學習筆記04 – axios的使用及封裝 安裝 Axios 和 TypeScript 類型定義 npm install axios npm install -D types/axios創建一個 Axios 實例并封裝成一個可復用的模塊&#xff0c;這樣可以在整個應用中輕松地進行 API 請求管理。 在 src 目錄下創建一個 services 文件夾&…

關于鋰電池的充電過程

鋰電池的充電階段大概可以分為四個階段&#xff1a;涓流充電、恒流充電、恒壓充電以及充電終止。 涓流充電&#xff1a;這是充電過程的第一階段&#xff0c;主要用于對完全放電的電池單元進行預充&#xff08;恢復性充電&#xff09;。當電池電壓低于大概3V時&#xff0c;采用最…

【學習css1】flex布局-頁面footer部分保持在網頁底部

中間內容高度不夠屏幕高度撐不開的頁面時候&#xff0c;頁面footer部分都能保持在網頁頁腳&#xff08;最底部&#xff09;的方法 1、首先上圖看顯示效果 2、奉上源碼 2.1、html部分 <body><header>頭部</header><main>主區域</main><foot…

PaintsUndo - 一張照片一鍵生成繪畫過程視頻 本地一鍵整合包下載

這就是ControlNet作者張呂敏大佬的新作&#xff0c;PaintsUndo。只要你有一張圖片&#xff0c;PaintsUndo 就能讓它變成完整的繪畫過程視頻。這科技&#xff0c;絕了。 你有沒有想過&#xff0c;一張靜態圖片也能變成一個繪畫教程? PaintsUndo 就是這么神奇。你只需要提供一…

通過手機供網、可修改WIFI_MAC的網絡設備

一、修改WIFI mac&#xff08;bssid&#xff09; 取一根網線&#xff0c;一頭連著設備黃色網口、一頭連著電腦按住設備reset按鍵&#xff0c;插入電源線&#xff0c;觀察到藍燈閃爍后再松開reset按鍵 打開電腦瀏覽器&#xff0c;進入192.168.1.1&#xff0c;選擇“MAC 地址修改…

【Spring Boot】Spring原理:Bean的作用域和生命周期

目錄 Spring原理一. 知識回顧1.1 回顧Spring IOC1.2 回顧Spring DI1.3 回顧如何獲取對象 二. Bean的作用域三. Bean的生命周期 Spring原理 一. 知識回顧 在之前IOC/DI的學習中我們也用到了Bean對象&#xff0c;現在先來回顧一下IOC/DI的知識吧&#xff01; 首先Spring IOC&am…

可視化學習:如何用WebGL繪制3D物體

在之前的文章中&#xff0c;我們使用WebGL繪制了很多二維的圖形和圖像&#xff0c;在學習2D繪圖的時候&#xff0c;我們提過很多次關于GPU的高效渲染&#xff0c;但是2D圖形的繪制只展示了WebGL部分的能力&#xff0c;WebGL更強大的地方在于&#xff0c;它可以繪制各種3D圖形&a…

C語言之數據在內存中的存儲(2),浮點數在內存中的存儲

目錄 前言 一、引例 二、浮點型在內存中的存儲 三、浮點數在內存中的存和取過程 1.浮點數的存儲過程 2.浮點數的取過程 四、引例解析 總結 前言 想知道浮點數在內存中是如何存儲的嗎&#xff0c;本文就告訴你答案&#xff0c;雖然一般情況題目還是面試涉及到浮點數在內…

新華三H3CNE網絡工程師認證—ACL使用場景

ACL主要用于實現流量的過濾&#xff0c;業務中網絡的需求不止局限于能夠連同。 一、過略工具 你的公司當中有研發部門&#xff0c;包括有財務部門&#xff0c;財務部門的訪問是要做到控制的&#xff0c;防止被攻擊。 這種的過濾方法為&#xff0c;在設備側可以基于訪問需求來…

解決IntelliJ IDEA連接MySQL時“Public Key Retrieval is not Allowed”問題

前言 在使用IntelliJ IDEA開發環境中連接MySQL數據庫時&#xff0c;可能會遇到“Public Key Retrieval is not allowed”這樣的錯誤提示&#xff0c;即使輸入的用戶名和密碼完全正確。本文將指導你如何解決這一問題&#xff0c;確保順利建立數據庫連接。 錯誤背景 這一問題通…

AI算力發展現狀與趨勢分析

綜合算力發展現狀與趨勢分析 在數字經濟的疾速推動下&#xff0c;綜合算力作為驅動各類應用和服務的新型生產力&#xff0c;其價值日益凸顯。我們深入探討了綜合算力的定義、重要性以及當前發展狀況&#xff1b;并從算力形態、運力性能和存儲技術等角度&#xff0c;預見了其發展…

基于Java技術的校友社交系統

你好呀&#xff0c;我是計算機學姐碼農小野&#xff01;如果你對校友社交系統感興趣或者有相關需求&#xff0c;可以私信聯系我。 開發語言 Java 數據庫 MySQL 技術 Java技術SpringBoot框架 工具 IDEA/Eclipse、Navicat、Maven 系統展示 首頁 校友會信息界面 校友活動…

Sqli-labs 3

1.按照路徑http://localhost/sqli-labs/sqli-labs-master/Less-3/進入 2.判斷注入類型----字符型 Payload&#xff1a;?id1’) and 11-- 注&#xff1a;根據報錯提示的語法錯誤&#xff0c;在第一行中使用接近’union select 1,2,3--’)的正確語法 3.判斷注入點&#xff1a;…

【Linux】vim詳解

1.什么是vi/vim? 簡單來說&#xff0c;vi是老式的文本編輯器&#xff0c;不過功能已經很齊全了&#xff0c;但是還是有可以進步的地方。vim則可以說是程序開發者的一項很好用的工具&#xff0c;就連 vim的官方網站&#xff08; http://www.vim.org&#xff09;自己也說vim是一…

如何計算卷積層輸出圖像的大小以及池化大小輸出

如何計算卷積層輸出圖像的大小&以及池化大小輸出 卷積 在卷積神經網絡&#xff08;CNN&#xff09;中&#xff0c;計算卷積層輸出圖像的大小是一個常見的操作。以下是卷積計算的基本公式和步驟&#xff1a; 卷積層輸出尺寸計算公式&#xff1a; Output_size ? Input_s…