#include "rtmp.h"

class RTMPWriter : public SrsFileWriter
{
private:
    RTMP *rtmp;
    std::string path;
    int fd;
public:
    RTMPWriter()
    {
        rtmp = RTMP_Alloc();
        RTMP_Init(rtmp);
    }
    ~RTMPWriter()
    {
        close();
        RTMP_Free(rtmp);
    }
public:
    /**
     * open file writer, in truncate mode.
     * @param p a string indicates the path of file to open.
     */
    virtual int open(std::string p)
    {
        path = p;
        if(!RTMP_SetupURL(rtmp, (char*)path.c_str()))
        {
            // do something...
            fprintf(stderr, "error rtmp setup URL %s\n", path.c_str());
            return -1;
        }
        RTMP_EnableWrite(rtmp);
        RTMP_Connect(rtmp, NULL);
        if (!RTMP_Connect(rtmp, NULL) || !RTMP_ConnectStream(rtmp, 0)) {
            fprintf(stderr, "error rtmp connect %s\n", path.c_str());
            return -1;
        }
        return 0;
    }
    /**
     * open file writer, in append mode.
     * @param p a string indicates the path of file to open.
     */
    virtual int open_append(std::string p)
    {
        return open(p);
    }
    /**
     * close current writer.
     * @remark user can reopen again.
     */
    virtual void close()
    {
       RTMP_Close(rtmp);
    }
public:
    virtual bool is_open()
    {
        return 1;
    }
    virtual void lseek(int64_t offset)
    {
    }
    virtual int64_t tellg()
    {
        return -1;
    }
public:
    /**
    * write to file. 
    * @param pnwrite the output nb_write, NULL to ignore.
    */
    virtual int write(void* buf, size_t count, ssize_t* pnwrite)
    {
        int wb = RTMP_Write(rtmp, (const char*)buf, count);
        if(pnwrite != NULL)
            *pnwrite = wb;
        return 0;
    }
    /**
     * for the HTTP FLV, to writev to improve performance.
     */
    virtual int writev(iovec* iov, int iovcnt, ssize_t* pnwrite)
    {
        ssize_t nwrite = 0;
        int total_len = 0, offset = 0;
        unsigned char *buf;
        for (int i = 0; i < iovcnt; i++) {
            iovec* piov = iov + i;
            total_len += piov->iov_len;
        }
        buf = (unsigned char*)malloc(total_len);
        for (int i = 0; i < iovcnt; i++) {
            iovec* piov = iov + i;
            memcpy(buf + offset, piov->iov_base, piov->iov_len);
            offset += piov->iov_len;
        }
        
        int wb = write(buf, total_len, pnwrite);
        free(buf);
        return wb;
    }
};
arrow
arrow
    文章標籤
    rtmp publish
    全站熱搜

    Person 發表在 痞客邦 留言(0) 人氣()