天天看點

FFmpeg時間戳詳解

作者: 葉餘 來源: https://www.cnblogs.com/leisure_chn/p/10584910.html

1. I 幀/P 幀/B 幀

I 幀:I 幀(Intra-coded picture, 幀内編碼幀,常稱為關鍵幀)包含一幅完整的圖像資訊,屬于幀内編碼圖像,不含運動矢量,在解碼時不需要參考其他幀圖像。是以在 I 幀圖像處可以切換頻道,而不會導緻圖像丢失或無法解碼。I 幀圖像用于阻止誤差的累積和擴散。在閉合式 GOP 中,每個 GOP 的第一個幀一定是 I 幀,且目前 GOP 的資料不會參考前後 GOP 的資料。

P 幀:P 幀(Predictive-coded picture, 預測編碼圖像幀)是幀間編碼幀,利用之前的 I 幀或 P 幀進行預測編碼。

B 幀:B 幀(Bi-directionally predicted picture, 雙向預測編碼圖像幀)是幀間編碼幀,利用之前和(或)之後的 I 幀或 P 幀進行雙向預測編碼。B 幀不可以作為參考幀。

B 幀具有更高的壓縮率,但需要更多的緩沖時間以及更高的 CPU 占用率,是以 B 幀适合本地存儲以及視訊點播,而不适用對實時性要求較高的直播系統。

2. DTS 和 PTS

DTS(Decoding Time Stamp, 解碼時間戳),表示壓縮幀的解碼時間。

PTS(Presentation Time Stamp, 顯示時間戳),表示将壓縮幀解碼後得到的原始幀的顯示時間。

音頻中 DTS 和 PTS 是相同的。視訊中由于 B 幀需要雙向預測,B 幀依賴于其前和其後的幀,是以含 B 幀的視訊解碼順序與顯示順序不同,即 DTS 與 PTS 不同。當然,不含 B 幀的視訊,其 DTS 和 PTS 是相同的。下圖以一個開放式 GOP 示意圖為例,說明視訊流的解碼順序和顯示順序

FFmpeg時間戳詳解

采集順序指圖像傳感器采集原始信号得到圖像幀的順序。

編碼順序指編碼器編碼後圖像幀的順序。存儲到磁盤的本地視訊檔案中圖像幀的順序與編碼順序相同。

傳輸順序指編碼後的流在網絡中傳輸過程中圖像幀的順序。

解碼順序指解碼器解碼圖像幀的順序。

顯示順序指圖像幀在顯示器上顯示的順序。

采集順序與顯示順序相同。編碼順序、傳輸順序和解碼順序相同。

以圖中“B[1]”幀為例進行說明,“B[1]”幀解碼時需要參考“I[0]”幀和“P[3]”幀,是以“P[3]”幀必須比“B[1]”幀先解碼。這就導緻了解碼順序和顯示順序的不一緻,後顯示的幀需要先解碼。

3. FFmpeg 中的時間基與時間戳

3.1 時間基與時間戳的概念

在 FFmpeg 中,時間基(time_base)是時間戳(timestamp)的機關,時間戳值乘以時間基,可以得到實際的時刻值(以秒等為機關)。例如,如果一個視訊幀的 dts 是 40,pts 是 160,其 time_base 是 1/1000 秒,那麼可以計算出此視訊幀的解碼時刻是 40 毫秒(40/1000),顯示時刻是 160 毫秒(160/1000)。FFmpeg 中時間戳(pts/dts)的類型是 int64_t 類型,把一個 time_base 看作一個時鐘脈沖,則可把 dts/pts 看作時鐘脈沖的計數。

3.2 三種時間基 tbr、tbn 和 tbc

不同的封裝格式具有不同的時間基。在 FFmpeg 處理音視訊過程中的不同階段,也會采用不同的時間基。

FFmepg 中有三種時間基,指令行中 tbr、tbn 和 tbc 的列印值就是這三種時間基的倒數:

tbn:對應容器中的時間基。值是 AVStream.time_base 的倒數

tbc:對應編解碼器中的時間基。值是 AVCodecContext.time_base 的倒數

tbr:從視訊流中猜算得到,可能是幀率或場率(幀率的 2 倍)

測試檔案下載下傳(右鍵另存為):

tnmil3.flv

使用 ffprobe 探測媒體檔案格式,如下:

