音視訊同步!RTCP 協議解析及程式碼實現

聲網Agora發表於2021-10-02

音視訊同步!RTCP協議解析及程式碼實現

RTCP 是實時控制協議(Real-Time Control Protocol)的縮寫。RTCP 由 RFC 3550 定義(取代作廢的 RFC 1889)。

實時傳輸協議(RTP)和實時控制協議(RTCP)結合使用,可以監視大型多播網路的資料傳遞。RTP 承載媒體流,而 RTCP 用於監視傳輸統計資訊和服務質量。監視使接收器能夠檢測是否有任何丟包並補償任何延遲抖動。

兩種協議都獨立於基礎傳輸層協議和網路層協議工作。RTP 標頭中的資訊告訴接收器如何重建資料,並描述編解碼器位元流的打包方式。

下面我們重點講解 RTCP 功能、RTCP 資訊包等。最後 RTCP 協議解析實現。

RTCP 有哪些功能

1、RTCP 主要功能是提供有關質量的反饋資料分發。這是 RTP 角色不可或缺的一部分,傳輸協議,與流量和擁塞有關其他傳輸協議的控制功能。

2、RTCP 帶有 RTP 的永續性傳輸級別識別符號源稱為規範名稱或 CNAME。自從如果發現衝突或程式重新啟動,接收方要求 CNAME 跟蹤每個參與者。

接收者也可能要求 CNAME 將來自給定參與者的多個資料流關聯到集合中相關 RTP 會話的數量,例如同步音訊和視訊。媒體間同步還需要 NTP 和 RTP 資料傳送方在 RTCP 資料包中包含的時間戳。

3、前兩個功能要求所有參與者傳送 RTCP 資料包,因此必須控制速率以使 RTP 能夠擴大到大量參與者。通過讓每個參與者將其控制包傳送給所有其他人,每個人都可以獨立觀察參與者的數量。

4、這項功能對於參加者可以任意進入和離開的鬆散會話程式十分有用,參加者可以自由進入或離開,沒有成員控制或引數協調。

功能 1-3 應該在所有環境中使用,尤其是在 IP 多播環境。RTP 應用程式設計師應避免只能在單播模式下工作且無法擴充套件到的機制更大的數字。RTCP 的傳輸可以單獨控制對於傳送者和接收者,適用於例如單向連結,而接收者沒有反饋可能的。

RTCP 協議的埠

RTSP 通常使用 RTP 協議來傳送實時流,RTP 一般使用偶數埠,而 RTCP 使用相鄰的奇數埠,即 RTP 埠號+1。

RTP 埠

img

RTCP 埠

img

RTCP 資訊包有哪些

在 RTCP 通訊控制中,RTCP 協議的功能是通過不同型別的 RTCP 包來實現的。RTCP 也是基於 UDP 包來傳送的,主要有五種型別的封包:

  1. SR:傳送端報告,由傳送 RTP 資料包的應用程式或中端發出的。
  2. RR:接收端報告,由接受但不傳送 RTP 資料包的應用程式或中端發出。
  3. SDES:源描述,傳遞與會話成員有關的標識資訊的載體,如使用者名稱、郵件、電話等。
  4. BYE:通知離開,通知回話中的其他成員將退出會話。
  5. APP:由應用程式自己定義,作為 RTCP 協議的擴充套件。
#define RTCP_SR      200
#define RTCP_RR      201
#define RTCP_SDES    202
#define RTCP_BYE     203
#define RTCP_APP     204

我們可以根據這五種型別包判斷 RTCP 頭部

