|
|
#include "videoLive555AVLibSource.h"
StreamClientState::StreamClientState() : iter(NULL), session(NULL), subsession(NULL), streamTimerTask(NULL), duration(0.0) {};
StreamClientState::~StreamClientState() { delete iter; if( session != NULL ){ // We also need to delete "session", and unschedule "streamTimerTask" (if set)
UsageEnvironment& env = session->envir(); // alias
env.taskScheduler().unscheduleDelayedTask(streamTimerTask); Medium::close(session); };};
CustomRTSPClient* CustomRTSPClient::createNew( videoLIVE555Source *session, UsageEnvironment& env, char const* rtspURL, int verbosityLevel, char const* applicationName, portNumBits tunnelOverHTTPPortNum) { return new CustomRTSPClient(session, env, rtspURL, verbosityLevel, applicationName, tunnelOverHTTPPortNum);};
CustomRTSPClient::CustomRTSPClient( videoLIVE555Source *session, UsageEnvironment& env, char const* rtspURL, int verbosityLevel, char const* applicationName, portNumBits tunnelOverHTTPPortNum) : RTSPClient(env,rtspURL, verbosityLevel, applicationName, tunnelOverHTTPPortNum, -1) , session(session){};
CustomRTSPClient::~CustomRTSPClient() {};
#define LOG( X ) m_pLog->Log( "LIVE555_SIN", this, X )
#define MLOG( X ) ME->m_pLog->Log( "LIVE555_SIN", ME, X )
#ifdef DEBUG
#define LOG_ERROR( X ) {\
char _tBfrErrMSG2w34[256];\ sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ m_pLog->Log( "LIVE555_SIN", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ }#else
#define LOG_ERROR( X ) m_pLog->Log( "LIVE555_SIN", this, _LOG_ERROR, X );
#endif
DummySink* DummySink::createNew( videoLIVE555Source* session, UsageEnvironment& env, MediaSubsession& subsession, char const* streamId, int w, int h, int ww, int hh ) { return new DummySink( session, env, subsession, streamId, w, h, ww, hh );}
DummySink::DummySink(videoLIVE555Source* session, UsageEnvironment& env, MediaSubsession& subsession, char const* streamId, int w, int h, int ww, int hh ) : MediaSink(env), session(session), frameIndex(0), fSubsession(subsession) { m_pLog = basicLogCollection::getInstance(); fStreamId = strDup(streamId);
m_nInWidth = w; m_nInHeight = h; m_nOutWidth = ww; m_nOutHeight = hh;
fReceiveBuffer = new u_int8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE]; fReceiveBufferAV = new u_int8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE + 4];
fReceiveBufferAV[0] = 0; fReceiveBufferAV[1] = 0; fReceiveBufferAV[2] = 0; fReceiveBufferAV[3] = 1;
av_init_packet(&avpkt); avpkt.flags |= AV_PKT_FLAG_KEY; avpkt.pts = avpkt.dts = 0;
memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
LOG( subsession.codecName() ); m_eCodecProbe = AV_CODEC_ID_NONE; if( strcmp(fSubsession.codecName(),"H264") == 0 ){ m_eCodecProbe = AV_CODEC_ID_H264; }; if( strcmp(fSubsession.codecName(),"JPEG") == 0 ){ m_eCodecProbe = AV_CODEC_ID_MJPEG; }; if( strcmp(fSubsession.codecName(),"H265") == 0 ){ m_eCodecProbe = AV_CODEC_ID_HEVC; };
codec = avcodec_find_decoder( m_eCodecProbe ); if (!codec) { LOG_ERROR( "codec not found!" ); };
codecContext = avcodec_alloc_context3(codec); frame = av_frame_alloc(); rgbFrame = av_frame_alloc(); //avpicture_alloc( ( AVPicture *) rgbFrame, AV_PIX_FMT_RGB24, 1920, 1080);
avpicture_alloc( ( AVPicture *) rgbFrame, AV_PIX_FMT_BGR24, 1280, 720 );
if (codec->capabilities & AV_CODEC_CAP_TRUNCATED) { codecContext->flags |= AV_CODEC_FLAG_TRUNCATED; // we do not send complete frames
}
if ( ( fSubsession.videoWidth() > 0 ) && ( fSubsession.videoHeight() > 0 ) ) { m_nInWidth = fSubsession.videoWidth(); m_nInHeight = fSubsession.videoHeight(); };
codecContext->width = m_nInWidth; codecContext->height = m_nInHeight; codecContext->pix_fmt = AV_PIX_FMT_YUV420P;
if (avcodec_open2(codecContext,codec,NULL) < 0) { LOG_ERROR( "could not open codec" ); }
//this->swsContext = sws_getContext( codecContext->width, codecContext->height, codecContext->pix_fmt, 1920, 1080, AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);
this->swsContext = sws_getContext( codecContext->width, codecContext->height, codecContext->pix_fmt, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, SWS_BICUBIC, NULL, NULL, NULL); m_pRGB = new cv::Mat( m_nOutHeight, m_nOutWidth, CV_8UC3, cv::Scalar( 255, 0, 255 ) ); char tB[128]; sprintf( tB, "Created Sink [%dx%d]->[1280x720]", codecContext->width,codecContext->height ); LOG( tB );};
DummySink::~DummySink() { delete[] fReceiveBuffer; delete [] fReceiveBufferAV; delete[] fStreamId;}
void DummySink::afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds ) { DummySink* sink = (DummySink*)clientData; sink->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds);};
void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned /*durationInMicroseconds*/) { // We've just received a frame of data. (Optionally) print out information about it:
//if (strcmp(fSubsession.codecName(),"H264") == 0) {
if( m_eCodecProbe != AV_CODEC_ID_NONE ) { avpkt.data = fReceiveBufferAV; avpkt.size = frameSize + 4; memcpy (fReceiveBufferAV + 4, fReceiveBuffer, frameSize); avpkt.data = fReceiveBufferAV; len = avcodec_decode_video2 (codecContext, frame, &got_picture, &avpkt); if (len < 0) { //LOG_ERROR( "Error while decoding frame " );// << frameIndex << "\n";
} else if (got_picture) { //envir() << "->Picture decoded :" << frameIndex << "\n";
//LOG( "Picture decoded" );
sws_scale( this->swsContext, this->frame->data,this->frame->linesize, 0, this->codecContext->height, this->rgbFrame->data, this->rgbFrame->linesize ); memcpy( m_pRGB->data, this->rgbFrame->data[0], this->rgbFrame->linesize[0] * m_nOutHeight ); this->session->consumeFrame( m_pRGB ); frameIndex ++; }; } else{ LOG("Codec Not Handled!"); LOG( fSubsession.codecName() ); }; // Then continue, to request the next frame of data:
continuePlaying();}
Boolean DummySink::continuePlaying() { if (fSource == NULL) return False; // sanity check (should not happen)
// Request the next frame of data from our input source. "afterGettingFrame()" will get called later, when it arrives:
fSource->getNextFrame(fReceiveBuffer, DUMMY_SINK_RECEIVE_BUFFER_SIZE, afterGettingFrame, this, onSourceClosure, this); return True;}
void DummySink::setSprop(u_int8_t const* prop, unsigned size) { uint8_t *buf; uint8_t *buf_start; buf = (uint8_t *)malloc(1000); buf_start = buf + 4;
avpkt.data = buf; avpkt.data[0] = 0; avpkt.data[1] = 0; avpkt.data[2] = 0; avpkt.data[3] = 1; memcpy (buf_start, prop, size); avpkt.size = size + 4; len = avcodec_decode_video2 (codecContext, frame, &got_picture, &avpkt); if (len < 0) { //envir() << "Error while decoding frame" << frame;
LOG_ERROR( "Error while decoding frame" ); // exit(6);
};
LOG( "after setSprop" ); // exit (111);
};
#undef LOG_ERROR
#undef MLOG
#undef LOG
#define LOG( X ) m_pLog->Log( "LIVE555_SRC", this, X )
#define MLOG( X ) ME->m_pLog->Log( "LIVE555_SRC", ME, X )
#ifdef DEBUG
#define LOG_ERROR( X ) {\
char _tBfrErrMSG2w34[256];\ sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ m_pLog->Log( "LIVE555_SRC", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ }#else
#define LOG_ERROR( X ) m_pLog->Log( "LIVE555_SRC", this, _LOG_ERROR, X );
#endif
videoLIVE555Source::videoLIVE555Source( void *opaque ): m_pScheduler(BasicTaskScheduler::createNew()), m_pUsageEnvironment(BasicUsageEnvironment::createNew(*m_pScheduler)), basicMediaSource(), //MediaSink(*m_pUsageEnvironment),
basicThread(), m_pLog(basicLogCollection::getInstance()), m_pOpaque(opaque){ m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1; if( !initLibAV() ) return; };
videoLIVE555Source::videoLIVE555Source( CSTR URI, void *opaque ): m_pScheduler(BasicTaskScheduler::createNew()), m_pUsageEnvironment(BasicUsageEnvironment::createNew(*m_pScheduler)), basicMediaSource(), //MediaSink(*m_pUsageEnvironment),
basicThread(), m_pLog(basicLogCollection::getInstance()), m_pOpaque(opaque){ m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1; if( !initLibAV() ) return; _open( URI );};
videoLIVE555Source::~videoLIVE555Source(){ _stop(); //if ( m_pSink ) delete( m_pSink );
};
void videoLIVE555Source::m_fThreadProc( void ){ _eventLoopWatchVariable = 0; m_pScheduler->doEventLoop( &_eventLoopWatchVariable ); LOG( "Rtsp event finished" ); m_pUsageEnvironment->reclaim(); m_pUsageEnvironment = NULL; delete m_pScheduler; m_pScheduler = NULL;};
Boolean videoLIVE555Source::continuePlaying(){ return False;};
void videoLIVE555Source::continueAfterDESCRIBE( RTSPClient* rtspClient, int resultCode, char* resultString){ CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); MLOG("After Describe EVT"); do { UsageEnvironment& env = rtspClient->envir(); // alias
StreamClientState& scs = MM->getStreamClientState(); // alias
if (resultCode != 0) { MLOG( "Failed to get a SDP description: "); MLOG( resultString ); delete[] resultString; break; };
char* const sdpDescription = resultString; MLOG( "Got a SDP description:" ); MLOG( sdpDescription );
// Create a media session object from this SDP description:
scs.session = MediaSession::createNew(env, sdpDescription); delete[] sdpDescription; // because we don't need it anymore
if (scs.session == NULL) { MLOG( "Failed to create a MediaSession object from the SDP description:" ); MLOG( env.getResultMsg() ); break; } else if (!scs.session->hasSubsessions()) { MLOG( "This session has no media subsessions (i.e., no \"m=\" lines)" ); break; };
// Then, create and set up our data source objects for the session. We do this by iterating over the session's 'subsessions',
// calling "MediaSubsession::initiate()", and then sending a RTSP "SETUP" command, on each one.
// (Each 'subsession' will have its own data source.)
scs.iter = new MediaSubsessionIterator(*scs.session); ME->setupNextSubsession(rtspClient); return; } while (0); // An unrecoverable error occurred with this stream.
ME->shutdownStream( rtspClient );};
void videoLIVE555Source::continueAfterSETUP( RTSPClient* rtspClient, int resultCode, char* resultString){ CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); MLOG("After Setup EVT"); do { UsageEnvironment& env = rtspClient->envir(); // alias
StreamClientState& streamClientState = MM->getStreamClientState(); // alias
if( resultCode != 0 ){ MLOG( "Failed to set up the subsession:"); MLOG( streamClientState.subsession->mediumName() ); MLOG( streamClientState.subsession->codecName() ); MLOG( resultString ); break; };
MLOG( "Set up the subsession" ); MLOG( streamClientState.subsession->mediumName() ); MLOG( streamClientState.subsession->codecName() ); if (streamClientState.subsession->rtcpIsMuxed()) { char tB[128]; sprintf( tB, "client port %d", streamClientState.subsession->clientPortNum() ); MLOG( tB ); } else { char tB[128]; sprintf( tB, "client ports %d-%d", streamClientState.subsession->clientPortNum(), streamClientState.subsession->clientPortNum()+1 ); MLOG( tB ); };
const char *sprop = streamClientState.subsession->fmtp_spropparametersets(); uint8_t const* sps = NULL; unsigned spsSize = 0; uint8_t const* pps = NULL; unsigned ppsSize = 0;
if (sprop != NULL) { unsigned numSPropRecords; SPropRecord* sPropRecords = parseSPropParameterSets(sprop, numSPropRecords); for (unsigned i = 0; i < numSPropRecords; ++i) { if (sPropRecords[i].sPropLength == 0) continue; // bad data
u_int8_t nal_unit_type = (sPropRecords[i].sPropBytes[0])&0x1F; if (nal_unit_type == 7/*SPS*/) { sps = sPropRecords[i].sPropBytes; spsSize = sPropRecords[i].sPropLength; } else if (nal_unit_type == 8/*PPS*/) { pps = sPropRecords[i].sPropBytes; ppsSize = sPropRecords[i].sPropLength; } } }
// Having successfully setup the subsession, create a data sink for it, and call "startPlaying()" on it.
// (This will prepare the data sink to receive data; the actual flow of data from the client won't start happening until later,
// after we've sent a RTSP "PLAY" command.)
streamClientState.subsession->sink = DummySink::createNew(ME, env, *streamClientState.subsession, rtspClient->url(), ME->m_nInWidth, ME->m_nInHeight, ME->m_nOutWidth, ME->m_nOutHeight ); // perhaps use your own custom "MediaSink" subclass instead
if (streamClientState.subsession->sink == NULL) { MLOG( "Failed to create a data sink for the subsession" ); MLOG( streamClientState.subsession->mediumName() ); MLOG( streamClientState.subsession->codecName() ); MLOG( env.getResultMsg() ); break; };
MLOG( "Created a data sink for the subsession" ); MLOG( streamClientState.subsession->mediumName() ); MLOG( streamClientState.subsession->codecName() );
streamClientState.subsession->miscPtr = rtspClient; // a hack to let subsession handler functions get the "RTSPClient" from the subsession
if (sps != NULL) { ((DummySink *)streamClientState.subsession->sink)->setSprop(sps, spsSize); } if (pps != NULL) { ((DummySink *)streamClientState.subsession->sink)->setSprop(pps, ppsSize); }
streamClientState.subsession->sink->startPlaying(*(streamClientState.subsession->readSource()), subsessionAfterPlaying, streamClientState.subsession);
// Also set a handler to be called if a RTCP "BYE" arrives for this subsession:
if (streamClientState.subsession->rtcpInstance() != NULL) { streamClientState.subsession->rtcpInstance()->setByeHandler( subsessionByeHandler, streamClientState.subsession ); }
} while (0); delete[] resultString; // Set up the next subsession, if any:
ME->setupNextSubsession(rtspClient);};void videoLIVE555Source::continueAfterPLAY( RTSPClient* rtspClient, int resultCode, char* resultString){ Boolean success = False; CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); MLOG("After Play EVT"); do { UsageEnvironment& env = rtspClient->envir(); // alias
StreamClientState& scs = ((CustomRTSPClient*)rtspClient)->getStreamClientState(); // alias
if (resultCode != 0) { MLOG( "Failed to start playing session: " ); MLOG( resultString ); break; };
// Set a timer to be handled at the end of the stream's expected duration (if the stream does not already signal its end
// using a RTCP "BYE"). This is optional. If, instead, you want to keep the stream active - e.g., so you can later
// 'seek' back within it and do another RTSP "PLAY" - then you can omit this code.
// (Alternatively, if you don't want to receive the entire stream, you could set this timer for some shorter value.)
if (scs.duration > 0) { unsigned const delaySlop = 2; // number of seconds extra to delay, after the stream's expected duration. (This is optional.)
scs.duration += delaySlop; unsigned uSecsToDelay = (unsigned)(scs.duration*1000000); scs.streamTimerTask = env.taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)streamTimerHandler, rtspClient); }
MLOG( "Started playing session" ); //if (scs.duration > 0) {
// env << " (for up to " << scs.duration << " seconds)";
// }
success = True; } while (0); delete[] resultString;
if (!success) { // An unrecoverable error occurred with this stream.
ME->shutdownStream(rtspClient); };};// Other event handler functions:
// called when a stream's subsession (e.g., audio or video substream) ends
void videoLIVE555Source::subsessionAfterPlaying( void* clientData ){ MediaSubsession* subsession = (MediaSubsession*)clientData; RTSPClient* rtspClient = (RTSPClient*)(subsession->miscPtr); CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); // Begin by closing this subsession's stream:
Medium::close(subsession->sink); subsession->sink = NULL;
// Next, check whether *all* subsessions' streams have now been closed:
MediaSession& session = subsession->parentSession(); MediaSubsessionIterator iter(session); while ((subsession = iter.next()) != NULL) { if (subsession->sink != NULL) return; // this subsession is still active
}
// All subsessions' streams have now been closed, so shutdown the client:
ME->shutdownStream(rtspClient);};
// called when a RTCP "BYE" is received for a subsession
void videoLIVE555Source::subsessionByeHandler( void* clientData ){//, char const* reason ){
MediaSubsession* subsession = (MediaSubsession*)clientData; RTSPClient* rtspClient = (RTSPClient*)subsession->miscPtr; CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); UsageEnvironment& env = rtspClient->envir(); // alias
MLOG( "Received RTCP \"BYE\" on subsession" ); MLOG( subsession->mediumName() ); MLOG( subsession->codecName() ); // Now act as if the subsession had closed:
subsessionAfterPlaying(subsession);};
void videoLIVE555Source::streamTimerHandler( void* clientData ){ CustomRTSPClient* rtspClient = (CustomRTSPClient*)clientData; StreamClientState& scs = rtspClient->getStreamClientState(); // alias
videoLIVE555Source * ME = (videoLIVE555Source *) rtspClient->getSession(); scs.streamTimerTask = NULL;
// Shut down the stream:
ME->shutdownStream(rtspClient);};
// The main streaming routine (for each "rtsp://" URL):
void videoLIVE555Source::openURL(UsageEnvironment& env, char const* progName, char const* rtspURL){ LOG("openURL Called!");};// Used to iterate through each stream's 'subsessions', setting up each one:
void videoLIVE555Source::setupNextSubsession(RTSPClient* rtspClient){ CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); MLOG("Next Subsession EVT"); UsageEnvironment& env = rtspClient->envir(); // alias
StreamClientState& scs = MM->getStreamClientState(); // alias
scs.subsession = scs.iter->next(); if (scs.subsession != NULL) { if (!scs.subsession->initiate()) { MLOG( "Failed to initiate the subsession:" ); MLOG( scs.subsession->mediumName() ); MLOG( scs.subsession->codecName() ); MLOG( env.getResultMsg() ); setupNextSubsession(rtspClient); // give up on this subsession; go to the next one
} else { MLOG( "Initiated the subsession"); MLOG( scs.subsession->mediumName() ); MLOG( scs.subsession->codecName() ); if ( strstr( scs.subsession->mediumName(),"video") != NULL ) { if (scs.subsession->rtcpIsMuxed()) { char tB[64]; sprintf( tB, "client port %d", scs.subsession->clientPortNum() ); MLOG( tB ); } else { char tB[64]; sprintf( tB, "client ports %d-%d", scs.subsession->clientPortNum(), scs.subsession->clientPortNum()+1 ); MLOG( tB ); }; // Continue setting up this subsession, by sending a RTSP "SETUP" command:
rtspClient->sendSetupCommand(*scs.subsession, continueAfterSETUP, False, REQUEST_STREAMING_OVER_TCP); } else { //Skip all Not Video subsession go to the next one
setupNextSubsession(rtspClient); }; }; return; };
// We've finished setting up all of the subsessions. Now, send a RTSP "PLAY" command to start the streaming:
if (scs.session->absStartTime() != NULL) { // Special case: The stream is indexed by 'absolute' time, so send an appropriate "PLAY" command:
rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY, scs.session->absStartTime(), scs.session->absEndTime()); } else { scs.duration = scs.session->playEndTime() - scs.session->playStartTime(); rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY); };};
// Used to shut down and close a stream (including its "RTSPClient" object):
void videoLIVE555Source::shutdownStream(RTSPClient* rtspClient, int exitCode ){ CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); MLOG("Shutdown EVT");};
// https://chowdera.com/2021/01/20210102084512591N.html
// https://github.com/drriguz/Kamera
bool videoLIVE555Source::_open( CSTR URI, bool ShowDeviceMenu, float framerate, int inputPin, int width, int height, int s_width, int s_height ){
m_nInHeight = height; m_nInWidth = width; m_nOutHeight = s_height; m_nOutWidth = s_width;
m_pRtspClient = CustomRTSPClient::createNew( this, *m_pUsageEnvironment, URI, RTSP_CLIENT_VERBOSITY_LEVEL, "ARGUS CLIENT" ); if( m_pRtspClient == NULL) { char tB[256]; sprintf( tB, "Failed to create a RTSP client for URL \"%s\":%s", URI, m_pUsageEnvironment->getResultMsg() ); LOG_ERROR( tB ); return false; }; m_pRtspClient->sendDescribeCommand(continueAfterDESCRIBE); return init();};
void videoLIVE555Source::consumeFrame( cv::Mat *frm ){ if ( m_pMediaDestination == NULL ) return; if(!m_pMediaDestination->pushFrame( *frm, m_pOpaque )){ m_pMediaDestination = NULL; };};
bool videoLIVE555Source::_close( void ){ return _stop();};bool videoLIVE555Source::_stop( void ){ shutdownStream( m_pRtspClient ); _eventLoopWatchVariable = 1; basicThread::waitThreadEnd( true ); return true;};bool videoLIVE555Source::isFinished( void ){ return false;};MediaStateStatus videoLIVE555Source::getStatus( void ){ return MS_UNDEFINED; };bool videoLIVE555Source::setSize( int Width, int Height ){ return false; };bool videoLIVE555Source::setProportionalByWidth( int Width ){ return false; };bool videoLIVE555Source::setProportionalByHeight( int Height ){ return false; };bool videoLIVE555Source::setFPS( int ){ return false; };bool videoLIVE555Source::setName( CSTR Name ){ return false; };bool videoLIVE555Source::setFrameAspectRatio( FrameAspectRatio AspectRatio ){ return false; };
#undef MLOG
#undef LOG
#undef LOG_ERROR
|