think@opensuse> ffprobe tnmil3.flv 
ffprobe version 4.1 Copyright (c) 2007-2018 the FFmpeg developers
Input #0, flv, from 'tnmil3.flv':
  Metadata:
    encoder         : Lavf58.20.100
  Duration: 00:00:03.60, start: 0.017000, bitrate: 513 kb/s
    Stream #0:0: Video: h264 (High), yuv420p(progressive), 784x480, 25 fps, 25 tbr, 1k tbn, 50 tbc
    Stream #0:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 128 kb/s      

關于 tbr、tbn 和 tbc 的說明,原文如下,來自 FFmpeg 郵件清單:

There are three different time bases for time stamps in FFmpeg. The

values printed are actually reciprocals of these, i.e. 1/tbr, 1/tbn and

1/tbc.

tbn is the time base in AVStream that has come from the container, I

think. It is used for all AVStream time stamps.

tbc is the time base in AVCodecContext for the codec used for a

particular stream. It is used for all AVCodecContext and related time

stamps.

tbr is guessed from the video stream and is the value users want to see

when they look for the video frame rate, except sometimes it is twice

what one would expect because of field rate versus frame rate.

3.3 内部時間基 AV_TIME_BASE

除以上三種時間基外,FFmpeg 還有一個内部時間基 AV_TIME_BASE(以及分數形式的 AV_TIME_BASE_Q)

// Internal time base represented as integer
#define AV_TIME_BASE            1000000
// Internal time base represented as fractional value
#define AV_TIME_BASE_Q          (AVRational){1, AV_TIME_BASE}      

AV_TIME_BASE 及 AV_TIME_BASE_Q 用于 FFmpeg 内部函數處理,使用此時間基計算得到時間值表示的是微秒。

3.4 時間值形式轉換

av_q2d()将時間從 AVRational 形式轉換為 double 形式。AVRational 是分數類型,double 是雙精度浮點數類型,轉換的結果機關是秒。轉換前後的值基于同一時間基,僅僅是數值的表現形式不同而已。

av_q2d()實作如下:

/**
 * Convert an AVRational to a `double`.
 * @param a AVRational to convert
 * @return `a` in floating-point form
 * @see av_d2q()
 */
static inline double av_q2d(AVRational a){
    return a.num / (double) a.den;
}      

av_q2d()使用方法如下:

AVStream stream;
AVPacket packet;
packet 播放時刻值:timestamp(機關秒) = packet.pts × av_q2d(stream.time_base);
packet 播放時長值:duration(機關秒) = packet.duration × av_q2d(stream.time_base);      

3.5 時間基轉換函數

av_rescale_q()用于不同時間基的轉換,用于将時間值從一種時間基轉換為另一種時間基。

/**
 * Rescale a 64-bit integer by 2 rational numbers.
 *
 * The operation is mathematically equivalent to `a × bq / cq`.
 *
 * This function is equivalent to av_rescale_q_rnd() with #AV_ROUND_NEAR_INF.
 *
 * @see av_rescale(), av_rescale_rnd(), av_rescale_q_rnd()
 */
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const;      

av_packet_rescale_ts()用于将 AVPacket 中各種時間值從一種時間基轉換為另一種時間基。

/**
 * Convert valid timing fields (timestamps / durations) in a packet from one
 * timebase to another. Timestamps with unknown values (AV_NOPTS_VALUE) will be
 * ignored.
 *
 * @param pkt packet on which the conversion will be performed
 * @param tb_src source timebase, in which the timing fields in pkt are
 *               expressed
 * @param tb_dst destination timebase, to which the timing fields will be
 *               converted
 */
void av_packet_rescale_ts(AVPacket *pkt, AVRational tb_src, AVRational tb_dst);      

3.6 轉封裝過程中的時間基轉換

容器中的時間基(AVStream.time_base,3.2 節中的 tbn)定義如下:

typedef struct AVStream {
    ......
    /**
     * This is the fundamental unit of time (in seconds) in terms
     * of which frame timestamps are represented.
     *
     * decoding: set by libavformat
     * encoding: May be set by the caller before avformat_write_header() to
     *           provide a hint to the muxer about the desired timebase. In
     *           avformat_write_header(), the muxer will overwrite this field
     *           with the timebase that will actually be used for the timestamps
     *           written into the file (which may or may not be related to the
     *           user-provided one, depending on the format).
     */
    AVRational time_base;
    ......
}      

AVStream.time_base 是 AVPacket 中 pts 和 dts 的時間機關,輸入流與輸出流中 time_base 按如下方式确定:

對于輸入流:打開輸入檔案後,調用 avformat_find_stream_info()可擷取到每個流中的 time_base

對于輸出流:打開輸出檔案後,調用 avformat_write_header()可根據輸出檔案封裝格式确定每個流的 time_base 并寫入輸出檔案中

不同封裝格式具有不同的時間基,在轉封裝(将一種封裝格式轉換為另一種封裝格式)過程中,時間基轉換相關代碼如下:

av_read_frame(ifmt_ctx, &pkt);
pkt.pts = av_rescale_q_rnd(pkt.pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
pkt.dts = av_rescale_q_rnd(pkt.dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
pkt.duration = av_rescale_q(pkt.duration, in_stream->time_base, out_stream->time_base);      

下面的代碼具有和上面代碼相同的效果:

// 從輸入檔案中讀取 packet
av_read_frame(ifmt_ctx, &pkt);
// 将 packet 中的各時間值從輸入流封裝格式時間基轉換到輸出流封裝格式時間基
av_packet_rescale_ts(&pkt, in_stream->time_base, out_stream->time_base);      

這裡流裡的時間基

in_stream->time_base

out_stream->time_base

,是容器中的時間基,就是 3.2 節中的 tbn。

例如,flv 封裝格式的 time_base 為{1,1000},ts 封裝格式的 time_base 為{1,90000}

我們編寫程式将 flv 封裝格式轉換為 ts 封裝格式,抓取原檔案(flv)的前四幀顯示時間戳:

think@opensuse> ffprobe -show_frames -select_streams v tnmil3.flv | grep pkt_pts  
ffprobe version 4.1 Copyright (c) 2007-2018 the FFmpeg developers
Input #0, flv, from 'tnmil3.flv':
  Metadata:
    encoder         : Lavf58.20.100
  Duration: 00:00:03.60, start: 0.017000, bitrate: 513 kb/s
    Stream #0:0: Video: h264 (High), yuv420p(progressive), 784x480, 25 fps, 25 tbr, 1k tbn, 50 tbc
    Stream #0:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 128 kb/s
pkt_pts=80
pkt_pts_time=0.080000
pkt_pts=120
pkt_pts_time=0.120000
pkt_pts=160
pkt_pts_time=0.160000
pkt_pts=200
pkt_pts_time=0.200000      

再抓取轉換的檔案(ts)的前四幀顯示時間戳:

think@opensuse> ffprobe -show_frames -select_streams v tnmil3.ts | grep pkt_pts  
ffprobe version 4.1 Copyright (c) 2007-2018 the FFmpeg developers
Input #0, mpegts, from 'tnmil3.ts':
  Duration: 00:00:03.58, start: 0.017000, bitrate: 619 kb/s
  Program 1 
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
    Stream #0:0[0x100]: Video: h264 (High) ([27][0][0][0] / 0x001B), yuv420p(progressive), 784x480, 25 fps, 25 tbr, 90k tbn, 50 tbc
    Stream #0:1[0x101]: Audio: aac (LC) ([15][0][0][0] / 0x000F), 44100 Hz, stereo, fltp, 127 kb/s
pkt_pts=7200
pkt_pts_time=0.080000
pkt_pts=10800
pkt_pts_time=0.120000
pkt_pts=14400
pkt_pts_time=0.160000
pkt_pts=18000
pkt_pts_time=0.200000      

可以發現,對于同一個視訊幀,它們時間基(tbn)不同是以時間戳(pkt_pts)也不同,但是計算出來的時刻值(pkt_pts_time)是相同的。

看第一幀的時間戳,計算關系:80×{1,1000} == 7200×{1,90000} == 0.080000

3.7 轉碼過程中的時間基轉換

編解碼器中的時間基(AVCodecContext.time_base,3.2 節中的 tbc)定義如下:

typedef struct AVCodecContext {
    ......
    
    /**
     * This is the fundamental unit of time (in seconds) in terms
     * of which frame timestamps are represented. For fixed-fps content,
     * timebase should be 1/framerate and timestamp increments should be
     * identically 1.
     * This often, but not always is the inverse of the frame rate or field rate
     * for video. 1/time_base is not the average frame rate if the frame rate is not
     * constant.
     *
     * Like containers, elementary streams also can store timestamps, 1/time_base
     * is the unit in which these timestamps are specified.
     * As example of such codec time base see ISO/IEC 14496-2:2001(E)
     * vop_time_increment_resolution and fixed_vop_rate
     * (fixed_vop_rate == 0 implies that it is different from the framerate)
     *
     * - encoding: MUST be set by user.
     * - decoding: the use of this field for decoding is deprecated.
     *             Use framerate instead.
     */
    AVRational time_base;
    
    ......
}      

上述注釋指出,AVCodecContext.time_base 是幀率(視訊幀)的倒數,每幀時間戳遞增 1,那麼 tbc 就等于幀率。編碼過程中,應由使用者設定好此參數。解碼過程中,此參數已過時,建議直接使用幀率倒數用作時間基。

這裡有一個問題:按照此處注釋說明,幀率為 25 的視訊流,tbc 理應為 25,但實際值卻為 50,不知作何解釋?是否 tbc 已經過時,不具參考意義?

根據注釋中的建議,實際使用時,在視訊解碼過程中,我們不使用 AVCodecContext.time_base,而用幀率倒數作時間基,在視訊編碼過程中,我們将 AVCodecContext.time_base 設定為幀率的倒數。

3.7.1 視訊流

視訊按幀播放,是以解碼後的原始視訊幀時間基為 1/framerate。

視訊解碼過程中的時間基轉換處理:

AVFormatContext *ifmt_ctx;
AVStream *in_stream;
AVCodecContext *dec_ctx;
AVPacket packet;
AVFrame *frame;
// 從輸入檔案中讀取編碼幀
av_read_frame(ifmt_ctx, &packet);
// 時間基轉換
int raw_video_time_base = av_inv_q(dec_ctx->framerate);
av_packet_rescale_ts(packet, in_stream->time_base, raw_video_time_base);
// 解碼
avcodec_send_packet(dec_ctx, packet)
avcodec_receive_frame(dec_ctx, frame);      

視訊編碼過程中的時間基轉換處理:

AVFormatContext *ofmt_ctx;
AVStream *out_stream;
AVCodecContext *dec_ctx;
AVCodecContext *enc_ctx;
AVPacket packet;
AVFrame *frame;
// 編碼
avcodec_send_frame(enc_ctx, frame);
avcodec_receive_packet(enc_ctx, packet);
// 時間基轉換
packet.stream_index = out_stream_idx;
enc_ctx->time_base = av_inv_q(dec_ctx->framerate);
av_packet_rescale_ts(&opacket, enc_ctx->time_base, out_stream->time_base);
// 将編碼幀寫入輸出媒體檔案
av_interleaved_write_frame(o_fmt_ctx, &packet);      

3.7.2 音頻流

音頻按采樣點播放,是以解碼後的原始音頻幀時間基為 1/sample_rate

音頻解碼過程中的時間基轉換處理:

AVFormatContext *ifmt_ctx;
AVStream *in_stream;
AVCodecContext *dec_ctx;
AVPacket packet;
AVFrame *frame;
// 從輸入檔案中讀取編碼幀
av_read_frame(ifmt_ctx, &packet);
// 時間基轉換
int raw_audio_time_base = av_inv_q(dec_ctx->sample_rate);
av_packet_rescale_ts(packet, in_stream->time_base, raw_audio_time_base);
// 解碼
avcodec_send_packet(dec_ctx, packet)
avcodec_receive_frame(dec_ctx, frame);      

音頻編碼過程中的時間基轉換處理:

AVFormatContext *ofmt_ctx;
AVStream *out_stream;
AVCodecContext *dec_ctx;
AVCodecContext *enc_ctx;
AVPacket packet;
AVFrame *frame;
// 編碼
avcodec_send_frame(enc_ctx, frame);
avcodec_receive_packet(enc_ctx, packet);
// 時間基轉換
packet.stream_index = out_stream_idx;
enc_ctx->time_base = av_inv_q(dec_ctx->sample_rate);
av_packet_rescale_ts(&opacket, enc_ctx->time_base, out_stream->time_base);
// 将編碼幀寫入輸出媒體檔案
av_interleaved_write_frame(o_fmt_ctx, &packet);      

4. 參考資料

[1].

What does the output of ffmpeg mean? tbr tbn tbc etc?

[2].

視訊編解碼基礎概念

,

https://www.cnblogs.com/leisure_chn/p/10285829.html

[3].

對 ffmpeg 的時間戳的了解筆記 https://blog.csdn.net/topsluo/article/details/76239136

[4].

ffmpeg 中的時間戳與時間基 http://www.imooc.com/article/91381

[5].

ffmpeg 編解碼中涉及到的 pts 詳解 http://www.52ffmpeg.com/article/353.html

[6].

音視訊錄入的 pts 和 dts 問題 https://blog.csdn.net/zhouyongku/article/details/38510747

5. 修改記錄

2019-03-16 V1.0 初稿

2019-03-23 V1.1 增加 3.7 節

「視訊雲技術」你最值得關注的音視訊技術公衆号,每周推送來自阿裡雲一線的實踐技術文章,在這裡與音視訊領域一流工程師交流切磋。
FFmpeg時間戳詳解

繼續閱讀