static bool dissect_rtcp_heur(u_char *rtcp_info,int PayloadLen)
{
    unsigned int offset = 0;
    unsigned int first_byte = 0;
    unsigned int packet_type = 0;


    /* 檢視第一個位元組 */
    first_byte = rtcp_info[offset];

    /* 版本位是否設定為2*/
    //printf("version: %d\n",((first_byte & 0xC0) >> 6));
    if (((first_byte & 0xC0) >> 6) != 2)
    {
        return false;
    }

    /* 看包型別 */
    offset += 1;
    packet_type = rtcp_info[offset];
    //printf("packet_type: %d\n",packet_type);
    /* 複合資料包中的第一個資料包應該是傳送方或接收者報告 */
    if (!((packet_type == RTCP_SR)  || (packet_type == RTCP_RR) ||
          (packet_type == RTCP_BYE) || (packet_type == RTCP_APP) ||
          (packet_type == RTCP_PSFB)))
    {
        return false;
    }

    /*總長度必須是4個位元組的倍數*/
    //printf("PayloadLen: %d\n",PayloadLen);
    if (PayloadLen % 4)
    {
        return false;
    }

    /* OK, dissect as RTCP */
    dissect_rtcp(rtcp_info,packet_type,offset,PayloadLen);
    return true;
}

RTCP 協議報文格式

SR:傳送端報告

img

版本(V):同 RTP 包頭部

填充 ( P ) :同 RTP 包頭部。

接收報告計數器(RC):5b 該 SR 包中接收的報告塊的數目。

包型別(PT): 8bit SR 包型別為 200

長度(length):SR 包以 32bit 為 1 單位的長度減 1

同步源(SSRC):SR 包傳送的同步源識別符號。與對應 RTP 包中的 SSRC 一樣。

NTP 時間戳(Network Time Protocol):SR 包傳送時的絕對時間。用於同步不同的流。

RTP 時間戳:與 NTP 時間戳對應,與 RTP 包中的時間戳具有相同的初始值。

Send’s Packet count:從開始發包到產生這個 SR 包的這段時間內傳送者傳送的有效資料的總位元組數,不包括頭部和填充,傳送者改變 SSRC 時,該域要清零。

同步源 n 的 SSRC 識別符號:該報告中包含的是從該源接收到的包的統計資訊。

丟失率:表明從上一個 SR 或 RR 包發出依來從同步源 n 傳送的 RTP 包的丟失率。

累計丟失資料:從開始接受 SSRC_n 的包到傳送 SR 這個時間段內 SSRC_n 傳送的 RTP 丟失的總數目。

收到的擴充套件最大序列號:從 SSRC_n 收到的從 RTP 資料包中的最大序列號。

接收抖動(Interarrival jitter):RTP 資料包接收時間的統計方差估計。

上次 SR 時間戳(Last SR):取最近從 SSRC_n 收到的 SR 包中的 NTP 時間戳中的中間 32bit。如果還未收到 SR 包,則為 0。

上次依賴 SR 延遲(Delay since Last SR):從上次 SSRC_n 收到 SR 包到傳送本包的延遲

Wireshark 抓包:

img

活動會話的參與者在傳送和接收 RTP 分組時使用 SR。SR 有三個不同的部分:報頭資訊、傳送方資訊和許多接收方報告塊。SR 也可以有一個與大綱相關的擴充套件域。

img

Wireshark 抓包:

img

SDES:源描述

SDES 提供了傳遞與會話成員有關的標識資訊的載體,如使用者名稱、郵件、電話等。每個 RTCP 混合分組中必須有 SDES 分組。

img

報頭包含一個長度域、一個淨荷型別域(PT=202)和一個源計數(RC)域。RC 域 5 個 bit,表示分組中資訊塊的數量。

每個資訊塊包含一個 SSRC 或 CSRC 值,其後跟著一個或多個的識別符號和一些可用於 SSRC 或 CSRC 的資訊。

CNAME 項的 SDES 包必須包含在每個組合 RTCP 包中。SDES 包可能包括其他源描述項,這要根據特別的應用需要,並同時考慮頻寬限制。

Wireshark 抓包:

img

SDES 源描述包提供了直觀的文字資訊來描述會話的參加者,包括 CNAME、NAME、EMAIL、PHONE、LOC 等源描述項。

這些為接收方獲取傳送方的有關資訊提供了方便。SDES 包由包頭與資料塊組成,資料塊可以沒有,也可有多個。包頭由版本(V)、填充(P)、長度指示、包型別(PT)和源計數(SC)組成。

