You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1291 lines
41 KiB

#include "videoLive555AVLibSource.h"
#ifndef LRF_PROXY_ONLY
#define FF_DISABLE_DEPRECATION_WARNINGS
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, const char * rtspURL, int verbosityLevel, const char * applicationName, portNumBits tunnelOverHTTPPortNum)
{
return new CustomRTSPClient(session, env, rtspURL, verbosityLevel, applicationName, tunnelOverHTTPPortNum);
}
CustomRTSPClient::CustomRTSPClient(videoLIVE555Source * session, UsageEnvironment & env, const char * rtspURL, int verbosityLevel, const char * 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[1024]; \
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, const char * streamId, int w, int h, int ww, int hh) :
MediaSink(env),
m_pSession(session),
//m_iFrameIndex(0),
m_sSubSession(subsession)
{
m_pLog = basicLogCollection::getInstance();
m_pStreamId = strDup(streamId);
m_iFrameIndex = 0;
m_nCurrentOutFile = 0;
m_pOutFile[0] = m_pOutFile[1] = NULL;
m_nInWidth = w;
m_nInHeight = h;
m_nOutWidth = ww;
m_nOutHeight = hh;
m_pReceiveBuffer = new uint8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE];
m_pReceiveBufferAV = new uint8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE + 4];
m_pReceiveBufferAV[0] = 0;
m_pReceiveBufferAV[1] = 0;
m_pReceiveBufferAV[2] = 0;
m_pReceiveBufferAV[3] = 1;
//av_init_packet(&m_sAvPkt);
m_sAvPkt.pts = AV_NOPTS_VALUE;
m_sAvPkt.dts = AV_NOPTS_VALUE;
m_sAvPkt.pos = -1;
m_sAvPkt.duration = 0;
//m_sAvPkt.convergence_duration = 0; //is deprecated
m_sAvPkt.flags = AV_PKT_FLAG_KEY;
m_sAvPkt.stream_index = 0;
m_sAvPkt.buf = NULL;
m_sAvPkt.side_data = NULL;
m_sAvPkt.side_data_elems = 0;
memset(m_aInBuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
LOG(m_sSubSession.codecName());
m_eCodecProbe = AV_CODEC_ID_NONE;
if (strcmp(m_sSubSession.codecName(), "JPEG") == 0)
{
m_eCodecProbe = AV_CODEC_ID_MJPEG;
}
else if (strcmp(m_sSubSession.codecName(), "H264") == 0)
{
m_eCodecProbe = AV_CODEC_ID_H264;
}
else if (strcmp(m_sSubSession.codecName(), "H265") == 0)
{
m_eCodecProbe = AV_CODEC_ID_HEVC;
};
m_pCodec = avcodec_find_decoder(m_eCodecProbe);
if (m_pCodec == NULL)
{
LOG_ERROR("codec not found!");
return;
};
m_pCodecContext = avcodec_alloc_context3(m_pCodec);
#if (LIBAVCODEC_VERSION_MAJOR >= 60)
#else
if (m_pCodec->capabilities & AV_CODEC_CAP_TRUNCATED)
{
m_pCodecContext->flags |= AV_CODEC_FLAG_TRUNCATED; // we do not send complete frames
};
#endif // (LIBAVCODEC_VERSION_MAJOR >= 60)
if ((m_sSubSession.videoWidth() > 0) && (m_sSubSession.videoHeight() > 0))
{
m_nInWidth = m_sSubSession.videoWidth();
m_nInHeight = m_sSubSession.videoHeight();
};
m_pCodecContext->width = m_nInWidth;
m_pCodecContext->height = m_nInHeight;
// Must be carefull! and get pix_fmt from stream
m_pCodecContext->pix_fmt = AV_PIX_FMT_YUV420P;
if (avcodec_open2(m_pCodecContext, m_pCodec, NULL) < 0)
{
LOG_ERROR("could not open codec!");
return;
};
if (m_pSession->getWM() & MS_MODE_STREAM_PROXY)
{
m_pH264 = (uint8_t *) malloc(256 * 1024);
m_pOutFormatCtx = NULL;
m_pOutFormatOpts = NULL;
if (avformat_alloc_output_context2(&m_pOutFormatCtx, NULL, NULL, "test.mp4") < 0)
{
LOG_ERROR("VideoFormat Context Memory Allocation Error");
// return false;
}
else
{
m_pOutFormatCtx->oformat = av_guess_format("mp4", NULL, NULL);
if (m_pOutFormatCtx->oformat != NULL)
{
av_dict_set(&m_pOutFormatOpts, "brand", "mp42", 0);
av_dict_set(&m_pOutFormatOpts, "movflags", "faststart", 0);
m_pOutFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
m_pOutStream = avformat_new_stream(m_pOutFormatCtx, NULL);
if (m_pOutStream != NULL)
{
// v60
const AVCodec *codec = avcodec_find_decoder( m_pOutStream->codecpar->codec_id );
AVCodecContext * c = avcodec_alloc_context3( codec );//m_pOutStream->codec;
c->codec_id = m_eCodecProbe;
c->codec_type = AVMEDIA_TYPE_VIDEO;
/* put sample parameters */
c->bit_rate = m_sSubSession.bandwidth(); // 400000;
/* resolution must be a multiple of two */
c->width = m_sSubSession.videoWidth();
c->height = m_sSubSession.videoHeight();
/* time base: this is the fundamental unit of time (in seconds) in terms
of which frame timestamps are represented. for fixed-fps content,
timebase should be 1/framerate and timestamp increments should be
identically 1. */
c->time_base.den = m_sSubSession.videoFPS();
c->time_base.num = 1;
c->gop_size = 12; /* emit one intra frame every twelve frames at most */
c->pix_fmt = AV_PIX_FMT_YUV420P;
if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO)
{
/* just for testing, we also add B frames */
c->max_b_frames = 2;
}
if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO)
{
/* needed to avoid using macroblocks in which some coeffs overflow
this doesnt happen with normal video, it just happens here as the
motion of the chroma plane doesnt match the luma plane */
c->mb_decision = 2;
}
// some formats want stream headers to be seperate
if (! strcmp(m_pOutFormatCtx->oformat->name, "mp4") || ! strcmp(m_pOutFormatCtx->oformat->name, "mov") || ! strcmp(m_pOutFormatCtx->oformat->name, "3gp"))
{
c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
LOG("Global Header Flag is Set!");
};
if (avio_open(&m_pOutFormatCtx->pb, "test_99.mp4", AVIO_FLAG_WRITE) < 0)
{
LOG_ERROR("Could not open output file.");
// return false;
};
if (avformat_write_header(m_pOutFormatCtx, &m_pOutFormatOpts) < 0)
{
LOG_ERROR("Error occurred when writing header to output file.");
// return false;
};
}
};
};
/*
m_pOutCodec = = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
if( m_pOutCodec == NULL ) {
LOG_ERROR( "output codec not found!" );
//m_pSession->setWM( m_pSession->getWM() & ( ~ MS_MODE_STREAM_PROXY ) );
return;
};
m_pOutCodecContext = avcodec_alloc_context3( m_pOutCodec );
if( m_pOutCodecContext == NULL ){
LOG_ERROR("VideoCodec Context Memory Allocation Error");
return;
} else {
LOG("Codec Context3 Allocated");
};
if( avformat_alloc_output_context2( &m_pOutFormatCtx, NULL, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
LOG_ERROR("VideoFormat Context Memory Allocation Error");
return;
};
m_pOutFormatCtx->oformat = av_guess_format( VIDEO_OUTPUT_CONTAINER, NULL, NULL );
if( m_pOutFormatCtx->oformat == NULL ){
LOG_ERROR("VideoFormat Format Not Guessed!");
return;
} else {
LOG("Video Container Format Guessed");
};
m_pOutVideoStr = avformat_new_stream( m_pOutFormatCtx, m_pOutCodec );
if( m_pOutVideoStr == NULL){
LOG_ERROR("VideoStream Not Created!");
} else {
LOG("VideoStream is Created");
};
m_pOutCodecContext->codec_id = VIDEO_OUTPUT_CODEC;
m_pOutCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;
m_pOutCodecContext->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
m_pOutCodecContext->bit_rate = VIDEO_OUTPUT_BITRATE;
//m_pOutCodecContext->bit_rate_tolerance = 1;
//m_pOutCodecContext->global_quality = 100;
//m_pOutCodecContext->compression_level = 2;
m_pOutCodecContext->width = m_nWidth;
m_pOutCodecContext->height = m_nHeight;
m_pOutCodecContext->time_base.num = 1;
m_pOutCodecContext->time_base.den = VIDEO_OUTPUT_FPS;
m_pOutCodecContext->gop_size = VIDEO_OUTPUT_GOP; // emit one intra frame every ten frames
//m_pVideoState->m_pCodecCtx->qmin = 15;
//m_pVideoState->m_pCodecCtx->qmax = 30;
m_pOutCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
if( m_pVideoState->m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ){
//Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
//Set format's privater options, to be passed to avformat_write_header()
LOG("Begin Options!");
int RetVal = 0;
//RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "movflags", "faststart", 0);
//if( RetVal < 0 ){
// LOG_ERROR( "av_dict_set movflags!");
//};
//default brand is "isom", which fails on some devices
RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "brand", "mp42", 0);
if( RetVal < 0 ){
LOG_ERROR( "av_dict_set brand!" );
};
//m_pVideoState->m_pCodecCtx->max_b_frames = 1;
m_pVideoState->m_pCodecCtx->level = 31;
RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "crf", "12", 0);
if( RetVal < 0 ){
LOG_ERROR("av_opt_set crf");
};
RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "profile", "main", 0);
if( RetVal < 0 ){
LOG_ERROR("av_opt_set profile");
};
RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "preset", "slow", 0);
if( RetVal < 0 ){
LOG_ERROR("av_opt_set preset");
};
// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
// Because Quicktime (ie. iOS) doesn't support this option
RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "b-pyramid", "0", 0);
if( RetVal < 0 ){
LOG_ERROR("av_opt_set b-pyramid");
};
LOG("End Options!");
};
//See up one page ->
avcodec_get_context_defaults3(m_pVideoState->m_pVideoStr->codec, m_pVideoState->m_pVideoCodec);
const AVRational dst_fps = { VIDEO_OUTPUT_FPS, 1 };
m_pVideoState->m_pVideoStr->codec->width = m_nWidth;
m_pVideoState->m_pVideoStr->codec->height = m_nHeight;
m_pVideoState->m_pVideoStr->codec->pix_fmt = m_pVideoState->m_pVideoCodec->pix_fmts[0];
m_pVideoState->m_pVideoStr->codec->time_base = m_pVideoState->m_pVideoStr->time_base = av_inv_q(dst_fps);
m_pVideoState->m_pVideoStr->r_frame_rate = m_pVideoState->m_pVideoStr->avg_frame_rate = dst_fps;
if (m_pVideoState->m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER) m_pVideoState->m_pVideoStr->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
//---->>
if (avcodec_is_open(m_pVideoState->m_pCodecCtx) == 0) {
LOG("output codec context is closed, opening");
int ret = avcodec_open2(m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoCodec, NULL);
if (ret < 0) {
LOG_ERROR("Error opening2 encoder");
char buffer[200];
sprintf(buffer, "Error code: %i", ret );
LOG_ERROR(buffer);
return false;
}
}else{
LOG("output codec context is opened");
};
*/
// https://github.com/rgaufman/live555/blob/master/testProgs/playCommon.cpp
// http://www.live555.com/liveMedia//doxygen/html/QuickTimeFileSink_8hh_source.html
// qtOut = QuickTimeFileSink::createNew(*env, *session, outFileName,
// fileSinkBufferSize,
// movieWidth, movieHeight,
// movieFPS,
// packetLossCompensate,
// syncStreams,
// generateHintTracks,
// generateMP4Format);
/* qtOut = QuickTimeFileSink::createNew( env, *session->getMS(), "TEST.mp4",
100000,
subsession.videoWidth(), subsession.videoHeight(),
subsession.videoFPS(),
0,
0,
0,
1);
*/
qtOut = (H264or5VideoFileSink *) H264VideoFileSink::createNew(env, "TEST22.mp4");
if (qtOut != NULL)
{
LOG("Created QTFS ---> Test.mp4");
// qtOut->startPlaying( NULL, NULL );
LOG("QTFS Started Play");
};
}
else if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES)
{
// Allocate Mems
m_pFrame = av_frame_alloc();
m_pRGBFrame = av_frame_alloc();
//avpicture_alloc((AVPicture *) m_pRGBFrame, AV_PIX_FMT_BGR24, m_nOutWidth, m_nOutHeight);
int ret = av_image_alloc( m_pRGBFrame->data, m_pRGBFrame->linesize, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, 32); // 32 for alignment
if (ret < 0) {
// Handle error
LOG_ERROR("Error Allocating RGBFrame!");
};
m_pSwsContext = sws_getContext(m_pCodecContext->width, m_pCodecContext->height, m_pCodecContext->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));
}
else
{
LOG("No Decode Frames Mode!");
m_pFrame = m_pRGBFrame = NULL;
m_pSwsContext = NULL;
m_pRGB = NULL;
};
#ifdef DEBUG
char tB[128];
sprintf(tB, "Created Sink [%dx%d]->[%dx%d]", m_pCodecContext->width, m_pCodecContext->height, m_nOutWidth, m_nOutHeight);
LOG(tB);
#endif
}
DummySink::~DummySink()
{
if (m_pSession->getWM() & MS_MODE_STREAM_PROXY)
{
if (m_pOutFormatCtx != NULL)
{
av_write_trailer(m_pOutFormatCtx);
avio_close(m_pOutFormatCtx->pb);
};
if (m_pOutFile[0] != NULL)
{
fflush(m_pOutFile[0]);
pclose(m_pOutFile[0]);
};
if (m_pOutFile[1] != NULL)
{
fflush(m_pOutFile[1]);
pclose(m_pOutFile[1]);
};
if (qtOut != NULL)
{
Medium::close(qtOut);
qtOut = NULL;
};
}
else if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES)
{
};
/*Medium::close(qtOut); qtOut = NULL;
Medium::close(aviOut); aviOut = NULL;
if (session == NULL) return;
MediaSubsessionIterator iter(*session);
MediaSubsession* subsession;
while ((subsession = iter.next()) != NULL) {
Medium::close(subsession->sink);
subsession->sink = NULL;
}*/
if (m_pFrame)
{
av_free(m_pFrame);
};
if (m_pRGBFrame)
{
};
if (m_pSwsContext)
{
};
if (m_pCodecContext)
{
};
if (m_pCodec)
{
};
delete[] m_pReceiveBuffer;
delete[] m_pReceiveBufferAV;
delete[] m_pStreamId;
}
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) {
//LOG("FRM");
if ( presentationTime.tv_sec ) presentationTime.tv_sec = presentationTime.tv_sec;
if ( numTruncatedBytes ) numTruncatedBytes = numTruncatedBytes;
if ( m_eCodecProbe != AV_CODEC_ID_NONE)
{
int got_picture = 0;
memcpy(m_pReceiveBufferAV + 4, m_pReceiveBuffer, frameSize);
m_sAvPkt.pts = AV_NOPTS_VALUE;
m_sAvPkt.dts = AV_NOPTS_VALUE;
m_sAvPkt.pos = -1;
m_sAvPkt.duration = 0;
//m_sAvPkt.convergence_duration = 0; // is deprecated
m_sAvPkt.flags = AV_PKT_FLAG_KEY;
m_sAvPkt.stream_index = 0;
m_sAvPkt.buf = NULL;
m_sAvPkt.side_data = NULL;
m_sAvPkt.side_data_elems = 0;
m_sAvPkt.size = frameSize + 4;
m_sAvPkt.data = m_pReceiveBufferAV;
if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES){
int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt );
if( ret < 0 ){
LOG_ERROR("Error Send Packet to Decoder!");
};
while ( ret >= 0 ) {
ret = avcodec_receive_frame( m_pCodecContext, m_pFrame );
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
// EAGAIN: Need more input packets
// EOF: Decoder flushed
break;
} else if (ret < 0) {
// Handle decoding error
break;
};
// LOG( "Picture decoded" );
got_picture = 1;
sws_scale( m_pSwsContext, m_pFrame->data, m_pFrame->linesize, 0, m_pCodecContext->height, m_pRGBFrame->data, m_pRGBFrame->linesize);
memcpy( m_pRGB->data, m_pRGBFrame->data[0], m_pRGBFrame->linesize[0] * m_nOutHeight );
m_pSession->consumeFrame( m_pRGB );
m_iFrameIndex++;
};
if ( ret == AVERROR_EOF ) {
//End
};
};
av_packet_unref(&m_sAvPkt);
if (m_pSession->getWM() & MS_MODE_STREAM_PROXY)
{
if (m_pSession->getWM() & MS_MODE_OVERLAYED_LOOPS)
{
// Sega - Mega - Drive
};
// write packet
#if (0)
// We've just received a frame of data. (Optionally) print out information about it:
#ifdef DEBUG_PRINT_EACH_RECEIVED_FRAME
if (fStreamId != NULL)
{
envir() << "Stream \"" << fStreamId << "\"; ";
}
envir() << fSubsession.mediumName() << "/" << fSubsession.codecName() << ":\tReceived " << frameSize << " bytes";
if (numTruncatedBytes > 0)
{
envir() << " (with " << numTruncatedBytes << " bytes truncated)";
}
char uSecsStr[6 + 1]; // used to output the 'microseconds' part of the presentation time
sprintf(uSecsStr, "%06u", (unsigned) presentationTime.tv_usec);
envir() << ".\tPresentation time: " << (int) presentationTime.tv_sec << "." << uSecsStr;
if (fSubsession.rtpSource() != NULL && ! fSubsession.rtpSource()->hasBeenSynchronizedUsingRTCP())
{
envir() << "!"; // mark the debugging output to indicate that this presentation time is not RTCP-synchronized
}
#ifdef DEBUG_PRINT_NPT
envir() << "\tNPT: " << fSubsession.getNormalPlayTime(presentationTime);
#endif
envir() << "\n";
#endif
#else
//*
// printf("__FUNCTION__ = %s\n", __FUNCTION__ );
// if(0 == strncmp(fSubsession.codecName(), "H264", 16) ){
unsigned char nalu_header[4] = {0, 0, 0, 1};
unsigned char extraData[256];
unsigned int num = 0;
SPropRecord * pSPropRecord;
pSPropRecord = parseSPropParameterSets(m_sSubSession.fmtp_spropparametersets(), num);
unsigned int extraLen;
extraLen = 0;
// p_record[0] is sps
// p+record[1] is pps
for (unsigned int i = 0; i < num; i++)
{
memcpy(&extraData[extraLen], &nalu_header[0], 4);
extraLen += 4;
memcpy(&extraData[extraLen], pSPropRecord[i].sPropBytes, pSPropRecord[i].sPropLength);
extraLen += pSPropRecord[i].sPropLength;
};
memcpy(&extraData[extraLen], &nalu_header[0], 4);
extraLen += 4;
delete[] pSPropRecord;
memcpy(m_pH264, &extraData[0], extraLen);
memcpy(m_pH264 + extraLen, m_pReceiveBuffer, frameSize);
int totalSize;
totalSize = extraLen + frameSize;
if (m_pOutFile[m_nCurrentOutFile] == NULL)
{
// m_pOutFile[m_nCurrentOutFile] = fopen("saved.h264", "wb" );
LOG("Opening");
// m_pOutFile[m_nCurrentOutFile] = popen("ffmpeg -y -hide_banner -i - -vcodec copy -movflags faststart -an ./ttt123.mp4", "w" );
m_pOutFile[m_nCurrentOutFile] = popen("ffmpeg -y -hide_banner -i - -vcodec copy -reserve_index_space 50k -an ./ttt123.mkv", "w");
if (m_pOutFile[m_nCurrentOutFile] == NULL)
{
LOG("Error !!");
};
};
if (m_pOutFile[m_nCurrentOutFile] != NULL)
{
fwrite(m_pH264, 1, totalSize, m_pOutFile[m_nCurrentOutFile]);
fflush(m_pOutFile[m_nCurrentOutFile]);
// fclose( fp );
};
// qtOut->addData( m_pH264, totalSize, presentationTime );
// printf("\tsaved %d bytes\n", totalSize );
// }/*if 0 == strncmp(fSubsession.codecName(), "H264", 16)*/
// if( got_picture ) {
if (m_pOutFormatCtx != NULL)
{
m_sAvPkt.duration = durationInMicroseconds;
if (got_picture)
{
m_sAvPkt.flags |= AV_PKT_FLAG_KEY;
}
m_sAvPkt.stream_index = m_pOutStream->index;
m_sAvPkt.size = totalSize;
m_sAvPkt.data = m_pH264;
// m_sAvPkt.size = frameSize;
// m_sAvPkt.data = m_pReceiveBuffer;
// av_packet_rescale_ts( &avpkt, m_pOutCodec->time_base, time_base );
int r = av_write_frame(m_pOutFormatCtx, &m_sAvPkt);
if (r < 0)
{
char tB[256];
av_strerror(r, tB, 256);
LOG_ERROR("Trouble with Video Output!");
LOG_ERROR(tB);
};
}
//}
#endif
};
#ifdef DEBUG
}
else
{
LOG("Codec Not Handled!");
LOG(m_sSubSession.codecName());
#endif
};
// 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(m_pReceiveBuffer, DUMMY_SINK_RECEIVE_BUFFER_SIZE, afterGettingFrame, this, onSourceClosure, this);
return True;
}
void DummySink::setSprop(const u_int8_t * prop, unsigned size)
{
uint8_t * buf;
uint8_t * buf_start;
LOG("setSprop");
buf = (uint8_t *) malloc(1004);
buf_start = buf + 4;
m_sAvPkt.data = buf;
m_sAvPkt.data[0] = 0;
m_sAvPkt.data[1] = 0;
m_sAvPkt.data[2] = 0;
m_sAvPkt.data[3] = 1;
if (size > 1000)
{
LOG_ERROR("Data Chunk too large!! Increase Mem!");
free(buf);
m_sAvPkt.data = NULL;
m_sAvPkt.size = 0;
return;
};
memcpy(buf_start, prop, size);
m_sAvPkt.size = size + 4;
if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES){
int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt );
if( ret < 0 ){
LOG_ERROR("Error Send Packet to Decoder!");
};
while ( ret >= 0 ) {
ret = avcodec_receive_frame( m_pCodecContext, m_pFrame );
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
LOG_ERROR("EAGAIN/EOF while decoding frame");
break;
} else if (ret < 0) {
LOG_ERROR("Error while decoding frame");
break;
};
};
};
LOG("after setSprop");
free(buf);
m_sAvPkt.data = NULL;
m_sAvPkt.size = 0;
}
#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[1024]; \
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 ): basicMediaSource(), /* MediaSink(*m_pUsageEnvironment),*/ basicThread(){
m_bIsParamsSet = false;
m_pOpaque = opaque;
m_pScheduler = BasicTaskScheduler::createNew();
m_pUsageEnvironment = BasicUsageEnvironment::createNew(*m_pScheduler);
m_pLog = basicLogCollection::getInstance();
// Default -> only decode frames
m_eWM = MS_MODE_DECODE_FRAMES;
m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1;
initLibAV();
}
videoLIVE555Source::videoLIVE555Source(CSTR URI, void * opaque, MS_WORK_MODE mode): basicMediaSource(),/* MediaSink(*m_pUsageEnvironment),*/ basicThread(){
m_pLog = basicLogCollection::getInstance();
m_pOpaque = opaque;
m_bIsParamsSet = true;
m_eWM = mode;
m_pScheduler = BasicTaskScheduler::createNew();
m_pUsageEnvironment = BasicUsageEnvironment::createNew(*m_pScheduler);
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)
{
LOG("Start Thread");
_eventLoopWatchVariable = 0;
m_bThreadStatus = TH_WORKING;
pthread_setname_np(pthread_self(), "Live555 Source");
// while ( m_bThreadStatus == TH_WORKING ) {
m_pScheduler->doEventLoop(&_eventLoopWatchVariable);
// streamTimerHandler( m_pRtspClient );
// SLEEP(3);
//};
LOG("Rtsp event finished");
// m_pUsageEnvironment->reclaim();
// m_pUsageEnvironment = NULL;
// delete m_pScheduler;
// m_pScheduler = NULL;
LOG("End Thread");
}
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;
};
ME->m_pMediaSession = scs.session;
// 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();
const uint8_t * sps = NULL;
unsigned spsSize = 0;
const uint8_t * 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);
MLOG("Done ContAfterSetup");
}
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)
{
const unsigned 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)
{
MLOG("Shutdown!");
// 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);
}
void videoLIVE555Source::sessionAfterPlaying(void * clientData)
{
MediaSession * session = (MediaSession *) clientData;
if (session->hasSubsessions())
{
MediaSubsessionIterator * itr = new MediaSubsessionIterator(*session);
if (itr != NULL)
{
MediaSubsession * subsession = itr->next();
while (subsession != NULL)
{
RTSPClient * rtspClient = (RTSPClient *) subsession->miscPtr;
CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
//UsageEnvironment & env = rtspClient->envir();
MLOG("sessionAfterPlaying!");
subsession = itr->next();
};
delete itr;
};
};
}
// 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, const char * progName, const char * rtspURL)
{
int a = 0;
if ( env.getErrno() ) a = 1;
if ( progName ) a = 2;
if ( rtspURL ) a = 3;
a = a - 1;
if ( a ) a = 0;
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();
if ( exitCode ) exitCode = exitCode;
#ifdef DEBUG
MLOG("Shutdown EVT");
#endif
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;
//};
//UsageEnvironment & env = rtspClient->envir();
MLOG("sendTearDown");
rtspClient->sendTeardownCommand(*streamClientState.session, NULL);
MLOG("Close Client");
Medium::close(rtspClient);
MLOG("SetLOOP");
_eventLoopWatchVariable = 1;
// MLOG( "Close Session" );
// Medium::close( streamClientState.session );
// MLOG( "Abort Thread" );
// waitThreadEnd( true );
// close RTSP client
// MLOG( "recalm Env" );
// env.reclaim();
// MLOG( "Delete Client" );
// delete MM;
// MLOG( "Delete Sink" );
// delete( (DummySink*) streamClientState.subsession->sink );
//*/
MLOG("Delete Scheduler");
m_pUsageEnvironment->reclaim();
m_pUsageEnvironment = NULL;
delete m_pScheduler;
m_pScheduler = NULL;
MLOG("All Done!");
m_eMediaStatus = MS_CLOSED;
}
// 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)
{
if ( ShowDeviceMenu ) ShowDeviceMenu = false;
if ( framerate ) framerate = framerate;
if ( inputPin ) inputPin = inputPin;
if (URI == NULL)
{
LOG_ERROR("Trying to open MediaSource without MRL!");
return false;
};
// if( !m_bIsParamsSet ) {
// LOG_ERROR("Trying to open MediaSource without all needded parameters!");
// return false;
// };
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;
LOG_ERROR("Error Consume Frame by Media Destination!");
};
}
bool videoLIVE555Source::_close(void)
{
LOG("CLOSE!");
return _stop();
}
bool videoLIVE555Source::_stop(void)
{
LOG("STOP!");
shutdownStream(m_pRtspClient);
return true;
}
bool videoLIVE555Source::isFinished(void)
{
return (m_eMediaStatus == MS_CLOSED);
}
MediaStateStatus videoLIVE555Source::getStatus(void)
{
return m_eMediaStatus;
}
bool videoLIVE555Source::setSize(int Width, int Height)
{
if( Width || Height ) return false;
return false;
}
bool videoLIVE555Source::setProportionalByWidth(int Width)
{
if( !Width ) return false;
return false;
}
bool videoLIVE555Source::setProportionalByHeight(int Height)
{
if( !Height ) return false;
return false;
}
bool videoLIVE555Source::setFPS(int A )
{
if( !A ) return false;
return false;
}
bool videoLIVE555Source::setName(CSTR Name)
{
if( !Name ) return false;
return false;
}
bool videoLIVE555Source::setFrameAspectRatio(FrameAspectRatio AspectRatio)
{
if( AspectRatio ) AspectRatio = AspectRatio;
return false;
}
#undef MLOG
#undef LOG
#undef LOG_ERROR
#undef FF_DISABLE_DEPRECATION_WARNINGS
#endif //!LRF_PROXY_ONLY