FlvMuxer.cpp 6.46 KB
Newer Older
1
/*
xiongziliang committed
2
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
3
 *
4
 * This file is part of ZLMediaKit(https://github.com/xia-chu/ZLMediaKit).
5
 *
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

#include "FlvMuxer.h"
12 13
#include "Util/File.h"
#include "Rtmp/utils.h"
xiongziliang committed
14 15 16

#define FILE_BUF_SIZE (64 * 1024)

xiongziliang committed
17
namespace mediakit {
xiongziliang committed
18 19 20 21 22 23 24


FlvMuxer::FlvMuxer() {
}
FlvMuxer::~FlvMuxer() {
}

25
void FlvMuxer::start(const EventPoller::Ptr &poller,const RtmpMediaSource::Ptr &media) {
xiongziliang committed
26 27 28
    if(!media){
        throw std::runtime_error("RtmpMediaSource 无效");
    }
xiongziliang committed
29 30
    if(!poller->isCurrentThread()){
        weak_ptr<FlvMuxer> weakSelf = getSharedPtr();
31 32
        //延时两秒启动录制,目的是为了等待config帧收集完毕
        poller->doDelayTask(2000,[weakSelf,poller,media](){
xiongziliang committed
33 34 35 36
            auto strongSelf = weakSelf.lock();
            if(strongSelf){
                strongSelf->start(poller,media);
            }
37
            return 0;
xiongziliang committed
38 39 40
        });
        return;
    }
xiongziliang committed
41 42 43 44

    onWriteFlvHeader(media);

    std::weak_ptr<FlvMuxer> weakSelf = getSharedPtr();
45
    _ring_reader = media->getRing()->attach(poller);
xiongziliang committed
46 47 48 49 50 51 52
    _ring_reader->setDetachCB([weakSelf](){
        auto strongSelf = weakSelf.lock();
        if(!strongSelf){
            return;
        }
        strongSelf->onDetach();
    });
53 54

    //音频同步于视频
xiongziliang committed
55
    _stamp[0].syncTo(_stamp[1]);
xiongziliang committed
56
    _ring_reader->setReadCB([weakSelf](const RtmpMediaSource::RingDataType &pkt){
xiongziliang committed
57 58 59 60
        auto strongSelf = weakSelf.lock();
        if(!strongSelf){
            return;
        }
xiongziliang committed
61

62 63
        size_t i = 0;
        auto size = pkt->size();
xiongziliang committed
64 65 66
        pkt->for_each([&](const RtmpPacket::Ptr &rtmp){
            strongSelf->onWriteRtmp(rtmp, ++i == size);
        });
xiongziliang committed
67 68 69
    });
}

70 71 72 73 74 75
BufferRaw::Ptr FlvMuxer::obtainBuffer(const void *data, size_t len) {
    auto buffer = BufferRaw::create();
    buffer->assign((const char *) data, len);
    return buffer;
}

xiongziliang committed
76 77 78 79 80 81
void FlvMuxer::onWriteFlvHeader(const RtmpMediaSource::Ptr &mediaSrc) {
    //发送flv文件头
    char flv_file_header[] = "FLV\x1\x5\x0\x0\x0\x9"; // have audio and have video
    bool is_have_audio = false,is_have_video = false;

    mediaSrc->getConfigFrame([&](const RtmpPacket::Ptr &pkt){
xiongziliang committed
82
        if(pkt->type_id == MSG_VIDEO){
xiongziliang committed
83 84
            is_have_video = true;
        }
xiongziliang committed
85
        if(pkt->type_id == MSG_AUDIO){
xiongziliang committed
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
            is_have_audio = true;
        }
    });

    if (is_have_audio && is_have_video) {
        flv_file_header[4] = 0x05;
    } else if (is_have_audio && !is_have_video) {
        flv_file_header[4] = 0x04;
    } else if (!is_have_audio && is_have_video) {
        flv_file_header[4] = 0x01;
    } else {
        flv_file_header[4] = 0x00;
    }

    //flv header
101
    onWrite(obtainBuffer(flv_file_header, sizeof(flv_file_header) - 1), false);
102 103 104

    auto size = htonl(0);
    //PreviousTagSize0 Always 0
105
    onWrite(obtainBuffer((char *)&size,4), false);
106

107 108 109 110 111 112 113

    auto &metadata = mediaSrc->getMetaData();
    if(metadata){
        //在有metadata的情况下才发送metadata
        //其实metadata没什么用,有些推流器不产生metadata
        AMFEncoder invoke;
        invoke << "onMetaData" << metadata;
xiongziliang committed
114
        onWriteFlvTag(MSG_DATA, std::make_shared<BufferString>(invoke.data()), 0, false);
115
    }
116

xiongziliang committed
117 118
    //config frame
    mediaSrc->getConfigFrame([&](const RtmpPacket::Ptr &pkt){
xiongziliang committed
119
        onWriteRtmp(pkt, true);
xiongziliang committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
    });
}



#if defined(_WIN32)
#pragma pack(push, 1)
#endif // defined(_WIN32)

class RtmpTagHeader {
public:
    uint8_t type = 0;
    uint8_t data_size[3] = {0};
    uint8_t timestamp[3] = {0};
    uint8_t timestamp_ex = 0;
    uint8_t streamid[3] = {0}; /* Always 0. */
}PACKED;