PT 佔 8 位,用於識別 RTCP 的 SDES 包,SC 佔 5 位,指示包含在 SDES 包中的 SSRC/CSRC 塊數量,零值有效,但沒有意義。

BYE: 通知離開

BYE 分組用於表示一個或多個媒體源不再是處於啟用狀態。

img

Wireshark 抓包:

img

作為可選項,BYE 包可包括一個 8 位八進位制計數,後跟文字資訊,表示離開原因。

最後,組合包中每個 RTCP 包可獨立處理,而不需要按照包組合的先後順序處理。

在組合包中有以下幾條強制約束。

  1. 只要頻寬允許,在 SR 包或 RR 包中的接收統計應該經常傳送,因此每個週期傳送的組合 RTCP 包中應包含報告包。
  2. 每個組合包中都應該包含 SDES CNAME,因為新接收者需要通過接收 CNAME 來識別源,並與媒體聯絡進行同步。
  3. 組合包前面是包型別數量,其增長應該受到限制。

RTCP 協議如何實現媒體流的同步

通過抓包分析 RTCP 傳送端報告,RTP 的同步其實就靠這三個域:

  1. sender SSRC :SR 包傳送的同步源識別符號。與對應 RTP 包中的 SSRC 一樣。
  2. NTP timestamp:SR 包傳送時的絕對時間。用於同步不同的流。
  3. RTP timestamp:與 NTP 時間戳對應,與 RTP 包中的時間戳具有相同的初始值。

img

那怎麼計算 NTP 時間呢?在 RTCP 中 NTP 時間存放在 8 個位元組中,分為:MSW 和 LSW,分別佔用 4 個位元組。

const char *tvb_ntp_fmt_ts_sec(u_char *rtcp_info, int offset)
{
    uint32_t tempstmp = 0;
    time_t temptime = 0;
    struct tm *bd;
    char *buff = NULL;
    
    tempstmp = ntohl(*(uint32_t*)(rtcp_info + offset));
    if (tempstmp == 0){
        return "NULL";
    }

    /* We need a temporary variable here so the unsigned math
    * works correctly (for years > 2036 according to RFC 2030
    * chapter 3).
    */
    temptime = (time_t)(tempstmp - NTP_BASETIME);
    bd = gmtime(&temptime);
    if (!bd){
        return "Not representable";
    }

    buff = (char *)malloc(NTP_TS_SIZE);
    snprintf(buff, NTP_TS_SIZE,
        "%s %2d, %d %02d:%02d:%02d UTC",
        mon_names[bd->tm_mon],
        bd->tm_mday,
        bd->tm_year + 1900,
        bd->tm_hour,
        bd->tm_min,
        bd->tm_sec);
    return buff;
}

NTP timestamp

  
    /* NTP timestamp */
    ts_msw = ntohl(*(uint32_t*)(rtcp_info + offset));
    printf("ts_msw: 0x%x\n",ts_msw);
    ts_lsw = ntohl(*(uint32_t*)(rtcp_info + offset + 4));
    printf("ts_lsw: 0x%x\n",ts_lsw);
    printf("MSW: %s\n",tvb_ntp_fmt_ts_sec(rtcp_info,offset));
    offset += 8;

RTCP 協議實現

下面我給出對 RTCP 協議解析實現的程式碼,根據回放報文,解析欄位資訊。

/* 接收者/傳送者計數是最後5位   */
#define RTCP_COUNT(octet)   ((octet) & 0x1F)


#define RTCP_PT_MIN  192
/* Supplemental H.261 specific RTCP packet types according to Section C.3.5 */
#define RTCP_FIR     192
#define RTCP_NACK    193
#define RTCP_SMPTETC 194
#define RTCP_IJ      195
/* RTCP packet types according to Section A.11.1 */
/* And https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml */
#define RTCP_SR      200
#define RTCP_RR      201
#define RTCP_SDES    202
#define RTCP_BYE     203
#define RTCP_APP     204
#define RTCP_RTPFB   205
#define RTCP_PSFB    206
#define RTCP_XR      207
#define RTCP_AVB     208
#define RTCP_RSI     209
#define RTCP_TOKEN   210

