diff --git a/lib/data/media/video/videoLive555AVLibSource.cpp b/lib/data/media/video/videoLive555AVLibSource.cpp index db1272ce..2a115e0c 100644 --- a/lib/data/media/video/videoLive555AVLibSource.cpp +++ b/lib/data/media/video/videoLive555AVLibSource.cpp @@ -61,9 +61,23 @@ DummySink * DummySink::createNew(videoLIVE555Source * session, UsageEnvironment DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, MediaSubsession & subsession, const char * streamId, int w, int h, int ww, int hh) : MediaSink(env), + m_pRGB(NULL), m_pSession(session), //m_iFrameIndex(0), - m_sSubSession(subsession) + m_sSubSession(subsession), + qtOut(NULL), + m_pCodec(NULL), + m_pCodecContext(NULL), + m_pOutCodec(NULL), + m_pOutCodecContext(NULL), + m_pOutFormatCtx(NULL), + m_pOutFormatOpts(NULL), + m_pOutStream(NULL), + m_pH264(NULL), + m_pFrame(NULL), + m_pRGBFrame(NULL), + m_pSwsContext(NULL), + m_bOutHeaderWritten(false) { m_pLog = basicLogCollection::getInstance(); @@ -85,7 +99,8 @@ DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, Media m_pReceiveBufferAV[2] = 0; m_pReceiveBufferAV[3] = 1; - //av_init_packet(&m_sAvPkt); + // av_packet_unref() also releases opaque_ref / side_data: every field must be defined + memset(&m_sAvPkt, 0, sizeof(m_sAvPkt)); m_sAvPkt.pts = AV_NOPTS_VALUE; m_sAvPkt.dts = AV_NOPTS_VALUE; m_sAvPkt.pos = -1; @@ -124,6 +139,11 @@ DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, Media }; m_pCodecContext = avcodec_alloc_context3(m_pCodec); + if (m_pCodecContext == NULL) + { + LOG_ERROR("could not allocate codec context!"); + return; + }; #if (LIBAVCODEC_VERSION_MAJOR >= 60) #else if (m_pCodec->capabilities & AV_CODEC_CAP_TRUNCATED) @@ -146,6 +166,7 @@ DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, Media if (avcodec_open2(m_pCodecContext, m_pCodec, NULL) < 0) { LOG_ERROR("could not open codec!"); + avcodec_free_context(&m_pCodecContext); // NULL: the frames are not decoded return; }; if (m_pSession->getWM() & MS_MODE_STREAM_PROXY) @@ -175,6 +196,12 @@ DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, Media // v60 const AVCodec *codec = avcodec_find_decoder( m_pOutStream->codecpar->codec_id ); AVCodecContext * c = avcodec_alloc_context3( codec );//m_pOutStream->codec; + if (c == NULL) + { + LOG_ERROR("Output Codec Context Allocation Error"); + } + else + { c->codec_id = m_eCodecProbe; c->codec_type = AVMEDIA_TYPE_VIDEO; @@ -211,15 +238,21 @@ DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, Media LOG("Global Header Flag is Set!"); }; + avcodec_free_context(&c); // only used to compute the flags above + }; 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) + } + else if (avformat_write_header(m_pOutFormatCtx, &m_pOutFormatOpts) < 0) { LOG_ERROR("Error occurred when writing header to output file."); // return false; + } + else + { + m_bOutHeaderWritten = true; // av_write_trailer() only after a written header }; } }; @@ -364,27 +397,30 @@ DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, Media // qtOut->startPlaying( NULL, NULL ); LOG("QTFS Started Play"); }; - } - else if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES) + }; + // Not "else if": afterGettingFrame() decodes whenever DECODE_FRAMES is set, also together with + // STREAM_PROXY - the frames / scaler must exist then (they were used uninitialized) + 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 + int ret = (m_pRGBFrame != NULL) ? av_image_alloc( m_pRGBFrame->data, m_pRGBFrame->linesize, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, 32) : -1; // 32 for alignment if (ret < 0) { - // Handle error LOG_ERROR("Error Allocating RGBFrame!"); + av_frame_free(&m_pRGBFrame); // NULL: no decoding (see canDecode()) }; 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); + if (m_pSwsContext == NULL) + { + LOG_ERROR("Error Creating Scaler!"); + }; 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]; @@ -395,65 +431,60 @@ DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, Media DummySink::~DummySink() { - if (m_pSession->getWM() & MS_MODE_STREAM_PROXY) + // Every pointer is NULL unless it was allocated (the constructor can return early) + if (m_pOutFormatCtx != NULL) { - if (m_pOutFormatCtx != NULL) + if (m_bOutHeaderWritten) { 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) + if (m_pOutFormatCtx->pb != NULL) { - Medium::close(qtOut); - qtOut = NULL; + avio_closep(&m_pOutFormatCtx->pb); }; - } - 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); + avformat_free_context(m_pOutFormatCtx); + m_pOutFormatCtx = NULL; }; - if (m_pRGBFrame) + av_dict_free(&m_pOutFormatOpts); + for (int i = 0; i < 2; i++) { + if (m_pOutFile[i] != NULL) + { + fflush(m_pOutFile[i]); + pclose(m_pOutFile[i]); + m_pOutFile[i] = NULL; + }; }; - if (m_pSwsContext) + if (qtOut != NULL) { + Medium::close(qtOut); + qtOut = NULL; }; - if (m_pCodecContext) + free(m_pH264); + + if (m_pSwsContext != NULL) { + sws_freeContext(m_pSwsContext); }; - if (m_pCodec) + if (m_pRGBFrame != NULL) { + av_freep(&m_pRGBFrame->data[0]); // av_image_alloc() buffer + av_frame_free(&m_pRGBFrame); }; + av_frame_free(&m_pFrame); // was av_free(): leaked the frame buffers + delete m_pRGB; + avcodec_free_context(&m_pCodecContext); // also closes it + delete[] m_pReceiveBuffer; delete[] m_pReceiveBufferAV; delete[] m_pStreamId; } +bool DummySink::canDecode(void) const +{ + return m_pCodecContext != NULL && m_pFrame != NULL && m_pRGBFrame != NULL && m_pSwsContext != NULL && m_pRGB != NULL; +} + void DummySink::afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { DummySink * sink = (DummySink *) clientData; @@ -486,7 +517,7 @@ void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes m_sAvPkt.size = frameSize + 4; m_sAvPkt.data = m_pReceiveBufferAV; - if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES){ + if ((m_pSession->getWM() & MS_MODE_DECODE_FRAMES) && canDecode()){ int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt ); if( ret < 0 ){ LOG_ERROR("Error Send Packet to Decoder!"); @@ -513,7 +544,7 @@ void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes }; }; av_packet_unref(&m_sAvPkt); - if (m_pSession->getWM() & MS_MODE_STREAM_PROXY) + if ((m_pSession->getWM() & MS_MODE_STREAM_PROXY) && m_pH264 != NULL) { if (m_pSession->getWM() & MS_MODE_OVERLAYED_LOOPS) @@ -677,7 +708,7 @@ void DummySink::setSprop(const u_int8_t * prop, unsigned size) }; memcpy(buf_start, prop, size); m_sAvPkt.size = size + 4; - if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES){ + if ((m_pSession->getWM() & MS_MODE_DECODE_FRAMES) && canDecode()){ int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt ); if( ret < 0 ){ LOG_ERROR("Error Send Packet to Decoder!"); @@ -715,12 +746,25 @@ void DummySink::setSprop(const u_int8_t * prop, unsigned size) #define LOG_ERROR(X) m_pLog->Log("LIVE555_SRC", this, _LOG_ERROR, X); #endif +void videoLIVE555Source::initMembers(void) +{ + m_pLog = basicLogCollection::getInstance(); + m_pRtspClient = NULL; + m_pSink = NULL; + m_pMediaSession = NULL; + fSubsession = NULL; + fStreamId = NULL; + fReceiveBuffer = NULL; + _eventLoopWatchVariable = 0; + m_tEventLoopThread = pthread_t(); + m_pScheduler = BasicTaskScheduler::createNew(); + m_pUsageEnvironment = BasicUsageEnvironment::createNew(*m_pScheduler); +} + videoLIVE555Source::videoLIVE555Source(void * opaque ): basicMediaSource(), /* MediaSink(*m_pUsageEnvironment),*/ basicThread(){ + initMembers(); 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; @@ -729,26 +773,44 @@ videoLIVE555Source::videoLIVE555Source(void * opaque ): basicMediaSource(), /* M } videoLIVE555Source::videoLIVE555Source(CSTR URI, void * opaque, MS_WORK_MODE mode): basicMediaSource(),/* MediaSink(*m_pUsageEnvironment),*/ basicThread(){ - m_pLog = basicLogCollection::getInstance(); + initMembers(); 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); } +/* + The destructor crashed the application: + - _stop() -> shutdownStream() ran on the caller's thread while the live555 thread was still inside + doEventLoop(): the RTSP client and the task scheduler were deleted under the running loop; + - the scheduler / environment were deleted there and dereferenced again by a second shutdown + (_close() then the destructor, or a shutdown from a live555 callback then the destructor); + - m_pRtspClient was not initialized: a source that was never opened (or failed to open) shut + down a random pointer; + - ~basicThread joins only after this object is destroyed: the thread still ran our members. + Now: stop the loop and join the thread first, then close the stream on this thread, and the + environment / scheduler only here, once. +*/ videoLIVE555Source::~videoLIVE555Source(){ _stop(); - // if ( m_pSink ) delete( m_pSink ); + if (m_pUsageEnvironment != NULL) + { + m_pUsageEnvironment->reclaim(); // deletes it once no live555 object uses it any more + m_pUsageEnvironment = NULL; + }; + delete m_pScheduler; + m_pScheduler = NULL; } void videoLIVE555Source::m_fThreadProc(void) { LOG("Start Thread"); - _eventLoopWatchVariable = 0; + // _eventLoopWatchVariable is reset by _open(): resetting it here lost a _stop() issued + // before the thread got to run (the loop then never ended) + m_tEventLoopThread = pthread_self(); m_bThreadStatus = TH_WORKING; pthread_setname_np(pthread_self(), "Live555 Source"); // while ( m_bThreadStatus == TH_WORKING ) { @@ -967,7 +1029,7 @@ void videoLIVE555Source::continueAfterPLAY(RTSPClient * rtspClient, int resultCo success = True; } while (0); - // delete[] resultString; + delete[] resultString; if (! success) { MLOG("Shutdown!"); @@ -1128,51 +1190,60 @@ void videoLIVE555Source::setupNextSubsession(RTSPClient * rtspClient) }; } -// Used to shut down and close a stream (including its "RTSPClient" object): +// Used to shut down and close a stream (including its "RTSPClient" object). +// Runs either on the live555 thread (from a live555 callback) or, once that thread was joined, +// on the thread that stops the source - never on both at once. It does not delete the +// scheduler / environment (the event loop may still be using them): the destructor does that. void videoLIVE555Source::shutdownStream(RTSPClient * rtspClient, int exitCode) { - CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; - videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession(); - if ( exitCode ) exitCode = exitCode; + if ( exitCode ) exitCode = exitCode; + if (rtspClient == NULL || rtspClient != m_pRtspClient) + { + _eventLoopWatchVariable = 1; + return; // already closed (a second shutdown closed a deleted client before) + }; + CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient; #ifdef DEBUG - MLOG("Shutdown EVT"); + LOG("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"); - //Must be checked if Client is connected before sending TearDown!!! - //rtspClient->sendTeardownCommand(*streamClientState.session, NULL); - MLOG("Close Client"); + + // First, check whether any subsessions have still to be closed (as live555 testRTSPClient): + // the sinks were never closed before - they leaked and kept reading a deleted source + if (streamClientState.session != NULL) + { + Boolean someSubsessionsWereActive = False; + MediaSubsessionIterator iter(*streamClientState.session); + MediaSubsession * subsession; + while ((subsession = iter.next()) != NULL) + { + if (subsession->sink != NULL) + { + Medium::close(subsession->sink); + subsession->sink = NULL; + if (subsession->rtcpInstance() != NULL) + { + subsession->rtcpInstance()->setByeHandler(NULL, NULL); // in case the server sends a RTCP "BYE" while handling "TEARDOWN" + }; + someSubsessionsWereActive = True; + }; + }; + if (someSubsessionsWereActive) + { + // Send a RTSP "TEARDOWN" command, to tell the server to shutdown the stream. + // Don't bother handling the response to the "TEARDOWN". + LOG("sendTearDown"); + rtspClient->sendTeardownCommand(*streamClientState.session, NULL); + }; + }; + + LOG("Close Client"); + m_pRtspClient = NULL; + m_pMediaSession = NULL; // closed with the client (StreamClientState destructor) 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; + _eventLoopWatchVariable = 1; // ends doEventLoop() + m_eMediaStatus = MS_CLOSED; + LOG("All Done!"); } // https://chowdera.com/2021/01/20210102084512591N.html @@ -1207,8 +1278,15 @@ bool videoLIVE555Source::_open(CSTR URI, bool ShowDeviceMenu, float framerate, i LOG_ERROR(tB); return false; }; + _eventLoopWatchVariable = 0; m_pRtspClient->sendDescribeCommand(continueAfterDESCRIBE); - return init(); + if (! init()) + { + LOG_ERROR("Can not start the live555 thread!"); + shutdownStream(m_pRtspClient); // no event loop is running: safe on this thread + return false; + }; + return true; } void videoLIVE555Source::consumeFrame(cv::Mat * frm) @@ -1233,10 +1311,24 @@ bool videoLIVE555Source::_close(void) bool videoLIVE555Source::_stop(void) { LOG("STOP!"); - shutdownStream(m_pRtspClient); + // live555 is single threaded: never touch its objects while its event loop runs on the other + // thread. Stop the loop and wait for the thread, then close what is left here. + _eventLoopWatchVariable = 1; + if (isEventLoopThread()) + { + return true; // called from a live555 callback: shutdown after the loop is left (destructor / _stop) + }; + waitThreadEnd(true); + shutdownStream(m_pRtspClient); // no-op when a live555 callback closed it already return true; } +bool videoLIVE555Source::isEventLoopThread(void) +{ + // m_bThreadStatus: getStatus() of this class is the media status + return m_bThreadStatus == TH_WORKING && pthread_equal(pthread_self(), m_tEventLoopThread); +} + bool videoLIVE555Source::isFinished(void) { return (m_eMediaStatus == MS_CLOSED); diff --git a/lib/data/media/video/videoLive555AVLibSource.h b/lib/data/media/video/videoLive555AVLibSource.h index 8f4ad122..6d24caf9 100644 --- a/lib/data/media/video/videoLive555AVLibSource.h +++ b/lib/data/media/video/videoLive555AVLibSource.h @@ -126,6 +126,10 @@ class DummySink : public MediaSink AVFrame * m_pRGBFrame; SwsContext * m_pSwsContext; + bool m_bOutHeaderWritten; + + bool canDecode(void) const; // decoder, frames and scaler were all created + uint8_t m_aInBuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE]; // char buf[1024]; AVPacket m_sAvPkt; @@ -180,6 +184,10 @@ class videoLIVE555Source : public basicMediaSource, public basicThread // Used to shut down and close a stream (including its "RTSPClient" object): void shutdownStream(RTSPClient * rtspClient, int exitCode = 1); + pthread_t m_tEventLoopThread; + void initMembers(void); + bool isEventLoopThread(void); // called from a live555 callback + protected: void m_fThreadProc(void);