#if defined(_WIN32)
#pragma pack(pop)
#endif // defined(_WIN32)

xiongziliang committed
142 143
void FlvMuxer::onWriteFlvTag(const RtmpPacket::Ptr &pkt, uint32_t time_stamp , bool flush) {
    onWriteFlvTag(pkt->type_id, pkt, time_stamp, flush);
xiongziliang committed
144 145
}

xiongziliang committed
146
void FlvMuxer::onWriteFlvTag(uint8_t type, const Buffer::Ptr &buffer, uint32_t time_stamp, bool flush) {
xiongziliang committed
147
    RtmpTagHeader header;
xiongziliang committed
148
    header.type = type;
149
    set_be24(header.data_size, (uint32_t)buffer->size());
xiongziliang committed
150 151
    header.timestamp_ex = (uint8_t) ((time_stamp >> 24) & 0xff);
    set_be24(header.timestamp, time_stamp & 0xFFFFFF);
152
    //tag header
153
    onWrite(obtainBuffer((char *)&header, sizeof(header)), false);
154
    //tag data
xiongziliang committed
155
    onWrite(buffer, false);
156
    uint32_t size = htonl((uint32_t)(buffer->size() + sizeof(header)));
157
    //PreviousTagSize
158
    onWrite(obtainBuffer((char *)&size,4), flush);
xiongziliang committed
159 160
}

xiongziliang committed
161
void FlvMuxer::onWriteRtmp(const RtmpPacket::Ptr &pkt,bool flush) {
162
    int64_t dts_out;
xiongziliang committed
163
    _stamp[pkt->type_id % 2].revise(pkt->time_stamp, 0, dts_out, dts_out);
164
    onWriteFlvTag(pkt, (uint32_t)dts_out,flush);
xiongziliang committed
165 166 167 168 169 170 171 172 173 174
}

void FlvMuxer::stop() {
    if(_ring_reader){
        _ring_reader.reset();
        onDetach();
    }
}

///////////////////////////////////////////////////////FlvRecorder/////////////////////////////////////////////////////
175
void FlvRecorder::startRecord(const EventPoller::Ptr &poller,const string &vhost, const string &app, const string &stream,const string &file_path) {
176
    startRecord(poller,dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,vhost,app,stream)),file_path);
xiongziliang committed
177 178
}

179
void FlvRecorder::startRecord(const EventPoller::Ptr &poller,const RtmpMediaSource::Ptr &media, const string &file_path) {
xiongziliang committed
180
    stop();
181
    lock_guard<recursive_mutex> lck(_file_mtx);
xiongziliang committed
182 183 184 185 186 187 188
    //开辟文件写缓存
    std::shared_ptr<char> fileBuf(new char[FILE_BUF_SIZE],[](char *ptr){
        if(ptr){
            delete [] ptr;
        }
    });
    //新建文件
xiongziliang committed
189
    _file.reset(File::create_file(file_path.data(), "wb"), [fileBuf](FILE *fp){
xiongziliang committed
190 191 192 193 194 195 196 197 198 199 200
        if(fp){
            fflush(fp);
            fclose(fp);
        }
    });
    if (!_file){
        throw std::runtime_error( StrPrinter << "打开文件失败:" << file_path);
    }

    //设置文件写缓存
    setvbuf( _file.get(), fileBuf.get(),_IOFBF, FILE_BUF_SIZE);
201
    start(poller,media);
xiongziliang committed
202 203
}

xiongziliang committed
204
void FlvRecorder::onWrite(const Buffer::Ptr &data, bool flush) {
xiongziliang committed
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    lock_guard<recursive_mutex> lck(_file_mtx);
    if(_file){
        fwrite(data->data(),data->size(),1,_file.get());
    }
}

void FlvRecorder::onDetach() {
    lock_guard<recursive_mutex> lck(_file_mtx);
    _file.reset();
}

std::shared_ptr<FlvMuxer> FlvRecorder::getSharedPtr() {
    return  shared_from_this();
}

220 221 222 223 224 225
FlvRecorder::FlvRecorder() {
}

FlvRecorder::~FlvRecorder() {
}

xiongziliang committed
226

xiongziliang committed
227
}//namespace mediakit