#define RTCP_PT_MAX  210


static const char mon_names[12][4] = {
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
};

/** data structure to hold time values with nanosecond resolution*/
typedef struct {
    time_t    secs;
    int    nsecs;
} nstime_t;


/*
 * 1900-01-01 00:00:00 (proleptic?) UTC.
 * Used by a number of time formats.
 */
#define EPOCH_DELTA_1900_01_01_00_00_00_UTC 2208988800U

/*
 * NTP_BASETIME is in fact epoch - ntp_start_time; ntp_start_time
 * is January 1, 2036, 00:00:00 UTC.
 */
#define NTP_BASETIME EPOCH_DELTA_1900_01_01_00_00_00_UTC
#define NTP_FLOAT_DENOM 4294967296.0
#define NTP_TS_SIZE 100


/* 解剖長度欄位。附加到此欄位的文字表示轉換為的實際位元組數 (即 (原始值 + 1) * 4) */
static int dissect_rtcp_length_field(u_char *rtcp_info, int offset)
{

    uint16_t  raw_length = ntohs(*(uint16_t*)(rtcp_info + offset));
    printf("(%u bytes)\n", (raw_length+1)*4);
    offset += 2;
    return offset;
}
static int dissect_rtcp_rr(u_char *rtcp_info, int offset,int count, int packet_length )
{
    int counter = 0;
    uint8_t  rr_flt = 0;
    int    rr_offset = offset;
    
    counter = 1;
    while ( counter <= count ) {
        uint32_t lsr = 0, dlsr = 0;

        /* Create a new subtree for a length of 24 bytes */

        /* SSRC_n source identifier, 32 bits */

        offset += 4;

        /* Fraction lost, 8bits */
        rr_flt = rtcp_info[offset];

        offset++;

        /* Cumulative number of packets lost, 24 bits */
        offset += 3;


        /* Sequence number cycles */

        offset += 2;
        /* highest sequence number received */

        offset += 2;

        /* Interarrival jitter */

        offset += 4;

        /* Last SR timestamp */
        lsr = ntohl(*(uint32_t*)(rtcp_info + offset));
        printf("Last SR timestamp: 0x%x\n",lsr);
        offset += 4;

        /* Delay since last SR timestamp */
        dlsr = ntohl(*(uint32_t*)(rtcp_info + offset));

        printf("(%d milliseconds)\n",(int)(((double)dlsr/(double)65536) * 1000.0));
        offset += 4;

        counter++;
    }

    return offset;
}

const char *tvb_ntp_fmt_ts_sec(u_char *rtcp_info, int offset)
{
    uint32_t tempstmp = 0;
    time_t temptime = 0;
    struct tm *bd;
    char *buff = NULL;
    
    tempstmp = ntohl(*(uint32_t*)(rtcp_info + offset));
    if (tempstmp == 0){
        return "NULL";
    }

    /* We need a temporary variable here so the unsigned math
    * works correctly (for years > 2036 according to RFC 2030
    * chapter 3).
    */
    temptime = (time_t)(tempstmp - NTP_BASETIME);
    bd = gmtime(&temptime);
    if (!bd){
        return "Not representable";
    }

    buff = (char *)malloc(NTP_TS_SIZE);
    snprintf(buff, NTP_TS_SIZE,
        "%s %2d, %d %02d:%02d:%02d UTC",
        mon_names[bd->tm_mon],
        bd->tm_mday,
        bd->tm_year + 1900,
        bd->tm_hour,
        bd->tm_min,
        bd->tm_sec);
    return buff;
}

static int dissect_rtcp_sr(u_char *rtcp_info, int offset,int count, int packet_length)
{

    uint32_t     ts_msw = 0, ts_lsw = 0;
    int         sr_offset = offset;

    /* NTP timestamp */
    ts_msw = ntohl(*(uint32_t*)(rtcp_info + offset));
    printf("ts_msw: 0x%x\n",ts_msw);
    ts_lsw = ntohl(*(uint32_t*)(rtcp_info + offset + 4));
    printf("ts_lsw: 0x%x\n",ts_lsw);

    //printf("offset: 0x%x 0x%x 0x%x 0x%x\n",rtcp_info[offset],rtcp_info[offset + 1],rtcp_info[offset + 2],rtcp_info[offset + 3]);
    printf("MSW: %s\n",tvb_ntp_fmt_ts_sec(rtcp_info,offset));
    offset += 8;

    /* RTP timestamp, 32 bits */
    
    offset += 4;
    /* Sender's packet count, 32 bits */

    offset += 4;
    /* Sender's octet count, 32 bits */

    offset += 4;


    /* The rest of the packet is equal to the RR packet */
    if ( count != 0 )
        offset = dissect_rtcp_rr(rtcp_info, offset, count, packet_length-(offset-sr_offset));
    else
    {
        /* If length remaining, assume profile-specific extension bytes */
        if ((offset-sr_offset) < packet_length)
        {

            offset = sr_offset + packet_length;
        }
    }

    return offset;
}

static int dissect_rtcp_sdes(u_char *rtcp_info, int offset, int count)
{
    int           chunk = 0;

    int           start_offset = 0;
    int           items_start_offset = 0;
    uint32_t       ssrc = 0;
    unsigned int  item_len = 0;
    unsigned int  sdes_type = 0;
    unsigned int  prefix_len = 0;

    chunk = 1;
    while ( chunk <= count ) 
    {
        /* Create a subtree for this chunk; we don't yet know
           the length. */
        start_offset = offset;

        ssrc = ntohl(*(uint32_t*)(rtcp_info + offset));
        printf("Chunk %u, SSRC/CSRC 0x%X\n", chunk, ssrc);

        /* SSRC_n source identifier, 32 bits */
        offset += 4;

        /* Create a subtree for the SDES items; we don't yet know
           the length */


        /*
         * Not every message is ended with "null" bytes, so check for
         * end of frame as well.
         */
         
          /* ID, 8 bits */
        sdes_type = rtcp_info[offset];
        printf("Type: %d\n",sdes_type);
        if (sdes_type == 0)
            break;
        offset++;
        /* Item length, 8 bits */
        item_len = rtcp_info[offset];
        printf("Length: %d\n",item_len);
        offset++;
        
        char *pszText = (char*)malloc(item_len);
        if (pszText != 0)
        {
            memcpy(pszText, rtcp_info + offset,item_len);
            pszText[item_len] = '\0';
            printf("Text = %s\n",pszText);
        }    

        chunk++;
    }

    return offset;
}

