H264.h 9.22 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
3 4 5
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
xiongziliang committed
6 7 8
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
9
 */
xiongziliang committed
10

11 12
#ifndef ZLMEDIAKIT_H264_H
#define ZLMEDIAKIT_H264_H
xiongziliang committed
13 14

#include "Frame.h"
15
#include "Track.h"
xiongziliang committed
16 17
#include "Util/base64.h"
using namespace toolkit;
xiongziliang committed
18 19
#define H264_TYPE(v) ((uint8_t)(v) & 0x1F)

xiongziliang committed
20
namespace mediakit{
xiongziliang committed
21

22
bool getAVCInfo(const string &strSps,int &iVideoWidth, int &iVideoHeight, float  &iVideoFps);
23
void splitH264(const char *ptr, int len, int prefix, const std::function<void(const char *, int, int)> &cb);
xiongziliang committed
24

xiongziliang committed
25
/**
26
 * 264帧类
xiongziliang committed
27
 */
xiongziliang committed
28
class H264Frame : public FrameImp {
xiongziliang committed
29
public:
30
    typedef std::shared_ptr<H264Frame> Ptr;
xiongziliang committed
31

xiongziliang committed
32 33 34 35
    typedef enum {
        NAL_SPS = 7,
        NAL_PPS = 8,
        NAL_IDR = 5,
36
        NAL_SEI = 6,
xiongziliang committed
37 38
    } NalType;

xiongziliang committed
39 40
    H264Frame(){
        _codecid = CodecH264;
41
    }
42

43
    bool keyFrame() const override {
44
        return H264_TYPE(_buffer[_prefix_size]) == H264Frame::NAL_IDR;
45
    }
xiongziliang committed
46 47

    bool configFrame() const override{
48
        switch(H264_TYPE(_buffer[_prefix_size]) ){
xiongziliang committed
49
            case H264Frame::NAL_SPS:
xiongziliang committed
50 51
            case H264Frame::NAL_PPS:return true;
            default:return false;
xiongziliang committed
52 53
        }
    }
xiongziliang committed
54 55
};

56 57 58 59 60
/**
 * 防止内存拷贝的H264类
 * 用户可以通过该类型快速把一个指针无拷贝的包装成Frame类
 * 该类型在DevChannel中有使用
 */
xiongziliang committed
61
class H264FrameNoCacheAble : public FrameFromPtr {
xiongziliang committed
62
public:
63
    typedef std::shared_ptr<H264FrameNoCacheAble> Ptr;
xiongziliang committed
64

xiongziliang committed
65
    H264FrameNoCacheAble(char *ptr,uint32_t size,uint32_t dts , uint32_t pts ,int prefix_size = 4){
xiongziliang committed
66 67 68 69
        _ptr = ptr;
        _size = size;
        _dts = dts;
        _pts = pts;
xiongziliang committed
70
        _prefix_size = prefix_size;
71
    }
72

73 74 75
    CodecId getCodecId() const override{
        return CodecH264;
    }
76

77
    bool keyFrame() const override {
xiongziliang committed
78
        return H264_TYPE(_ptr[_prefix_size]) == H264Frame::NAL_IDR;
79
    }
xiongziliang committed
80 81

    bool configFrame() const override{
xiongziliang committed
82
        switch(H264_TYPE(_ptr[_prefix_size])){
xiongziliang committed
83
            case H264Frame::NAL_SPS:
xiongziliang committed
84 85
            case H264Frame::NAL_PPS:return true;
            default:return false;
xiongziliang committed
86 87
        }
    }
xiongziliang committed
88 89
};

90 91
typedef FrameInternal<H264FrameNoCacheAble> H264FrameInternal;

xiongziliang committed
92 93 94
/**
 * 264视频通道
 */
xiongziliang committed
95
class H264Track : public VideoTrack{
xiongziliang committed
96
public:
xiongziliang committed
97
    typedef std::shared_ptr<H264Track> Ptr;
98 99

    /**
xiongziliang committed
100 101 102 103 104
     * 不指定sps pps构造h264类型的媒体
     * 在随后的inputFrame中获取sps pps
     */
    H264Track(){}
    /**
105 106 107 108 109 110 111 112 113
     * 构造h264类型的媒体
     * @param sps sps帧数据
     * @param pps pps帧数据
     * @param sps_prefix_len 264头长度,可以为3个或4个字节,一般为0x00 00 00 01
     * @param pps_prefix_len 264头长度,可以为3个或4个字节,一般为0x00 00 00 01
     */
    H264Track(const string &sps,const string &pps,int sps_prefix_len = 4,int pps_prefix_len = 4){
        _sps = sps.substr(sps_prefix_len);
        _pps = pps.substr(pps_prefix_len);
xiongziliang committed
114
        onReady();
115 116 117 118 119 120 121 122 123 124 125 126 127
    }

    /**
     * 构造h264类型的媒体
     * @param sps sps帧
     * @param pps pps帧
     */
    H264Track(const Frame::Ptr &sps,const Frame::Ptr &pps){
        if(sps->getCodecId() != CodecH264 || pps->getCodecId() != CodecH264 ){
            throw std::invalid_argument("必须输入H264类型的帧");
        }
        _sps = string(sps->data() + sps->prefixSize(),sps->size() - sps->prefixSize());
        _pps = string(pps->data() + pps->prefixSize(),pps->size() - pps->prefixSize());
xiongziliang committed
128
        onReady();
xiongziliang committed
129
    }
130 131 132 133 134

    /**
     * 返回不带0x00 00 00 01头的sps
     * @return
     */
xiongziliang committed
135 136 137
    const string &getSps() const{
        return _sps;
    }
138 139 140 141 142

    /**
     * 返回不带0x00 00 00 01头的pps
     * @return
     */
xiongziliang committed
143 144 145
    const string &getPps() const{
        return _pps;
    }
146 147

    CodecId getCodecId() const override {
148
        return CodecH264;
xiongziliang committed
149
    }
150 151 152 153 154 155

    /**
     * 返回视频高度
     * @return
     */
    int getVideoHeight() const override{
156
        return _height ;
157 158 159 160 161 162 163
    }

    /**
     * 返回视频宽度
     * @return
     */
    int getVideoWidth() const override{
164
        return _width;
165 166 167 168 169 170 171 172 173
    }

    /**
     * 返回视频fps
     * @return
     */
    float getVideoFps() const override{
        return _fps;
    }
xiongziliang committed
174

175 176
    bool ready() override {
        return !_sps.empty() && !_pps.empty();
xiongziliang committed
177 178
    }

179 180 181 182 183 184
    /**
    * 输入数据帧,并获取sps pps
    * @param frame 数据帧
    */
    void inputFrame(const Frame::Ptr &frame) override{
        int type = H264_TYPE(*((uint8_t *)frame->data() + frame->prefixSize()));
185
        if(type == H264Frame::NAL_SPS || type == H264Frame::NAL_SEI){
186
            //有些设备会把SPS PPS IDR帧当做一个帧打包,所以我们要split一下
187 188 189 190
            splitH264(frame->data(), frame->size(), frame->prefixSize(), [&](const char *ptr, int len, int prefix) {
                H264FrameInternal::Ptr sub_frame = std::make_shared<H264FrameInternal>(frame, (char *)ptr, len, prefix);
                inputFrame_l(sub_frame);
            });
191 192 193 194 195 196 197 198 199 200 201 202 203 204
        } else{
            inputFrame_l(frame);
        }
    }
private:
    /**
     * 解析sps获取宽高fps
     */
    void onReady(){
        getAVCInfo(_sps,_width,_height,_fps);
    }
    Track::Ptr clone() override {
        return std::make_shared<std::remove_reference<decltype(*this)>::type >(*this);
    }
xiongziliang committed
205 206 207 208 209

