#include "LiveStreamMediaSubSession.h"


CLiveStreamMediaSubSession *CLiveStreamMediaSubSession::createNew(UsageEnvironment& env,CImageIO *piImgIO) {
    return new CLiveStreamMediaSubSession(env, piImgIO);
}


CLiveStreamMediaSubSession::CLiveStreamMediaSubSession(UsageEnvironment& env,CImageIO *piImgIO)
    :OnDemandServerMediaSubsession(env, false)
{
    m_piImgIO = piImgIO;
    m_pReplicator = nullptr;
    m_pNullSink = nullptr;

    CFramedLiveSource *pH264Source = CFramedLiveSource::createNew(envir(),m_piImgIO);
    m_pReplicator = StreamReplicator::createNew(envir(),pH264Source,false);

    CreateNullStream();
}

CLiveStreamMediaSubSession::~CLiveStreamMediaSubSession()
{
    m_pNullSink->stopPlaying();
    Medium::close(m_pNullSink);
    Medium::close(m_pReplicator);
}

void CLiveStreamMediaSubSession::CreateNullStream()
{
    FramedSource* pFirstReplicator = m_pReplicator->createStreamReplica();

    m_pNullSink = CNULLSink::createNew(envir());
    m_pNullSink->startPlaying(*pFirstReplicator,NULL,NULL);
}

FramedSource *CLiveStreamMediaSubSession::createNewStreamSource(unsigned /*clientSessionId*/, unsigned& estBitrate) {
    estBitrate = 5120;

    FramedSource* pReplicator = m_pReplicator->createStreamReplica();

    H264VideoStreamFramer *pVideoSource =
            H264VideoStreamFramer::createNew(envir(),pReplicator );

    m_piImgIO->SetKeyFrameFlag();
    return pVideoSource;
}

RTPSink* CLiveStreamMediaSubSession::createNewRTPSink(Groupsock* rtpGroupsock,
                                                      unsigned char rtpPayloadTypeIfDynamic,
                                                      FramedSource* /*inputSource*/) {
    H264VideoRTPSink *pSink = H264VideoRTPSink::createNew(envir(),rtpGroupsock, 96);
    return pSink;
}

char const* CLiveStreamMediaSubSession::sdpLines()
{
    const char *strSDPLines =
            "m=video 0 RTP/AVP 96\r\n"
            "c=IN IP4 0.0.0.0\r\n"
            "b=AS:96\r\n"
            "a=rtpmap:96 H264/90000\r\n"
            "a=fmtp:96 packetization-mode=1;profile-level-id=000000;sprop-parameter-sets=H264\r\n"
            "a=control:track1\r\n";

    fSDPLines = strDup(strSDPLines);
    return fSDPLines;
}
