1. 程式人生 > >TS流之代碼分析

TS流之代碼分析

xtra new 校正 reat ted 跟著 ror enable 好的

  代碼分析前,先要了解TS流基本概念:TS流之基本概念。

  VLC解析TS流是通過libts庫來分離的,libts庫使用libdvbpsi庫來解TS表。

1. libts庫在加載的時候,會將以下如下兩個函數註冊下去,當接收到PAT或者PMT的時候,會進行調用。PAT和PMT每隔一段時間就會發送一次,以更新節目信息。

static void PATCallBack( void*, dvbpsi_pat_t * );
static void PMTCallBack( void *data, dvbpsi_pmt_t *p_pmt );

2. PATCallBack回調函數,獲取並保存所有節目列表及其PID。

static void PATCallBack( void *data, dvbpsi_pat_t *p_pat )
{
    demux_t              *p_demux = (demux_t *)data;
    demux_sys_t          *p_sys = p_demux->p_sys;
    dvbpsi_pat_program_t *p_program;
    ts_pid_t             *pat = &p_sys->pid[0];

    msg_Dbg( p_demux, "PATCallBack called
" ); if( ( pat->psi->i_pat_version != -1 && ( !p_pat->b_current_next || p_pat->i_version == pat->psi->i_pat_version ) ) || p_sys->b_user_pmt ) { dvbpsi_DeletePAT( p_pat ); return; } msg_Dbg( p_demux, "new PAT ts_id=%d version=%d current_next=%d
", p_pat->i_ts_id, p_pat->i_version, p_pat->b_current_next );
  ......
/* now create programs */ for( p_program = p_pat->p_first_program; p_program != NULL; p_program = p_program->p_next ) { // 依次輸出PAT表中的節目,包括其number和PID msg_Dbg( p_demux, " * number=%d pid=%d", p_program->i_number, p_program->i_pid ); if( p_program->i_number == 0 ) continue; // 節目的PID就是它所對應的PMT,這裏獲取該節目對應的PMT ts_pid_t *pmt = &p_sys->pid[p_program->i_pid]; ValidateDVBMeta( p_demux, p_program->i_pid ); if( pmt->b_valid ) { bool b_add = true; for( int i_prg = 0; b_add && i_prg < pmt->psi->i_prg; i_prg++ ) if( pmt->psi->prg[i_prg]->i_number == p_program->i_number ) b_add = false; if( !b_add ) continue; } else { TAB_APPEND( (ts_pid_t **), p_sys->i_pmt, p_sys->pmt, pmt ); // sunqueen modify } PIDInit( pmt, true, pat->psi ); ts_prg_psi_t *prg = pmt->psi->prg[pmt->psi->i_prg-1];     
    ......
// 註冊PMT回調函數 prg->handle = dvbpsi_AttachPMT( p_program->i_number, PMTCallBack, p_demux ); prg->i_number = p_program->i_number; prg->i_pid_pmt = p_program->i_pid; /* Now select PID at access level */ if( ProgramIsSelected( p_demux, p_program->i_number ) ) { if( p_sys->i_current_program == 0 ) p_sys->i_current_program = p_program->i_number; if( SetPIDFilter( p_demux, p_program->i_pid, true ) ) p_sys->b_access_control = false; } } pat->psi->i_pat_version = p_pat->i_version; dvbpsi_DeletePAT( p_pat ); }

3. PMTCallBack與PATCallBack類似,主要是循環讀取某一節目的碼流列表及及其PID,不再贅述。

4. Demux分離,使用GatherData收集一幀。

static int Demux( demux_t *p_demux )
{
    demux_sys_t *p_sys = p_demux->p_sys;
    bool b_wait_es = p_sys->i_pmt_es <= 0;

    /* We read at most 100 TS packet or until a frame is completed */
    for( int i_pkt = 0; i_pkt < p_sys->i_ts_read; i_pkt++ )
    {
        bool         b_frame = false;
        block_t     *p_pkt;
        if( !(p_pkt = ReadTSPacket( p_demux )) )
        {
            return 0;
        }

        if( p_sys->b_start_record )
        {
            /* Enable recording once synchronized */
            stream_Control( p_demux->s, STREAM_SET_RECORD_STATE, true, "ts" );
            p_sys->b_start_record = false;
        }

        if( p_sys->b_udp_out )
        {
            memcpy( &p_sys->buffer[i_pkt * p_sys->i_packet_size],
                    p_pkt->p_buffer, p_sys->i_packet_size );
        }

        /* Parse the TS packet */
        ts_pid_t *p_pid = &p_sys->pid[PIDGet( p_pkt )];
        // 這裏可以把接收到的包的pid打出來,方便調試
        msg_Dbg( p_demux, "received pkt pid[%d]", PIDGet( p_pkt ) );

        if( p_pid->b_valid )
        {
            // 如果當前包是PSI信息,使用dvbpsi庫解表
            if( p_pid->psi )
            {
                // 如果是PAT或者0x11 0x12等
                if( p_pid->i_pid == 0 || ( p_sys->b_dvb_meta && ( p_pid->i_pid == 0x11 || p_pid->i_pid == 0x12 || p_pid->i_pid == 0x14 ) ) )
                {
                    dvbpsi_PushPacket( p_pid->psi->handle, p_pkt->p_buffer );
                }
                else
                {
                    for( int i_prg = 0; i_prg < p_pid->psi->i_prg; i_prg++ )
                    {
                        dvbpsi_PushPacket( p_pid->psi->prg[i_prg]->handle,
                                           p_pkt->p_buffer );
                    }
                }
                block_Release( p_pkt );
            }
       // 如果當前的包是數據,則收集 
else if( !p_sys->b_udp_out ) { // 返回值為是否已經獲取了一整幀的數據 b_frame = GatherData( p_demux, p_pid, p_pkt ); } else { PCRHandle( p_demux, p_pid, p_pkt ); block_Release( p_pkt ); } } else { if( !p_pid->b_seen ) { msg_Dbg( p_demux, "pid[%d] unknown", p_pid->i_pid ); } /* We have to handle PCR if present */ PCRHandle( p_demux, p_pid, p_pkt ); block_Release( p_pkt ); } p_pid->b_seen = true; if( b_frame || ( b_wait_es && p_sys->i_pmt_es > 0 ) ) break; } if( p_sys->b_udp_out ) { /* Send the complete block */ net_Write( p_demux, p_sys->fd, NULL, p_sys->buffer, p_sys->i_ts_read * p_sys->i_packet_size ); } return 1; }

5. GatherData解析TS包

// 解析TS包
static bool GatherData( demux_t *p_demux, ts_pid_t *pid, block_t *p_bk )
{
    const uint8_t *p = p_bk->p_buffer;// 第一個字節(8位)為同步字節,此處沒有獲取
    const bool b_unit_start = p[1]&0x40;// payload_unit_start_indicator是否被置位
    const bool b_scrambled  = p[3]&0x80;// 是否加擾
    const bool b_adaptation = p[3]&0x20;// 是否有調整字段控制
    const bool b_payload    = p[3]&0x10;// 有無payload
    const int  i_cc         = p[3]&0x0f; /* continuity counter */// 獲取連續的計數
    bool       b_discontinuity = false;  /* discontinuity */

    /* transport_scrambling_control is ignored */
    int         i_skip = 0;
    bool        i_ret  = false;
    /* For now, ignore additional error correction
     * TODO: handle Reed-Solomon 204,188 error correction */
    // 目前暫時忽略擴展錯誤糾正的情況
    p_bk->i_buffer = TS_PACKET_SIZE_188;

    // 至少發生了1位錯誤,且不可糾正
    if( p[1]&0x80 )
    {
        msg_Dbg( p_demux, "transport_error_indicator set (pid=%d)",
                 pid->i_pid );
        if( pid->es->p_data ) //&& pid->es->fmt.i_cat == VIDEO_ES )
            pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
    }

    if( p_demux->p_sys->csa )
    {
        vlc_mutex_lock( &p_demux->p_sys->csa_lock );
        csa_Decrypt( p_demux->p_sys->csa, p_bk->p_buffer, p_demux->p_sys->i_csa_pkt_size );
        vlc_mutex_unlock( &p_demux->p_sys->csa_lock );
    }

    if( !b_adaptation )
    {
        /* We don‘t have any adaptation_field, so payload starts
         * immediately after the 4 byte TS header */
        // 沒有調整字段,所以有效凈荷緊跟著4個字節的TS頭
        i_skip = 4;
    }
    else
    {
        /* p[4] is adaptation_field_length minus one */
        // 如果有調整字段,那麽TS頭後的第一個字節就是調整字段的長度
        i_skip = 5 + p[4];
        if( p[4] > 0 )
        {
            /* discontinuity indicator found in stream */
            b_discontinuity = (p[5]&0x80) ? true : false;
            if( b_discontinuity && pid->es->p_data )
            {
                msg_Warn( p_demux, "discontinuity indicator (pid=%d) ",
                            pid->i_pid );
                /* pid->es->p_data->i_flags |= BLOCK_FLAG_DISCONTINUITY; */
            }
        }
    }

    /* Test continuity counter */
    /* continuous when (one of this):
        * diff == 1
        * diff == 0 and payload == 0
        * diff == 0 and duplicate packet (playload != 0) <- should we
        *   test the content ?
     */
    const int i_diff = ( i_cc - pid->i_cc )&0x0f;
    if( b_payload && i_diff == 1 )
    {
        pid->i_cc = ( pid->i_cc + 1 ) & 0xf;
    }
    else
    {
        if( pid->i_cc == 0xff )
        {
            msg_Warn( p_demux, "first packet for pid=%d cc=0x%x",
                      pid->i_pid, i_cc );
            pid->i_cc = i_cc;
        }
        else if( i_diff != 0 && !b_discontinuity )
        {
            msg_Warn( p_demux, "discontinuity received 0x%x instead of 0x%x (pid=%d)",
                      i_cc, ( pid->i_cc + 1 )&0x0f, pid->i_pid );

            pid->i_cc = i_cc;
            if( pid->es->p_data && pid->es->fmt.i_cat != VIDEO_ES )
            {
                /* Small video artifacts are usually better than
                 * dropping full frames */
                pid->es->p_data->i_flags |= BLOCK_FLAG_CORRUPTED;
            }
        }
    }

    // 校正PCR
    PCRHandle( p_demux, pid, p_bk );

    if( i_skip >= 188 || pid->es->id == NULL || p_demux->p_sys->b_udp_out )
    {
        block_Release( p_bk );
        return i_ret;
    }

    /* */
    if( !pid->b_scrambled != !b_scrambled )
    {
        msg_Warn( p_demux, "scrambled state changed on pid %d (%d->%d)",
                  pid->i_pid, pid->b_scrambled, b_scrambled );

        pid->b_scrambled = b_scrambled;

        for( int i = 0; i < pid->i_extra_es; i++ )
        {
            es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
                            pid->extra_es[i]->id, b_scrambled );
        }
        es_out_Control( p_demux->out, ES_OUT_SET_ES_SCRAMBLED_STATE,
                        pid->es->id, b_scrambled );
    }

    /* We have to gather it */
    p_bk->p_buffer += i_skip;
    p_bk->i_buffer -= i_skip;

    if( b_unit_start )
    {
        if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION && p_bk->i_buffer > 0 )
        {
            int i_pointer_field = __MIN( p_bk->p_buffer[0], p_bk->i_buffer - 1 );
            block_t *p = block_Duplicate( p_bk );
            if( p )
            {
                p->i_buffer = i_pointer_field;
                p->p_buffer++;
                block_ChainLastAppend( &pid->es->pp_last, p );
            }
            p_bk->i_buffer -= 1 + i_pointer_field;
            p_bk->p_buffer += 1 + i_pointer_field;
        }
        if( pid->es->p_data )
        {
            ParseData( p_demux, pid );
            i_ret = true;
        }

        block_ChainLastAppend( &pid->es->pp_last, p_bk );
        if( pid->es->data_type == TS_ES_DATA_PES )
        {
            if( p_bk->i_buffer > 6 )
            {
                // 一個PES包含一幀圖像,此時獲取PES包的長度
                // 當收集到的數據大於等於i_data_size時,將接收到的一整幀圖像放入block中
                // 等待解碼線程解碼
                // PES包頭為24位(3個字節),流ID為8位(1個字節),故PES包長度從第5個字節開始
                pid->es->i_data_size = GetWBE( &p_bk->p_buffer[4] );
                if( pid->es->i_data_size > 0 )
                {
                    pid->es->i_data_size += 6;
                }
            }
        }
        else if( pid->es->data_type == TS_ES_DATA_TABLE_SECTION )
        {
            if( p_bk->i_buffer > 3 && p_bk->p_buffer[0] != 0xff )
            {
                pid->es->i_data_size = 3 + (((p_bk->p_buffer[1] & 0xf) << 8) | p_bk->p_buffer[2]);
            }
        }
        pid->es->i_data_gathered += p_bk->i_buffer;
        if( pid->es->i_data_size > 0 &&
            pid->es->i_data_gathered >= pid->es->i_data_size )
        {
            ParseData( p_demux, pid );
            i_ret = true;
        }
    }
    else
    {
        if( pid->es->p_data == NULL )
        {
            /* msg_Dbg( p_demux, "broken packet" ); */
            block_Release( p_bk );
        }
        else
        {
            block_ChainLastAppend( &pid->es->pp_last, p_bk );
            pid->es->i_data_gathered += p_bk->i_buffer;

            if( pid->es->i_data_size > 0 &&
                pid->es->i_data_gathered >= pid->es->i_data_size )
            {
                // 認為此時已經獲取了一整幀數據,那麽push到block的隊列中等待解碼線程解碼
                ParseData( p_demux, pid );
                i_ret = true;
            }
        }
    }

    return i_ret;
}

  附:

  配置好的Windows版vlc工程下載:https://github.com/jiayayao/vlc_2.1.0-vs_2010,下載後使用vs2010可以直接編譯運行,調試學習非常方便。

  

TS流之代碼分析