H264Rtp.cpp 10.4 KB
Newer Older
1 2 3
/*
 * MIT License
 *
xiongziliang committed
4
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
5
 * Copyright (c) 2019 火宣 <459502659@qq.com>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
xiongziliang committed
27

xiongziliang committed
28
#include "H264Rtp.h"
xiongziliang committed
29

xiongziliang committed
30
namespace mediakit{
31

xiongziliang committed
32 33 34 35 36 37 38 39 40 41 42 43 44 45

typedef struct {
    unsigned forbidden_zero_bit :1;
    unsigned nal_ref_idc :2;
    unsigned type :5;
} NALU;

typedef struct {
    unsigned S :1;
    unsigned E :1;
    unsigned R :1;
    unsigned type :5;
} FU;

46
static bool MakeNalu(uint8_t in, NALU &nal) {
xiongziliang committed
47 48 49 50 51 52 53 54
    nal.forbidden_zero_bit = in >> 7;
    if (nal.forbidden_zero_bit) {
        return false;
    }
    nal.nal_ref_idc = (in & 0x60) >> 5;
    nal.type = in & 0x1f;
    return true;
}
55
static bool MakeFU(uint8_t in, FU &fu) {
xiongziliang committed
56 57 58 59 60 61 62 63 64 65
    fu.S = in >> 7;
    fu.E = (in >> 6) & 0x01;
    fu.R = (in >> 5) & 0x01;
    fu.type = in & 0x1f;
    if (fu.R != 0) {
        return false;
    }
    return true;
}

66
H264RtpDecoder::H264RtpDecoder() {
67
    _h264frame = obtainFrame();
68 69 70 71
}

H264Frame::Ptr  H264RtpDecoder::obtainFrame() {
    //从缓存池重新申请对象,防止覆盖已经写入环形缓存的对象
72
    auto frame = ResourcePoolHelper<H264Frame>::obtainObj();
73 74
    frame->_buffer.clear();
    frame->_prefix_size = 4;
75 76 77
    return frame;
}

xiongziliang committed
78
bool H264RtpDecoder::inputRtp(const RtpPacket::Ptr &rtp, bool key_pos) {
xiongziliang committed
79
    return decodeRtp(rtp);
xiongziliang committed
80 81
}

82
bool H264RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtppack) {
xiongziliang committed
83 84 85 86 87 88 89 90
    /**
     * h264帧类型
     * Type==1:P/B frame
     * Type==5:IDR frame
     * Type==6:SEI frame
     * Type==7:SPS frame
     * Type==8:PPS frame
     */
3503207480@qq.com committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	/*
	RTF3984 5.2节  Common Structure of the RTP Payload Format
    Table 1.  Summary of NAL unit types and their payload structures

	   Type   Packet    Type name                        Section
	   ---------------------------------------------------------
	   0      undefined                                    -
	   1-23   NAL unit  Single NAL unit packet per H.264   5.6
	   24     STAP-A    Single-time aggregation packet     5.7.1
	   25     STAP-B    Single-time aggregation packet     5.7.1
	   26     MTAP16    Multi-time aggregation packet      5.7.2
	   27     MTAP24    Multi-time aggregation packet      5.7.2
	   28     FU-A      Fragmentation unit                 5.8
	   29     FU-B      Fragmentation unit                 5.8
	   30-31  undefined                                    -


	*/
xiongziliang committed
109 110
    const uint8_t *frame = (uint8_t *) rtppack->data() + rtppack->offset;
    int length = rtppack->size() - rtppack->offset;
xiongziliang committed
111 112 113 114 115
    NALU nal;
    MakeNalu(*frame, nal);

    if (nal.type >= 0 && nal.type < 24) {
        //a full frame
116 117 118
        _h264frame->_buffer.assign("\x0\x0\x0\x1", 4);
        _h264frame->_buffer.append((char *)frame, length);
        _h264frame->_pts = rtppack->timeStamp;
119
        auto key = _h264frame->keyFrame();
120
        onGetH264(_h264frame);
121
        return (key); //i frame
xiongziliang committed
122 123
    }

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    switch (nal.type){
        case 24:{
            // 24 STAP-A   单一时间的组合包
            bool haveIDR = false;
            auto ptr = frame + 1;
            while(true){
                int off = ptr - frame;
                if (off >= length) {
                    break;
                }
                //获取当前nalu的大小
                uint16_t len = *ptr++;
                len <<= 8;
                len |= *ptr++;
                if (off + len > length) {
                    break;
                }
                if(len >= 10){
                    //过小的帧丢弃
                    NALU nal;
                    MakeNalu(ptr[0], nal);
145 146 147
                    _h264frame->_buffer.assign("\x0\x0\x0\x1", 4);
                    _h264frame->_buffer.append((char *)ptr, len);
                    _h264frame->_pts = rtppack->timeStamp;
148 149 150 151 152 153 154 155
                    if(nal.type == H264Frame::NAL_IDR){
                        haveIDR = true;
                    }
                    onGetH264(_h264frame);
                }
                ptr += len;
            }
            return haveIDR;
xiongziliang committed
156 157
        }

158 159 160 161
        case 28:{
            //FU-A
            FU fu;
            MakeFU(frame[1], fu);
162
            if (fu.S) {
3503207480@qq.com committed
163
                //该帧的第一个rtp包  FU-A start
164
                char tmp = (nal.forbidden_zero_bit << 7 | nal.nal_ref_idc << 5 | fu.type);
165 166 167 168
                _h264frame->_buffer.assign("\x0\x0\x0\x1", 4);
                _h264frame->_buffer.push_back(tmp);
                _h264frame->_buffer.append((char *)frame + 2, length - 2);
                _h264frame->_pts = rtppack->timeStamp;
169 170 171
                //该函数return时,保存下当前sequence,以便下次对比seq是否连续
                _lastSeq = rtppack->sequence;
                return _h264frame->keyFrame();
172 173
            }

174 175
            if (rtppack->sequence != _lastSeq + 1 && rtppack->sequence != 0) {
                //中间的或末尾的rtp包,其seq必须连续(如果回环了则判定为连续),否则说明rtp丢包,那么该帧不完整,必须得丢弃
176
                _h264frame->_buffer.clear();
177
                WarnL << "rtp sequence不连续: " << rtppack->sequence << " != " << _lastSeq << " + 1,该帧被废弃";
178 179
                return false;
            }
180 181

            if (!fu.E) {
3503207480@qq.com committed
182
                //该帧的中间rtp包  FU-A mid
183
                _h264frame->_buffer.append((char *)frame + 2, length - 2);
184 185 186
                //该函数return时,保存下当前sequence,以便下次对比seq是否连续
                _lastSeq = rtppack->sequence;
                return false;
187
            }
188

3503207480@qq.com committed
189
            //该帧最后一个rtp包  FU-A end
190 191
            _h264frame->_buffer.append((char *)frame + 2, length - 2);
            _h264frame->_pts = rtppack->timeStamp;
192
            onGetH264(_h264frame);
193
            return false;
xiongziliang committed
194
        }
195 196 197 198 199 200 201 202 203 204 205

        default:{
            // 29 FU-B     单NAL单元B模式
            // 25 STAP-B   单一时间的组合包
            // 26 MTAP16   多个时间的组合包
            // 27 MTAP24   多个时间的组合包
            // 0 udef
            // 30 udef
            // 31 udef
            WarnL << "不支持的rtp类型:" << (int)nal.type << " " << rtppack->sequence;
            return false;
xiongziliang committed
206 207 208 209
        }
    }
}

xiongziliang committed
210
void H264RtpDecoder::onGetH264(const H264Frame::Ptr &frame) {
211
    auto flag = _dts_generator.getDts(frame->_pts,frame->_dts);
212 213 214 215 216 217 218 219
    if(!flag){
        if(frame->configFrame() || frame->keyFrame()){
            flag = true;
            frame->_dts = frame->_pts;
        }
    }

    //根据pts计算dts
220 221 222 223
    if(flag){
        //写入环形缓存
        RtpCodec::inputFrame(frame);
    }
224
    _h264frame = obtainFrame();
xiongziliang committed
225
}
xiongziliang committed
226

227

xiongziliang committed
228 229 230 231 232 233 234
////////////////////////////////////////////////////////////////////////

H264RtpEncoder::H264RtpEncoder(uint32_t ui32Ssrc,
                               uint32_t ui32MtuSize,
                               uint32_t ui32SampleRate,
                               uint8_t ui8PlayloadType,
                               uint8_t ui8Interleaved) :
235 236 237 238 239
        RtpInfo(ui32Ssrc,
                ui32MtuSize,
                ui32SampleRate,
                ui8PlayloadType,
                ui8Interleaved) {
xiongziliang committed
240 241
}

242
void H264RtpEncoder::inputFrame(const Frame::Ptr &frame) {
243
    GET_CONFIG(uint32_t,cycleMS,Rtp::kCycleMS);
244
    auto pcData = frame->data() + frame->prefixSize();
245
    auto uiStamp = frame->pts();
246
    auto iLen = frame->size() - frame->prefixSize();
xiongziliang committed
247 248
    //获取NALU的5bit 帧类型
    unsigned char naluType =  H264_TYPE(pcData[0]);
xiongziliang committed
249 250

    uiStamp %= cycleMS;
251
    int iSize = _ui32MtuSize - 2;
xiongziliang committed
252 253 254 255 256 257 258
    //超过MTU则按照FU-A模式打包
    if (iLen > iSize) {
        //最高位bit为forbidden_zero_bit,
        //后面2bit为nal_ref_idc(帧重要程度),00:可以丢,11:不能丢
        //末尾5bit为nalu type,固定为28(FU-A)
        unsigned char f_nri_flags = (*((unsigned char *) pcData) & 0x60) | 28;
        unsigned char s_e_r_flags;
xiongziliang committed
259 260 261 262
        bool bFirst = true;
        bool mark = false;
        int nOffset = 1;
        while (!mark) {
xiongziliang committed
263 264
            if (iLen < nOffset + iSize) {
                //已经拆分结束
xiongziliang committed
265 266
                iSize = iLen - nOffset;
                mark = true;
xiongziliang committed
267 268 269 270 271
                //FU-A end
                s_e_r_flags = (1 << 6) | naluType;
            } else if (bFirst) {
                //FU-A start
                s_e_r_flags = (1 << 7) | naluType;
xiongziliang committed
272
            } else {
xiongziliang committed
273 274
                //FU-A mid
                s_e_r_flags = naluType;
xiongziliang committed
275
            }
276 277 278 279 280 281 282

            {
                //传入nullptr先不做payload的内存拷贝
                auto rtp = makeRtp(getTrackType(), nullptr, iSize + 2, mark, uiStamp);
                //rtp payload 负载部分
                uint8_t *payload = (uint8_t*)rtp->data() + rtp->offset;
                //FU-A 第1个字节
xiongziliang committed
283
                payload[0] = f_nri_flags;
284
                //FU-A 第2个字节
xiongziliang committed
285
                payload[1] = s_e_r_flags;
286 287 288 289 290
                //H264 数据
                memcpy(payload + 2, (unsigned char *) pcData + nOffset, iSize);
                //输入到rtp环形缓存
                RtpCodec::inputRtp(rtp,bFirst && naluType == H264Frame::NAL_IDR);
            }
xiongziliang committed
291
            nOffset += iSize;
292
            bFirst = false;
xiongziliang committed
293 294
        }
    } else {
295
        makeH264Rtp(naluType,pcData, iLen, true, true, uiStamp);
xiongziliang committed
296 297 298
    }
}

299 300
void H264RtpEncoder::makeH264Rtp(int nal_type,const void* data, unsigned int len, bool mark, bool first_packet, uint32_t uiStamp) {
    RtpCodec::inputRtp(makeRtp(getTrackType(),data,len,mark,uiStamp),first_packet && nal_type == H264Frame::NAL_IDR);
xiongziliang committed
301 302 303
}

}//namespace mediakit