static void dissect_rtcp(u_char *rtcp_info,int packet_type, int offset,int PayloadLen)
{
    unsigned int  temp_byte = 0;
    int  elem_count = 0;
    int  packet_length = 0;
    int  total_packet_length = 0;
    int loop = 2;
    bool flag_rtcp = false;

        /*檢查是否為有效型別*/
        if ( ( packet_type < RTCP_PT_MIN ) || ( packet_type >  RTCP_PT_MAX ) )
            exit(-1);

        /*
         * 獲取完整的RTCP資料包的長度
         */
         
        packet_length = (ntohs(*(uint16_t*)(rtcp_info + offset + 1)) + 1) * 4 ;
        //printf("packet_length: %d\n",packet_length);

        
        temp_byte = rtcp_info[offset-1];
        elem_count = RTCP_COUNT( temp_byte );/* Source count, 5 bits */
        printf("Reception report count: %d\n",elem_count);  

        switch ( packet_type ) 
        {
            
            case RTCP_SR:
            case RTCP_RR:
                /*
                    Real-time Transport Control Protocol (Receiver Report)
                    10.. .... = Version: RFC 1889 Version (2)
                    ..0. .... = Padding: False
                    ...0 0001 = Reception report count: 1
                    Packet type: Receiver Report (201)
                    Length: 7 (32 bytes)
                    Sender SSRC: 0xb584b03e (3045371966)
                    Source 1
                */

                /* Packet type, 8 bits */
                offset++;
                /* Packet length in 32 bit words MINUS one, 16 bits */
                offset = dissect_rtcp_length_field(rtcp_info, offset);
                /* Sender Synchronization source, 32 bits */
                offset += 4;

                if ( packet_type == RTCP_SR )
                {
                    offset = dissect_rtcp_sr(rtcp_info, offset, elem_count, packet_length-8 );
                    printf("dissect_rtcp_sr\n");
                }
                else
                {    
                    offset = dissect_rtcp_rr(rtcp_info, offset, elem_count, packet_length-8 );                            
                }
                
                //uint16_t second_packet_type = ntohs(*(uint16_t*)(rtcp_info + offset));

                //printf("111offset: 0x%x 0x%x 0x%x 0x%x\n",rtcp_info[offset],rtcp_info[offset + 1],rtcp_info[offset + 2],rtcp_info[offset + 3]);
                
                if (rtcp_info[offset + 1] == RTCP_SDES)
                {
                    
                    /* Source count, 5 bits */
                    offset++;
                    /* Packet type, 8 bits */
                    offset++;
                    /* Packet length in 32 bit words MINUS one, 16 bits */
                    offset = dissect_rtcp_length_field(rtcp_info, offset);
                    offset = dissect_rtcp_sdes(rtcp_info,offset,elem_count);

                }

            break;

            default:
                /*
                 * To prevent endless loops in case of an unknown message type
                 * increase offset. Some time the while will end :-)
                 */
                offset++;
                break;

        }
        
}


static bool dissect_rtcp_heur(u_char *rtcp_info,int PayloadLen)
{
    unsigned int offset = 0;
    unsigned int first_byte = 0;
    unsigned int packet_type = 0;


    /* 檢視第一個位元組 */
    first_byte = rtcp_info[offset];

    /* 版本位是否設定為2*/
    //printf("version: %d\n",((first_byte & 0xC0) >> 6));
    if (((first_byte & 0xC0) >> 6) != 2)
    {
        return false;
    }

    /* 看包型別 */
    offset += 1;
    packet_type = rtcp_info[offset];
    //printf("packet_type: %d\n",packet_type);
    /* 複合資料包中的第一個資料包應該是傳送方或接收者報告 */
    if (!((packet_type == RTCP_SR)  || (packet_type == RTCP_RR) ||
          (packet_type == RTCP_BYE) || (packet_type == RTCP_APP) ||
          (packet_type == RTCP_PSFB)))
    {
        return false;
    }

    /*總長度必須是4個位元組的倍數*/
    //printf("PayloadLen: %d\n",PayloadLen);
    if (PayloadLen % 4)
    {
        return false;
    }

    /* OK, dissect as RTCP */
    dissect_rtcp(rtcp_info,packet_type,offset,PayloadLen);
    return true;
}


static void confirm_rtcp_packet(struct ip *pIp)
{
    int iIpTotalLen = ntohs(pIp->ip_len);
    int offset = 0;
    int nFragSeq = 0;
    struct udphdr* pUdpHdr = (struct udphdr*)((char*)pIp + (pIp->ip_hl<<2));
    if (pIp->ip_p == IPPROTO_UDP) 
    {
        printf("\n");
        
        int iPayloadLen = iIpTotalLen - (pIp->ip_hl<<2) - 8;
        printf("UDP Payload Len %d\n", iPayloadLen);
        
        u_char *pDnsHdr = (u_char*)(pUdpHdr+1);
        dissect_rtcp_heur(pDnsHdr,iPayloadLen);
        
    }    
}

編譯執行:

img

總結

RTCP 協議是流媒體通訊的基石。RTCP 協議則負責可靠傳輸、流量控制和擁塞控制等服務質量保證。上面講解了 RTCP 功能、RTCP 資料包格式及程式碼實現。最後,學習一個新的協議,最好還是研究學習官方文件,因為這是最權威的資料。

相關文章