FlvMuxer.cpp 6.31 KB
Newer Older
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

#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 64 65 66

        int i = 0;
        int size = pkt->size();
        pkt->for_each([&](const RtmpPacket::Ptr &rtmp){
            strongSelf->onWriteRtmp(rtmp, ++i == size);
        });
xiongziliang committed
67 68 69 70 71 72 73 74 75
    });
}

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
76
        if(pkt->type_id == MSG_VIDEO){
xiongziliang committed
77 78
            is_have_video = true;
        }
xiongziliang committed
79
        if(pkt->type_id == MSG_AUDIO){
xiongziliang committed
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
            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
xiongziliang committed
95
    onWrite(std::make_shared<BufferRaw>(flv_file_header, sizeof(flv_file_header) - 1), false);
96 97 98

    auto size = htonl(0);
    //PreviousTagSize0 Always 0
xiongziliang committed
99
    onWrite(std::make_shared<BufferRaw>((char *)&size,4), false);
100

101 102 103 104 105 106 107

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

xiongziliang committed
111 112
    //config frame
    mediaSrc->getConfigFrame([&](const RtmpPacket::Ptr &pkt){
xiongziliang committed
113
        onWriteRtmp(pkt, true);
xiongziliang committed
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    });
}



#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
136 137
void FlvMuxer::onWriteFlvTag(const RtmpPacket::Ptr &pkt, uint32_t time_stamp , bool flush) {
    onWriteFlvTag(pkt->type_id, pkt, time_stamp, flush);
xiongziliang committed
138 139
}

xiongziliang committed
140
void FlvMuxer::onWriteFlvTag(uint8_t type, const Buffer::Ptr &buffer, uint32_t time_stamp, bool flush) {
xiongziliang committed
141
    RtmpTagHeader header;
xiongziliang committed
142
    header.type = type;
143
    set_be24(header.data_size, buffer->size());
xiongziliang committed
144 145
    header.timestamp_ex = (uint8_t) ((time_stamp >> 24) & 0xff);
    set_be24(header.timestamp, time_stamp & 0xFFFFFF);
146
    //tag header
xiongziliang committed
147
    onWrite(std::make_shared<BufferRaw>((char *)&header, sizeof(header)), false);
148
    //tag data
xiongziliang committed
149
    onWrite(buffer, false);
150 151
    auto size = htonl((buffer->size() + sizeof(header)));
    //PreviousTagSize
xiongziliang committed
152
    onWrite(std::make_shared<BufferRaw>((char *)&size,4), flush);
xiongziliang committed
153 154
}

xiongziliang committed
155
void FlvMuxer::onWriteRtmp(const RtmpPacket::Ptr &pkt,bool flush) {
156
    int64_t dts_out;
xiongziliang committed
157
    _stamp[pkt->type_id % 2].revise(pkt->time_stamp, 0, dts_out, dts_out);
xiongziliang committed
158
    onWriteFlvTag(pkt, dts_out,flush);
xiongziliang committed
159 160 161 162 163 164 165 166 167 168
}

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

///////////////////////////////////////////////////////FlvRecorder/////////////////////////////////////////////////////
169
void FlvRecorder::startRecord(const EventPoller::Ptr &poller,const string &vhost, const string &app, const string &stream,const string &file_path) {
170
    startRecord(poller,dynamic_pointer_cast<RtmpMediaSource>(MediaSource::find(RTMP_SCHEMA,vhost,app,stream)),file_path);
xiongziliang committed
171 172
}

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

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

xiongziliang committed
198
void FlvRecorder::onWrite(const Buffer::Ptr &data, bool flush) {
xiongziliang committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    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();
}

214 215 216 217 218 219
FlvRecorder::FlvRecorder() {
}

FlvRecorder::~FlvRecorder() {
}

xiongziliang committed
220

xiongziliang committed
221
}//namespace mediakit