    /**
     * 输入数据帧,并获取sps pps
     * @param frame 数据帧
     */
210
    void inputFrame_l(const Frame::Ptr &frame){
xiongziliang committed
211
        int type = H264_TYPE(*((uint8_t *)frame->data() + frame->prefixSize()));
xiongziliang committed
212
        switch (type){
xiongziliang committed
213
            case H264Frame::NAL_SPS:{
xiongziliang committed
214 215 216 217
                //sps
                _sps = string(frame->data() + frame->prefixSize(),frame->size() - frame->prefixSize());
            }
                break;
xiongziliang committed
218
            case H264Frame::NAL_PPS:{
xiongziliang committed
219 220 221 222 223
                //pps
                _pps = string(frame->data() + frame->prefixSize(),frame->size() - frame->prefixSize());
            }
                break;

xiongziliang committed
224
            case H264Frame::NAL_IDR:{
xiongziliang committed
225
                //I
xiongziliang committed
226
                insertConfigFrame(frame);
227
                VideoTrack::inputFrame(frame);
xiongziliang committed
228 229 230
            }
                break;

231
            default:
232
                VideoTrack::inputFrame(frame);
xiongziliang committed
233 234
                break;
        }
xiongziliang committed
235

236
        _last_frame_is_idr = type == H264Frame::NAL_IDR;
xiongziliang committed
237 238 239
        if(_width == 0 && ready()){
            onReady();
        }
xiongziliang committed
240
    }
xiongziliang committed
241

xiongziliang committed
242 243
    //生成sdp
    Sdp::Ptr getSdp() override ;
xiongziliang committed
244 245 246 247 248 249 250 251
private:
    //在idr帧前插入sps pps帧
    void insertConfigFrame(const Frame::Ptr &frame){
        if(_last_frame_is_idr){
            return;
        }

        if(!_sps.empty()){
xiongziliang committed
252
            auto spsFrame = std::make_shared<H264Frame>();
253 254 255 256
            spsFrame->_prefix_size = 4;
            spsFrame->_buffer.assign("\x0\x0\x0\x1",4);
            spsFrame->_buffer.append(_sps);
            spsFrame->_dts = frame->dts();
xiongziliang committed
257
            VideoTrack::inputFrame(spsFrame);
xiongziliang committed
258 259 260
        }

        if(!_pps.empty()){
xiongziliang committed
261
            auto ppsFrame = std::make_shared<H264Frame>();
262 263 264 265
            ppsFrame->_prefix_size = 4;
            ppsFrame->_buffer.assign("\x0\x0\x0\x1",4);
            ppsFrame->_buffer.append(_pps);
            ppsFrame->_dts = frame->dts();
xiongziliang committed
266
            VideoTrack::inputFrame(ppsFrame);
xiongziliang committed
267 268
        }
    }
269
private:
xiongziliang committed
270 271
    string _sps;
    string _pps;
272 273 274
    int _width = 0;
    int _height = 0;
    float _fps = 0;
xiongziliang committed
275
    bool _last_frame_is_idr = false;
xiongziliang committed
276 277
};

278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
/**
* h264类型sdp
*/
class H264Sdp : public Sdp {
public:
    /**
     *
     * @param sps 264 sps,不带0x00000001头
     * @param pps 264 pps,不带0x00000001头
     * @param playload_type  rtp playload type 默认96
     * @param bitrate 比特率
     */
    H264Sdp(const string &strSPS,
            const string &strPPS,
            int playload_type = 96,
            int bitrate = 4000) : Sdp(90000,playload_type) {
        //视频通道
        _printer << "m=video 0 RTP/AVP " << playload_type << "\r\n";
        _printer << "b=AS:" << bitrate << "\r\n";
        _printer << "a=rtpmap:" << playload_type << " H264/" << 90000 << "\r\n";
xiongziliang committed
298
        _printer << "a=fmtp:" << playload_type << " packetization-mode=1; profile-level-id=";
299 300 301 302 303 304 305 306 307 308 309

        char strTemp[100];
        uint32_t profile_level_id = 0;
        if (strSPS.length() >= 4) { // sanity check
            profile_level_id = (uint8_t(strSPS[1]) << 16) |
                               (uint8_t(strSPS[2]) << 8)  |
                               (uint8_t(strSPS[3])); // profile_idc|constraint_setN_flag|level_idc
        }
        memset(strTemp, 0, 100);
        sprintf(strTemp, "%06X", profile_level_id);
        _printer << strTemp;
xiongziliang committed
310
        _printer << "; sprop-parameter-sets=";
311 312 313 314 315 316
        memset(strTemp, 0, 100);
        av_base64_encode(strTemp, 100, (uint8_t *) strSPS.data(), strSPS.size());
        _printer << strTemp << ",";
        memset(strTemp, 0, 100);
        av_base64_encode(strTemp, 100, (uint8_t *) strPPS.data(), strPPS.size());
        _printer << strTemp << "\r\n";
xiongziliang committed
317
        _printer << "a=control:trackID=" << (int)TrackVideo << "\r\n";
318 319 320 321 322 323 324 325 326 327 328 329 330
    }

    string getSdp() const override {
        return _printer;
    }

    CodecId getCodecId() const override {
        return CodecH264;
    }
private:
    _StrPrinter _printer;
};

xiongziliang committed
331
}//namespace mediakit
xiongziliang committed
332
#endif //ZLMEDIAKIT_H264_H