首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

ortp 庫 C++ 封裝實戰:RTP 收發端類設計與 Windows 測試範例

     編輯:關於C語言

應網友需求,整理 ortp (oRTP 0.9.1) 程式設計範例。環境:VS2008 + Windows,語言 C++,對 C 風格 ortp API 進行 RAII 風格封裝。完整工程見附件,編譯後開兩個執行個體,一選 Client 一選 Server 即可測試。

架構概覽

  • COrtpClient:接收端封裝,負責建立 RTP_SESSION_RECVONLY 會話、自適應抖動補償、阻塞式接收。
  • COrtpServer:發送端封裝,負責 RTP_SESSION_SENDONLY 會話、遠端地址設定、時間戳遞增發送。
  • 共通:靜態 init()/deInit() 管理 Winsock 與 ortp 庫全域初始化/清理;Payload Type 34 (視訊)、時間戳增量 3600 (90kHz 時鐘下 40ms/幀)。

核心介面設計

接收端 COrtpClient

class COrtpClient {
public:
    COrtpClient(); ~COrtpClient();
    static bool init();       // WSAStartup + ortp_init + ortp_scheduler_init
    static bool deInit();     // ortp_exit + WSACleanup
    bool create(const char* localip, int localport); // 綁定本地 IP:Port
    bool get_recv_data(char* pBuffer, int& len);     // 循環 rtp_session_recv_with_ts 直到 have_more=0
private:
    RtpSession* m_pSession;
    long m_curTimeStamp;
    int  m_timeStampInc; // 3600
};

發送端 COrtpServer

class COrtpServer {
public:
    COrtpServer(); ~COrtpServer();
    static bool init(); static bool deInit();
    bool create(const char* destIP, int destport);   // 設定遠端地址
    int  send_data(unsigned char* buffer, int len);  // rtp_session_send_with_ts + 時間戳遞增
private:
    RtpSession* m_pSession;
    long m_curTimeStamp;
    int  m_timeStampInc;
    char* m_ssrc; // 可選 SSRC
};

關鍵實現細節

  • 阻塞 + 排程模式:rtp_session_set_blocking_mode(1) + rtp_session_set_scheduling_mode(1),簡化同步邏輯。
  • 自適應抖動緩衝:rtp_session_enable_adaptive_jitter_compensation(1) + rtp_session_set_jitter_compensation(40) (ms)。
  • 時間戳管理:發送端每次 send_data 後 m_curTimeStamp += m_timeStampInc;接收端每次 get_recv_data 成功後同步遞增,確保同步。
  • 分片接收:get_recv_data 內部循環 rtp_session_recv_with_ts,累積至緩衝區或達 have_more=0,單次讀取上限 1024 位元組。

測試主程式邏輯

void main() {
    cout << "1-Client  2-Server: ";
    int num; cin >> num;
    if (num == 1) {
        COrtpClient::init();
        COrtpClient client;
        client.create("127.0.0.1", 8000);
        char buf[10*1024];
        while (1) {
            int len = sizeof(buf);
            if (client.get_recv_data(buf, len))
                cout << "recv " << len << " bytes\n";
            else Sleep(10);
        }
    } else if (num == 2) {
        COrtpServer::init();
        COrtpServer server;
        server.create("127.0.0.1", 8000);
        unsigned char buf[8*1024];
        while (1) {
            server.send_data(buf, sizeof(buf));
            cout << "send bytes\n";
            Sleep(100);
        }
    }
}

常見坑與注意事項

  1. 防火牆:本機回環通常無礙,跨機需開放 UDP 8000。
  2. Payload Type 一致:雙端必須設定相同 PT (範例用 34),否則接收端會丟棄封包。
  3. 時間戳單位:ortp 內部以 90kHz 為基準 (視訊常用),3600 = 40ms,對應 25fps。
  4. SSRC:可透過環境變數 SSRC 指定,否則庫自動產生。
  5. 版本相容:範例基於 ortp-0.9.1,新版 API 可能有變動,遷移時請查閱 ortp.h。

本文出自「對影成三人」部落格,轉載請保留出處:原文連結

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved