H265Rtp.cpp 8.12 KB
Newer Older
1 2 3
/*
 * MIT License
 *
xiongziliang committed
4
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
5 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
#include "H265Rtp.h"
28 29 30

namespace mediakit{

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
//41
//42              0                   1
//43              0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
//44             +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//45             |F|   Type    |  LayerId  | TID |
//46             +-------------+-----------------+
//48                F       = 0
//49                Type    = 49 (fragmentation unit (FU))
//50                LayerId = 0
//51                TID     = 1
//56         /*
//57               create the FU header
//58
//59               0 1 2 3 4 5 6 7
//60              +-+-+-+-+-+-+-+-+
//61              |S|E|  FuType   |
//62              +---------------+
//63
//64                 S       = variable
//65                 E       = variable
//66                 FuType  = NAL unit type
//67
53 54 55 56

typedef struct {
    unsigned S :1;
    unsigned E :1;
57
    unsigned type :6;
58 59
} FU;

60
static void MakeFU(uint8_t in, FU &fu) {
61 62
    fu.S = in >> 7;
    fu.E = (in >> 6) & 0x01;
63
    fu.type = in & 0x3f;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
}

H265RtpDecoder::H265RtpDecoder() {
    _h265frame = obtainFrame();
}

H265Frame::Ptr  H265RtpDecoder::obtainFrame() {
    //从缓存池重新申请对象,防止覆盖已经写入环形缓存的对象
    auto frame = ResourcePoolHelper<H265Frame>::obtainObj();
    frame->buffer.clear();
    frame->iPrefixSize = 4;
    return frame;
}

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

bool H265RtpDecoder::decodeRtp(const RtpPacket::Ptr &rtppack) {
xiongziliang committed
83 84
    const uint8_t *frame = (uint8_t *) rtppack->data() + rtppack->offset;
    int length = rtppack->size() - rtppack->offset;
85
    int nal = H265_TYPE(frame[0]);
86

87 88 89 90 91 92 93 94 95 96 97 98
    if (nal > 50){
        WarnL << "不支持该类型的265 RTP包" << nal;
        return false; // packet discard, Unsupported (HEVC) NAL type
    }
    switch (nal) {
        case 50:
        case 48: // aggregated packet (AP) - with two or more NAL units
            WarnL << "不支持该类型的265 RTP包" << nal;
            return false;
        case 49: {
            // fragmentation unit (FU)
            FU fu;
99
            MakeFU(frame[2], fu);
xiongziliang committed
100 101
            if (fu.S) {
                //该帧的第一个rtp包
102 103 104
                _h265frame->buffer.assign("\x0\x0\x0\x1", 4);
                _h265frame->buffer.push_back(fu.type << 1);
                _h265frame->buffer.push_back(0x01);
105
                _h265frame->buffer.append((char *) frame + 3, length - 3);
106
                _h265frame->timeStamp = rtppack->timeStamp;
xiongziliang committed
107 108
                //该函数return时,保存下当前sequence,以便下次对比seq是否连续
                _lastSeq = rtppack->sequence;
109 110 111
                return (_h265frame->keyFrame()); //i frame
            }

xiongziliang committed
112 113
            if (rtppack->sequence != _lastSeq + 1 && rtppack->sequence != 0) {
                //中间的或末尾的rtp包,其seq必须连续(如果回环了则判定为连续),否则说明rtp丢包,那么该帧不完整,必须得丢弃
114
                _h265frame->buffer.clear();
xiongziliang committed
115
                WarnL << "rtp sequence不连续: " << rtppack->sequence << " != " << _lastSeq << " + 1,该帧被废弃";
116 117
                return false;
            }
xiongziliang committed
118 119 120

            if (!fu.E) {
                //该帧的中间rtp包
121
                _h265frame->buffer.append((char *) frame + 3, length - 3);
xiongziliang committed
122 123 124
                //该函数return时,保存下当前sequence,以便下次对比seq是否连续
                _lastSeq = rtppack->sequence;
                return false;
125
            }
xiongziliang committed
126 127

            //该帧最后一个rtp包
128
            _h265frame->buffer.append((char *) frame + 3, length - 3);
xiongziliang committed
129 130 131 132
            _h265frame->timeStamp = rtppack->timeStamp;
            auto key = _h265frame->keyFrame();
            onGetH265(_h265frame);
            return key;
133
        }
134

135 136 137 138
        default: // 4.4.1. Single NAL Unit Packets (p24)
            //a full frame
            _h265frame->buffer.assign("\x0\x0\x0\x1", 4);
            _h265frame->buffer.append((char *)frame, length);
139
            _h265frame->timeStamp = rtppack->timeStamp;
xiongziliang committed
140
            auto key = _h265frame->keyFrame();
141
            onGetH265(_h265frame);
xiongziliang committed
142
            return key;
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    }
}

void H265RtpDecoder::onGetH265(const H265Frame::Ptr &frame) {
    //写入环形缓存
    RtpCodec::inputFrame(frame);
    _h265frame = obtainFrame();
}


////////////////////////////////////////////////////////////////////////

H265RtpEncoder::H265RtpEncoder(uint32_t ui32Ssrc,
                               uint32_t ui32MtuSize,
                               uint32_t ui32SampleRate,
                               uint8_t ui8PlayloadType,
                               uint8_t ui8Interleaved) :
        RtpInfo(ui32Ssrc,
                ui32MtuSize,
                ui32SampleRate,
                ui8PlayloadType,
                ui8Interleaved) {
}

void H265RtpEncoder::inputFrame(const Frame::Ptr &frame) {
168
    GET_CONFIG(uint32_t,cycleMS,Rtp::kCycleMS);
169
    uint8_t *pcData = (uint8_t*)frame->data() + frame->prefixSize();
170 171
    auto uiStamp = frame->stamp();
    auto iLen = frame->size() - frame->prefixSize();
172
    unsigned char naluType = H265_TYPE(pcData[0]); //获取NALU的5bit 帧类型
173
    uiStamp %= cycleMS;
174 175

    int maxSize = _ui32MtuSize - 3;
xiongziliang committed
176 177
    //超过MTU,按照FU方式打包
    if (iLen > maxSize) {
178
        //获取帧头数据,1byte
xiongziliang committed
179
        unsigned char s_e_flags;
180 181
        bool bFirst = true;
        bool mark = false;
182
        int nOffset = 2;
183
        while (!mark) {
184 185
            if (iLen < nOffset + maxSize) {			//是否拆分结束
                maxSize = iLen - nOffset;
186
                mark = true;
xiongziliang committed
187
                //FU end
xiongziliang committed
188
                s_e_flags = (1 << 6) | naluType;
189
            } else if (bFirst) {
xiongziliang committed
190
                //FU start
xiongziliang committed
191
                s_e_flags = (1 << 7) | naluType;
192
            } else {
xiongziliang committed
193
                //FU mid
xiongziliang committed
194
                s_e_flags = naluType;
195
            }
196

197 198 199 200 201
            {
                //传入nullptr先不做payload的内存拷贝
                auto rtp = makeRtp(getTrackType(), nullptr, maxSize + 3, mark, uiStamp);
                //rtp payload 负载部分
                uint8_t *payload = (uint8_t*)rtp->data() + rtp->offset;
xiongziliang committed
202
                //FU 第1个字节,表明为FU
203
                payload[0] = 49 << 1;
xiongziliang committed
204
                //FU 第2个字节貌似固定为1
205
                payload[1] = 1;
xiongziliang committed
206
                //FU 第3个字节
xiongziliang committed
207
                payload[2] = s_e_flags;
208 209 210 211 212 213
                //H265 数据
                memcpy(payload + 3,pcData + nOffset, maxSize);
                //输入到rtp环形缓存
                RtpCodec::inputRtp(rtp,bFirst && H265Frame::isKeyFrame(naluType));
            }

214
            nOffset += maxSize;
215
            bFirst = false;
216 217
        }
    } else {
218
        makeH265Rtp(naluType,pcData, iLen, true, true, uiStamp);
219 220 221
    }
}

222 223
void H265RtpEncoder::makeH265Rtp(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 && H265Frame::isKeyFrame(nal_type));
224 225 226
}

}//namespace mediakit