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.

1289 lines
41 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "videoLive555AVLibSource.h"
  2. #ifndef LRF_PROXY_ONLY
  3. #define FF_DISABLE_DEPRECATION_WARNINGS
  4. StreamClientState::StreamClientState() :
  5. iter(NULL),
  6. session(NULL),
  7. subsession(NULL),
  8. streamTimerTask(NULL),
  9. duration(0.0)
  10. {
  11. }
  12. StreamClientState::~StreamClientState()
  13. {
  14. delete iter;
  15. if (session != NULL)
  16. {
  17. // We also need to delete "session", and unschedule "streamTimerTask" (if set)
  18. UsageEnvironment & env = session->envir(); // alias
  19. env.taskScheduler().unscheduleDelayedTask(streamTimerTask);
  20. Medium::close(session);
  21. };
  22. }
  23. CustomRTSPClient * CustomRTSPClient::createNew(videoLIVE555Source * session, UsageEnvironment & env, const char * rtspURL, int verbosityLevel, const char * applicationName, portNumBits tunnelOverHTTPPortNum)
  24. {
  25. return new CustomRTSPClient(session, env, rtspURL, verbosityLevel, applicationName, tunnelOverHTTPPortNum);
  26. }
  27. CustomRTSPClient::CustomRTSPClient(videoLIVE555Source * session, UsageEnvironment & env, const char * rtspURL, int verbosityLevel, const char * applicationName, portNumBits tunnelOverHTTPPortNum) :
  28. RTSPClient(env, rtspURL, verbosityLevel, applicationName, tunnelOverHTTPPortNum, -1),
  29. session(session)
  30. {
  31. }
  32. CustomRTSPClient::~CustomRTSPClient() {}
  33. #define LOG(X) m_pLog->Log("LIVE555_SIN", this, X)
  34. #define MLOG(X) ME->m_pLog->Log("LIVE555_SIN", ME, X)
  35. #ifdef DEBUG
  36. #define LOG_ERROR(X) \
  37. { \
  38. char _tBfrErrMSG2w34[1024]; \
  39. sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  40. m_pLog->Log("LIVE555_SIN", this, _LOG_ERROR, _tBfrErrMSG2w34); \
  41. }
  42. #else
  43. #define LOG_ERROR(X) m_pLog->Log("LIVE555_SIN", this, _LOG_ERROR, X);
  44. #endif
  45. DummySink * DummySink::createNew(videoLIVE555Source * session, UsageEnvironment & env, MediaSubsession & subsession, char const * streamId, int w, int h, int ww, int hh)
  46. {
  47. return new DummySink(session, env, subsession, streamId, w, h, ww, hh);
  48. }
  49. DummySink::DummySink(videoLIVE555Source * session, UsageEnvironment & env, MediaSubsession & subsession, const char * streamId, int w, int h, int ww, int hh) :
  50. MediaSink(env),
  51. m_pSession(session),
  52. //m_iFrameIndex(0),
  53. m_sSubSession(subsession)
  54. {
  55. m_pLog = basicLogCollection::getInstance();
  56. m_pStreamId = strDup(streamId);
  57. m_iFrameIndex = 0;
  58. m_nCurrentOutFile = 0;
  59. m_pOutFile[0] = m_pOutFile[1] = NULL;
  60. m_nInWidth = w;
  61. m_nInHeight = h;
  62. m_nOutWidth = ww;
  63. m_nOutHeight = hh;
  64. m_pReceiveBuffer = new uint8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE];
  65. m_pReceiveBufferAV = new uint8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE + 4];
  66. m_pReceiveBufferAV[0] = 0;
  67. m_pReceiveBufferAV[1] = 0;
  68. m_pReceiveBufferAV[2] = 0;
  69. m_pReceiveBufferAV[3] = 1;
  70. //av_init_packet(&m_sAvPkt);
  71. m_sAvPkt.pts = AV_NOPTS_VALUE;
  72. m_sAvPkt.dts = AV_NOPTS_VALUE;
  73. m_sAvPkt.pos = -1;
  74. m_sAvPkt.duration = 0;
  75. //m_sAvPkt.convergence_duration = 0; //is deprecated
  76. m_sAvPkt.flags = AV_PKT_FLAG_KEY;
  77. m_sAvPkt.stream_index = 0;
  78. m_sAvPkt.buf = NULL;
  79. m_sAvPkt.side_data = NULL;
  80. m_sAvPkt.side_data_elems = 0;
  81. memset(m_aInBuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
  82. LOG(m_sSubSession.codecName());
  83. m_eCodecProbe = AV_CODEC_ID_NONE;
  84. if (strcmp(m_sSubSession.codecName(), "JPEG") == 0)
  85. {
  86. m_eCodecProbe = AV_CODEC_ID_MJPEG;
  87. }
  88. else if (strcmp(m_sSubSession.codecName(), "H264") == 0)
  89. {
  90. m_eCodecProbe = AV_CODEC_ID_H264;
  91. }
  92. else if (strcmp(m_sSubSession.codecName(), "H265") == 0)
  93. {
  94. m_eCodecProbe = AV_CODEC_ID_HEVC;
  95. };
  96. m_pCodec = avcodec_find_decoder(m_eCodecProbe);
  97. if (m_pCodec == NULL)
  98. {
  99. LOG_ERROR("codec not found!");
  100. return;
  101. };
  102. m_pCodecContext = avcodec_alloc_context3(m_pCodec);
  103. if (m_pCodec->capabilities & AV_CODEC_CAP_TRUNCATED)
  104. {
  105. m_pCodecContext->flags |= AV_CODEC_FLAG_TRUNCATED; // we do not send complete frames
  106. };
  107. if ((m_sSubSession.videoWidth() > 0) && (m_sSubSession.videoHeight() > 0))
  108. {
  109. m_nInWidth = m_sSubSession.videoWidth();
  110. m_nInHeight = m_sSubSession.videoHeight();
  111. };
  112. m_pCodecContext->width = m_nInWidth;
  113. m_pCodecContext->height = m_nInHeight;
  114. // Must be carefull! and get pix_fmt from stream
  115. m_pCodecContext->pix_fmt = AV_PIX_FMT_YUV420P;
  116. if (avcodec_open2(m_pCodecContext, m_pCodec, NULL) < 0)
  117. {
  118. LOG_ERROR("could not open codec!");
  119. return;
  120. };
  121. if (m_pSession->getWM() & MS_MODE_STREAM_PROXY)
  122. {
  123. m_pH264 = (uint8_t *) malloc(256 * 1024);
  124. m_pOutFormatCtx = NULL;
  125. m_pOutFormatOpts = NULL;
  126. if (avformat_alloc_output_context2(&m_pOutFormatCtx, NULL, NULL, "test.mp4") < 0)
  127. {
  128. LOG_ERROR("VideoFormat Context Memory Allocation Error");
  129. // return false;
  130. }
  131. else
  132. {
  133. m_pOutFormatCtx->oformat = av_guess_format("mp4", NULL, NULL);
  134. if (m_pOutFormatCtx->oformat != NULL)
  135. {
  136. av_dict_set(&m_pOutFormatOpts, "brand", "mp42", 0);
  137. av_dict_set(&m_pOutFormatOpts, "movflags", "faststart", 0);
  138. m_pOutFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  139. m_pOutStream = avformat_new_stream(m_pOutFormatCtx, NULL);
  140. if (m_pOutStream != NULL)
  141. {
  142. AVCodec *codec = avcodec_find_decoder( m_pOutStream->codecpar->codec_id );
  143. AVCodecContext * c = avcodec_alloc_context3( codec );//m_pOutStream->codec;
  144. c->codec_id = m_eCodecProbe;
  145. c->codec_type = AVMEDIA_TYPE_VIDEO;
  146. /* put sample parameters */
  147. c->bit_rate = m_sSubSession.bandwidth(); // 400000;
  148. /* resolution must be a multiple of two */
  149. c->width = m_sSubSession.videoWidth();
  150. c->height = m_sSubSession.videoHeight();
  151. /* time base: this is the fundamental unit of time (in seconds) in terms
  152. of which frame timestamps are represented. for fixed-fps content,
  153. timebase should be 1/framerate and timestamp increments should be
  154. identically 1. */
  155. c->time_base.den = m_sSubSession.videoFPS();
  156. c->time_base.num = 1;
  157. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  158. c->pix_fmt = AV_PIX_FMT_YUV420P;
  159. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO)
  160. {
  161. /* just for testing, we also add B frames */
  162. c->max_b_frames = 2;
  163. }
  164. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO)
  165. {
  166. /* needed to avoid using macroblocks in which some coeffs overflow
  167. this doesnt happen with normal video, it just happens here as the
  168. motion of the chroma plane doesnt match the luma plane */
  169. c->mb_decision = 2;
  170. }
  171. // some formats want stream headers to be seperate
  172. if (! strcmp(m_pOutFormatCtx->oformat->name, "mp4") || ! strcmp(m_pOutFormatCtx->oformat->name, "mov") || ! strcmp(m_pOutFormatCtx->oformat->name, "3gp"))
  173. {
  174. c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  175. LOG("Global Header Flag is Set!");
  176. };
  177. if (avio_open(&m_pOutFormatCtx->pb, "test_99.mp4", AVIO_FLAG_WRITE) < 0)
  178. {
  179. LOG_ERROR("Could not open output file.");
  180. // return false;
  181. };
  182. if (avformat_write_header(m_pOutFormatCtx, &m_pOutFormatOpts) < 0)
  183. {
  184. LOG_ERROR("Error occurred when writing header to output file.");
  185. // return false;
  186. };
  187. }
  188. };
  189. };
  190. /*
  191. m_pOutCodec = = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  192. if( m_pOutCodec == NULL ) {
  193. LOG_ERROR( "output codec not found!" );
  194. //m_pSession->setWM( m_pSession->getWM() & ( ~ MS_MODE_STREAM_PROXY ) );
  195. return;
  196. };
  197. m_pOutCodecContext = avcodec_alloc_context3( m_pOutCodec );
  198. if( m_pOutCodecContext == NULL ){
  199. LOG_ERROR("VideoCodec Context Memory Allocation Error");
  200. return;
  201. } else {
  202. LOG("Codec Context3 Allocated");
  203. };
  204. if( avformat_alloc_output_context2( &m_pOutFormatCtx, NULL, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  205. LOG_ERROR("VideoFormat Context Memory Allocation Error");
  206. return;
  207. };
  208. m_pOutFormatCtx->oformat = av_guess_format( VIDEO_OUTPUT_CONTAINER, NULL, NULL );
  209. if( m_pOutFormatCtx->oformat == NULL ){
  210. LOG_ERROR("VideoFormat Format Not Guessed!");
  211. return;
  212. } else {
  213. LOG("Video Container Format Guessed");
  214. };
  215. m_pOutVideoStr = avformat_new_stream( m_pOutFormatCtx, m_pOutCodec );
  216. if( m_pOutVideoStr == NULL){
  217. LOG_ERROR("VideoStream Not Created!");
  218. } else {
  219. LOG("VideoStream is Created");
  220. };
  221. m_pOutCodecContext->codec_id = VIDEO_OUTPUT_CODEC;
  222. m_pOutCodecContext->codec_type = AVMEDIA_TYPE_VIDEO;
  223. m_pOutCodecContext->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  224. m_pOutCodecContext->bit_rate = VIDEO_OUTPUT_BITRATE;
  225. //m_pOutCodecContext->bit_rate_tolerance = 1;
  226. //m_pOutCodecContext->global_quality = 100;
  227. //m_pOutCodecContext->compression_level = 2;
  228. m_pOutCodecContext->width = m_nWidth;
  229. m_pOutCodecContext->height = m_nHeight;
  230. m_pOutCodecContext->time_base.num = 1;
  231. m_pOutCodecContext->time_base.den = VIDEO_OUTPUT_FPS;
  232. m_pOutCodecContext->gop_size = VIDEO_OUTPUT_GOP; // emit one intra frame every ten frames
  233. //m_pVideoState->m_pCodecCtx->qmin = 15;
  234. //m_pVideoState->m_pCodecCtx->qmax = 30;
  235. m_pOutCodecContext->flags |= CODEC_FLAG_GLOBAL_HEADER;
  236. if( m_pVideoState->m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ){
  237. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  238. //Set format's privater options, to be passed to avformat_write_header()
  239. LOG("Begin Options!");
  240. int RetVal = 0;
  241. //RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "movflags", "faststart", 0);
  242. //if( RetVal < 0 ){
  243. // LOG_ERROR( "av_dict_set movflags!");
  244. //};
  245. //default brand is "isom", which fails on some devices
  246. RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "brand", "mp42", 0);
  247. if( RetVal < 0 ){
  248. LOG_ERROR( "av_dict_set brand!" );
  249. };
  250. //m_pVideoState->m_pCodecCtx->max_b_frames = 1;
  251. m_pVideoState->m_pCodecCtx->level = 31;
  252. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "crf", "12", 0);
  253. if( RetVal < 0 ){
  254. LOG_ERROR("av_opt_set crf");
  255. };
  256. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "profile", "main", 0);
  257. if( RetVal < 0 ){
  258. LOG_ERROR("av_opt_set profile");
  259. };
  260. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "preset", "slow", 0);
  261. if( RetVal < 0 ){
  262. LOG_ERROR("av_opt_set preset");
  263. };
  264. // Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  265. // Because Quicktime (ie. iOS) doesn't support this option
  266. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "b-pyramid", "0", 0);
  267. if( RetVal < 0 ){
  268. LOG_ERROR("av_opt_set b-pyramid");
  269. };
  270. LOG("End Options!");
  271. };
  272. //See up one page ->
  273. avcodec_get_context_defaults3(m_pVideoState->m_pVideoStr->codec, m_pVideoState->m_pVideoCodec);
  274. const AVRational dst_fps = { VIDEO_OUTPUT_FPS, 1 };
  275. m_pVideoState->m_pVideoStr->codec->width = m_nWidth;
  276. m_pVideoState->m_pVideoStr->codec->height = m_nHeight;
  277. m_pVideoState->m_pVideoStr->codec->pix_fmt = m_pVideoState->m_pVideoCodec->pix_fmts[0];
  278. m_pVideoState->m_pVideoStr->codec->time_base = m_pVideoState->m_pVideoStr->time_base = av_inv_q(dst_fps);
  279. m_pVideoState->m_pVideoStr->r_frame_rate = m_pVideoState->m_pVideoStr->avg_frame_rate = dst_fps;
  280. if (m_pVideoState->m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER) m_pVideoState->m_pVideoStr->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  281. //---->>
  282. if (avcodec_is_open(m_pVideoState->m_pCodecCtx) == 0) {
  283. LOG("output codec context is closed, opening");
  284. int ret = avcodec_open2(m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoCodec, NULL);
  285. if (ret < 0) {
  286. LOG_ERROR("Error opening2 encoder");
  287. char buffer[200];
  288. sprintf(buffer, "Error code: %i", ret );
  289. LOG_ERROR(buffer);
  290. return false;
  291. }
  292. }else{
  293. LOG("output codec context is opened");
  294. };
  295. */
  296. // https://github.com/rgaufman/live555/blob/master/testProgs/playCommon.cpp
  297. // http://www.live555.com/liveMedia//doxygen/html/QuickTimeFileSink_8hh_source.html
  298. // qtOut = QuickTimeFileSink::createNew(*env, *session, outFileName,
  299. // fileSinkBufferSize,
  300. // movieWidth, movieHeight,
  301. // movieFPS,
  302. // packetLossCompensate,
  303. // syncStreams,
  304. // generateHintTracks,
  305. // generateMP4Format);
  306. /* qtOut = QuickTimeFileSink::createNew( env, *session->getMS(), "TEST.mp4",
  307. 100000,
  308. subsession.videoWidth(), subsession.videoHeight(),
  309. subsession.videoFPS(),
  310. 0,
  311. 0,
  312. 0,
  313. 1);
  314. */
  315. qtOut = (H264or5VideoFileSink *) H264VideoFileSink::createNew(env, "TEST22.mp4");
  316. if (qtOut != NULL)
  317. {
  318. LOG("Created QTFS ---> Test.mp4");
  319. // qtOut->startPlaying( NULL, NULL );
  320. LOG("QTFS Started Play");
  321. };
  322. }
  323. else if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES)
  324. {
  325. // Allocate Mems
  326. m_pFrame = av_frame_alloc();
  327. m_pRGBFrame = av_frame_alloc();
  328. //avpicture_alloc((AVPicture *) m_pRGBFrame, AV_PIX_FMT_BGR24, m_nOutWidth, m_nOutHeight);
  329. int ret = av_image_alloc( m_pRGBFrame->data, m_pRGBFrame->linesize, m_nOutWidth, m_nOutHeight, AV_PIX_FMT_BGR24, 32); // 32 for alignment
  330. if (ret < 0) {
  331. // Handle error
  332. LOG_ERROR("Error Allocating RGBFrame!");
  333. };
  334. 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);
  335. m_pRGB = new cv::Mat(m_nOutHeight, m_nOutWidth, CV_8UC3, cv::Scalar(255, 0, 255));
  336. }
  337. else
  338. {
  339. LOG("No Decode Frames Mode!");
  340. m_pFrame = m_pRGBFrame = NULL;
  341. m_pSwsContext = NULL;
  342. m_pRGB = NULL;
  343. };
  344. #ifdef DEBUG
  345. char tB[128];
  346. sprintf(tB, "Created Sink [%dx%d]->[%dx%d]", m_pCodecContext->width, m_pCodecContext->height, m_nOutWidth, m_nOutHeight);
  347. LOG(tB);
  348. #endif
  349. }
  350. DummySink::~DummySink()
  351. {
  352. if (m_pSession->getWM() & MS_MODE_STREAM_PROXY)
  353. {
  354. if (m_pOutFormatCtx != NULL)
  355. {
  356. av_write_trailer(m_pOutFormatCtx);
  357. avio_close(m_pOutFormatCtx->pb);
  358. };
  359. if (m_pOutFile[0] != NULL)
  360. {
  361. fflush(m_pOutFile[0]);
  362. pclose(m_pOutFile[0]);
  363. };
  364. if (m_pOutFile[1] != NULL)
  365. {
  366. fflush(m_pOutFile[1]);
  367. pclose(m_pOutFile[1]);
  368. };
  369. if (qtOut != NULL)
  370. {
  371. Medium::close(qtOut);
  372. qtOut = NULL;
  373. };
  374. }
  375. else if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES)
  376. {
  377. };
  378. /*Medium::close(qtOut); qtOut = NULL;
  379. Medium::close(aviOut); aviOut = NULL;
  380. if (session == NULL) return;
  381. MediaSubsessionIterator iter(*session);
  382. MediaSubsession* subsession;
  383. while ((subsession = iter.next()) != NULL) {
  384. Medium::close(subsession->sink);
  385. subsession->sink = NULL;
  386. }*/
  387. if (m_pFrame)
  388. {
  389. av_free(m_pFrame);
  390. };
  391. if (m_pRGBFrame)
  392. {
  393. };
  394. if (m_pSwsContext)
  395. {
  396. };
  397. if (m_pCodecContext)
  398. {
  399. };
  400. if (m_pCodec)
  401. {
  402. };
  403. delete[] m_pReceiveBuffer;
  404. delete[] m_pReceiveBufferAV;
  405. delete[] m_pStreamId;
  406. }
  407. void DummySink::afterGettingFrame(void * clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds)
  408. {
  409. DummySink * sink = (DummySink *) clientData;
  410. sink->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds);
  411. }
  412. void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds)
  413. {
  414. // We've just received a frame of data. (Optionally) print out information about it:
  415. // if (strcmp(fSubsession.codecName(),"H264") == 0) {
  416. //LOG("FRM");
  417. if ( presentationTime.tv_sec ) presentationTime.tv_sec = presentationTime.tv_sec;
  418. if ( numTruncatedBytes ) numTruncatedBytes = numTruncatedBytes;
  419. if ( m_eCodecProbe != AV_CODEC_ID_NONE)
  420. {
  421. int got_picture = 0;
  422. memcpy(m_pReceiveBufferAV + 4, m_pReceiveBuffer, frameSize);
  423. m_sAvPkt.pts = AV_NOPTS_VALUE;
  424. m_sAvPkt.dts = AV_NOPTS_VALUE;
  425. m_sAvPkt.pos = -1;
  426. m_sAvPkt.duration = 0;
  427. //m_sAvPkt.convergence_duration = 0; // is deprecated
  428. m_sAvPkt.flags = AV_PKT_FLAG_KEY;
  429. m_sAvPkt.stream_index = 0;
  430. m_sAvPkt.buf = NULL;
  431. m_sAvPkt.side_data = NULL;
  432. m_sAvPkt.side_data_elems = 0;
  433. m_sAvPkt.size = frameSize + 4;
  434. m_sAvPkt.data = m_pReceiveBufferAV;
  435. if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES){
  436. int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt );
  437. if( ret < 0 ){
  438. LOG_ERROR("Error Send Packet to Decoder!");
  439. };
  440. while ( ret >= 0 ) {
  441. ret = avcodec_receive_frame( m_pCodecContext, m_pFrame );
  442. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  443. // EAGAIN: Need more input packets
  444. // EOF: Decoder flushed
  445. break;
  446. } else if (ret < 0) {
  447. // Handle decoding error
  448. break;
  449. };
  450. // LOG( "Picture decoded" );
  451. got_picture = 1;
  452. sws_scale( m_pSwsContext, m_pFrame->data, m_pFrame->linesize, 0, m_pCodecContext->height, m_pRGBFrame->data, m_pRGBFrame->linesize);
  453. memcpy( m_pRGB->data, m_pRGBFrame->data[0], m_pRGBFrame->linesize[0] * m_nOutHeight );
  454. m_pSession->consumeFrame( m_pRGB );
  455. m_iFrameIndex++;
  456. };
  457. if ( ret == AVERROR_EOF ) {
  458. //End
  459. };
  460. };
  461. av_packet_unref(&m_sAvPkt);
  462. if (m_pSession->getWM() & MS_MODE_STREAM_PROXY)
  463. {
  464. if (m_pSession->getWM() & MS_MODE_OVERLAYED_LOOPS)
  465. {
  466. // Sega - Mega - Drive
  467. };
  468. // write packet
  469. #if (0)
  470. // We've just received a frame of data. (Optionally) print out information about it:
  471. #ifdef DEBUG_PRINT_EACH_RECEIVED_FRAME
  472. if (fStreamId != NULL)
  473. {
  474. envir() << "Stream \"" << fStreamId << "\"; ";
  475. }
  476. envir() << fSubsession.mediumName() << "/" << fSubsession.codecName() << ":\tReceived " << frameSize << " bytes";
  477. if (numTruncatedBytes > 0)
  478. {
  479. envir() << " (with " << numTruncatedBytes << " bytes truncated)";
  480. }
  481. char uSecsStr[6 + 1]; // used to output the 'microseconds' part of the presentation time
  482. sprintf(uSecsStr, "%06u", (unsigned) presentationTime.tv_usec);
  483. envir() << ".\tPresentation time: " << (int) presentationTime.tv_sec << "." << uSecsStr;
  484. if (fSubsession.rtpSource() != NULL && ! fSubsession.rtpSource()->hasBeenSynchronizedUsingRTCP())
  485. {
  486. envir() << "!"; // mark the debugging output to indicate that this presentation time is not RTCP-synchronized
  487. }
  488. #ifdef DEBUG_PRINT_NPT
  489. envir() << "\tNPT: " << fSubsession.getNormalPlayTime(presentationTime);
  490. #endif
  491. envir() << "\n";
  492. #endif
  493. #else
  494. //*
  495. // printf("__FUNCTION__ = %s\n", __FUNCTION__ );
  496. // if(0 == strncmp(fSubsession.codecName(), "H264", 16) ){
  497. unsigned char nalu_header[4] = {0, 0, 0, 1};
  498. unsigned char extraData[256];
  499. unsigned int num = 0;
  500. SPropRecord * pSPropRecord;
  501. pSPropRecord = parseSPropParameterSets(m_sSubSession.fmtp_spropparametersets(), num);
  502. unsigned int extraLen;
  503. extraLen = 0;
  504. // p_record[0] is sps
  505. // p+record[1] is pps
  506. for (unsigned int i = 0; i < num; i++)
  507. {
  508. memcpy(&extraData[extraLen], &nalu_header[0], 4);
  509. extraLen += 4;
  510. memcpy(&extraData[extraLen], pSPropRecord[i].sPropBytes, pSPropRecord[i].sPropLength);
  511. extraLen += pSPropRecord[i].sPropLength;
  512. };
  513. memcpy(&extraData[extraLen], &nalu_header[0], 4);
  514. extraLen += 4;
  515. delete[] pSPropRecord;
  516. memcpy(m_pH264, &extraData[0], extraLen);
  517. memcpy(m_pH264 + extraLen, m_pReceiveBuffer, frameSize);
  518. int totalSize;
  519. totalSize = extraLen + frameSize;
  520. if (m_pOutFile[m_nCurrentOutFile] == NULL)
  521. {
  522. // m_pOutFile[m_nCurrentOutFile] = fopen("saved.h264", "wb" );
  523. LOG("Opening");
  524. // m_pOutFile[m_nCurrentOutFile] = popen("ffmpeg -y -hide_banner -i - -vcodec copy -movflags faststart -an ./ttt123.mp4", "w" );
  525. m_pOutFile[m_nCurrentOutFile] = popen("ffmpeg -y -hide_banner -i - -vcodec copy -reserve_index_space 50k -an ./ttt123.mkv", "w");
  526. if (m_pOutFile[m_nCurrentOutFile] == NULL)
  527. {
  528. LOG("Error !!");
  529. };
  530. };
  531. if (m_pOutFile[m_nCurrentOutFile] != NULL)
  532. {
  533. fwrite(m_pH264, 1, totalSize, m_pOutFile[m_nCurrentOutFile]);
  534. fflush(m_pOutFile[m_nCurrentOutFile]);
  535. // fclose( fp );
  536. };
  537. // qtOut->addData( m_pH264, totalSize, presentationTime );
  538. // printf("\tsaved %d bytes\n", totalSize );
  539. // }/*if 0 == strncmp(fSubsession.codecName(), "H264", 16)*/
  540. // if( got_picture ) {
  541. if (m_pOutFormatCtx != NULL)
  542. {
  543. m_sAvPkt.duration = durationInMicroseconds;
  544. if (got_picture)
  545. {
  546. m_sAvPkt.flags |= AV_PKT_FLAG_KEY;
  547. }
  548. m_sAvPkt.stream_index = m_pOutStream->index;
  549. m_sAvPkt.size = totalSize;
  550. m_sAvPkt.data = m_pH264;
  551. // m_sAvPkt.size = frameSize;
  552. // m_sAvPkt.data = m_pReceiveBuffer;
  553. // av_packet_rescale_ts( &avpkt, m_pOutCodec->time_base, time_base );
  554. int r = av_write_frame(m_pOutFormatCtx, &m_sAvPkt);
  555. if (r < 0)
  556. {
  557. char tB[256];
  558. av_strerror(r, tB, 256);
  559. LOG_ERROR("Trouble with Video Output!");
  560. LOG_ERROR(tB);
  561. };
  562. }
  563. //}
  564. #endif
  565. };
  566. #ifdef DEBUG
  567. }
  568. else
  569. {
  570. LOG("Codec Not Handled!");
  571. LOG(m_sSubSession.codecName());
  572. #endif
  573. };
  574. // Then continue, to request the next frame of data:
  575. continuePlaying();
  576. }
  577. Boolean DummySink::continuePlaying()
  578. {
  579. if (fSource == NULL)
  580. {
  581. return False; // sanity check (should not happen)
  582. }
  583. // Request the next frame of data from our input source. "afterGettingFrame()" will get called later, when it arrives:
  584. fSource->getNextFrame(m_pReceiveBuffer, DUMMY_SINK_RECEIVE_BUFFER_SIZE, afterGettingFrame, this, onSourceClosure, this);
  585. return True;
  586. }
  587. void DummySink::setSprop(const u_int8_t * prop, unsigned size)
  588. {
  589. uint8_t * buf;
  590. uint8_t * buf_start;
  591. LOG("setSprop");
  592. buf = (uint8_t *) malloc(1004);
  593. buf_start = buf + 4;
  594. m_sAvPkt.data = buf;
  595. m_sAvPkt.data[0] = 0;
  596. m_sAvPkt.data[1] = 0;
  597. m_sAvPkt.data[2] = 0;
  598. m_sAvPkt.data[3] = 1;
  599. if (size > 1000)
  600. {
  601. LOG_ERROR("Data Chunk too large!! Increase Mem!");
  602. free(buf);
  603. m_sAvPkt.data = NULL;
  604. m_sAvPkt.size = 0;
  605. return;
  606. };
  607. memcpy(buf_start, prop, size);
  608. m_sAvPkt.size = size + 4;
  609. if (m_pSession->getWM() & MS_MODE_DECODE_FRAMES){
  610. int ret = avcodec_send_packet( m_pCodecContext, &m_sAvPkt );
  611. if( ret < 0 ){
  612. LOG_ERROR("Error Send Packet to Decoder!");
  613. };
  614. while ( ret >= 0 ) {
  615. ret = avcodec_receive_frame( m_pCodecContext, m_pFrame );
  616. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
  617. LOG_ERROR("EAGAIN/EOF while decoding frame");
  618. break;
  619. } else if (ret < 0) {
  620. LOG_ERROR("Error while decoding frame");
  621. break;
  622. };
  623. };
  624. };
  625. LOG("after setSprop");
  626. free(buf);
  627. m_sAvPkt.data = NULL;
  628. m_sAvPkt.size = 0;
  629. }
  630. #undef LOG_ERROR
  631. #undef MLOG
  632. #undef LOG
  633. #define LOG(X) m_pLog->Log("LIVE555_SRC", this, X)
  634. #define MLOG(X) ME->m_pLog->Log("LIVE555_SRC", ME, X)
  635. #ifdef DEBUG
  636. #define LOG_ERROR(X) \
  637. { \
  638. char _tBfrErrMSG2w34[1024]; \
  639. sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \
  640. m_pLog->Log("LIVE555_SRC", this, _LOG_ERROR, _tBfrErrMSG2w34); \
  641. }
  642. #else
  643. #define LOG_ERROR(X) m_pLog->Log("LIVE555_SRC", this, _LOG_ERROR, X);
  644. #endif
  645. videoLIVE555Source::videoLIVE555Source(void * opaque ): basicMediaSource(), /* MediaSink(*m_pUsageEnvironment),*/ basicThread(){
  646. m_bIsParamsSet = false;
  647. m_pOpaque = opaque;
  648. m_pScheduler = BasicTaskScheduler::createNew();
  649. m_pUsageEnvironment = BasicUsageEnvironment::createNew(*m_pScheduler);
  650. m_pLog = basicLogCollection::getInstance();
  651. // Default -> only decode frames
  652. m_eWM = MS_MODE_DECODE_FRAMES;
  653. m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1;
  654. initLibAV();
  655. }
  656. videoLIVE555Source::videoLIVE555Source(CSTR URI, void * opaque, MS_WORK_MODE mode): basicMediaSource(),/* MediaSink(*m_pUsageEnvironment),*/ basicThread(){
  657. m_pLog = basicLogCollection::getInstance();
  658. m_pOpaque = opaque;
  659. m_bIsParamsSet = true;
  660. m_eWM = mode;
  661. m_pScheduler = BasicTaskScheduler::createNew();
  662. m_pUsageEnvironment = BasicUsageEnvironment::createNew(*m_pScheduler);
  663. m_nOutWidth = m_nInWidth = m_nOutHeight = m_nInHeight = -1;
  664. if(!initLibAV() ) return;
  665. _open(URI);
  666. }
  667. videoLIVE555Source::~videoLIVE555Source(){
  668. _stop();
  669. // if ( m_pSink ) delete( m_pSink );
  670. }
  671. void videoLIVE555Source::m_fThreadProc(void)
  672. {
  673. LOG("Start Thread");
  674. _eventLoopWatchVariable = 0;
  675. m_bThreadStatus = TH_WORKING;
  676. pthread_setname_np(pthread_self(), "Live555 Source");
  677. // while ( m_bThreadStatus == TH_WORKING ) {
  678. m_pScheduler->doEventLoop(&_eventLoopWatchVariable);
  679. // streamTimerHandler( m_pRtspClient );
  680. // SLEEP(3);
  681. //};
  682. LOG("Rtsp event finished");
  683. // m_pUsageEnvironment->reclaim();
  684. // m_pUsageEnvironment = NULL;
  685. // delete m_pScheduler;
  686. // m_pScheduler = NULL;
  687. LOG("End Thread");
  688. }
  689. Boolean videoLIVE555Source::continuePlaying()
  690. {
  691. return False;
  692. }
  693. void videoLIVE555Source::continueAfterDESCRIBE(RTSPClient * rtspClient, int resultCode, char * resultString)
  694. {
  695. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  696. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  697. MLOG("After Describe EVT");
  698. do
  699. {
  700. UsageEnvironment & env = rtspClient->envir(); // alias
  701. StreamClientState & scs = MM->getStreamClientState(); // alias
  702. if (resultCode != 0)
  703. {
  704. MLOG("Failed to get a SDP description: ");
  705. MLOG(resultString);
  706. delete[] resultString;
  707. break;
  708. };
  709. char * const sdpDescription = resultString;
  710. MLOG("Got a SDP description:");
  711. MLOG(sdpDescription);
  712. // Create a media session object from this SDP description:
  713. scs.session = MediaSession::createNew(env, sdpDescription);
  714. delete[] sdpDescription; // because we don't need it anymore
  715. if (scs.session == NULL)
  716. {
  717. MLOG("Failed to create a MediaSession object from the SDP description:");
  718. MLOG(env.getResultMsg());
  719. break;
  720. }
  721. else if (! scs.session->hasSubsessions())
  722. {
  723. MLOG("This session has no media subsessions (i.e., no \"m=\" lines)");
  724. break;
  725. };
  726. ME->m_pMediaSession = scs.session;
  727. // Then, create and set up our data source objects for the session. We do this by iterating over the session's 'subsessions',
  728. // calling "MediaSubsession::initiate()", and then sending a RTSP "SETUP" command, on each one.
  729. // (Each 'subsession' will have its own data source.)
  730. scs.iter = new MediaSubsessionIterator(*scs.session);
  731. ME->setupNextSubsession(rtspClient);
  732. return;
  733. }
  734. while (0);
  735. // An unrecoverable error occurred with this stream.
  736. ME->shutdownStream(rtspClient);
  737. }
  738. void videoLIVE555Source::continueAfterSETUP(RTSPClient * rtspClient, int resultCode, char * resultString)
  739. {
  740. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  741. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  742. MLOG("After Setup EVT");
  743. do
  744. {
  745. UsageEnvironment & env = rtspClient->envir(); // alias
  746. StreamClientState & streamClientState = MM->getStreamClientState(); // alias
  747. if (resultCode != 0)
  748. {
  749. MLOG("Failed to set up the subsession:");
  750. MLOG(streamClientState.subsession->mediumName());
  751. MLOG(streamClientState.subsession->codecName());
  752. MLOG(resultString);
  753. break;
  754. };
  755. MLOG("Set up the subsession");
  756. MLOG(streamClientState.subsession->mediumName());
  757. MLOG(streamClientState.subsession->codecName());
  758. if (streamClientState.subsession->rtcpIsMuxed())
  759. {
  760. char tB[128];
  761. sprintf(tB, "client port %d", streamClientState.subsession->clientPortNum());
  762. MLOG(tB);
  763. }
  764. else
  765. {
  766. char tB[128];
  767. sprintf(tB, "client ports %d-%d", streamClientState.subsession->clientPortNum(), streamClientState.subsession->clientPortNum() + 1);
  768. MLOG(tB);
  769. };
  770. const char * sprop = streamClientState.subsession->fmtp_spropparametersets();
  771. const uint8_t * sps = NULL;
  772. unsigned spsSize = 0;
  773. const uint8_t * pps = NULL;
  774. unsigned ppsSize = 0;
  775. if (sprop != NULL)
  776. {
  777. unsigned numSPropRecords;
  778. SPropRecord * sPropRecords = parseSPropParameterSets(sprop, numSPropRecords);
  779. for (unsigned i = 0; i < numSPropRecords; ++i)
  780. {
  781. if (sPropRecords[i].sPropLength == 0)
  782. {
  783. continue; // bad data
  784. }
  785. u_int8_t nal_unit_type = (sPropRecords[i].sPropBytes[0]) & 0x1F;
  786. if (nal_unit_type == 7 /*SPS*/)
  787. {
  788. sps = sPropRecords[i].sPropBytes;
  789. spsSize = sPropRecords[i].sPropLength;
  790. }
  791. else if (nal_unit_type == 8 /*PPS*/)
  792. {
  793. pps = sPropRecords[i].sPropBytes;
  794. ppsSize = sPropRecords[i].sPropLength;
  795. }
  796. }
  797. }
  798. // Having successfully setup the subsession, create a data sink for it, and call "startPlaying()" on it.
  799. // (This will prepare the data sink to receive data; the actual flow of data from the client won't start happening until later,
  800. // after we've sent a RTSP "PLAY" command.)
  801. streamClientState.subsession->sink = DummySink::createNew(ME, env, *streamClientState.subsession, rtspClient->url(), ME->m_nInWidth, ME->m_nInHeight, ME->m_nOutWidth, ME->m_nOutHeight);
  802. // perhaps use your own custom "MediaSink" subclass instead
  803. if (streamClientState.subsession->sink == NULL)
  804. {
  805. MLOG("Failed to create a data sink for the subsession");
  806. MLOG(streamClientState.subsession->mediumName());
  807. MLOG(streamClientState.subsession->codecName());
  808. MLOG(env.getResultMsg());
  809. break;
  810. };
  811. MLOG("Created a data sink for the subsession");
  812. // MLOG( streamClientState.subsession->mediumName() );
  813. // MLOG( streamClientState.subsession->codecName() );
  814. streamClientState.subsession->miscPtr = rtspClient; // a hack to let subsession handler functions get the "RTSPClient" from the subsession
  815. if (sps != NULL)
  816. {
  817. ((DummySink *) streamClientState.subsession->sink)->setSprop(sps, spsSize);
  818. }
  819. if (pps != NULL)
  820. {
  821. ((DummySink *) streamClientState.subsession->sink)->setSprop(pps, ppsSize);
  822. }
  823. streamClientState.subsession->sink->startPlaying(*(streamClientState.subsession->readSource()), subsessionAfterPlaying, streamClientState.subsession);
  824. // Also set a handler to be called if a RTCP "BYE" arrives for this subsession:
  825. if (streamClientState.subsession->rtcpInstance() != NULL)
  826. {
  827. streamClientState.subsession->rtcpInstance()->setByeHandler(subsessionByeHandler, streamClientState.subsession);
  828. }
  829. }
  830. while (0);
  831. delete[] resultString;
  832. // Set up the next subsession, if any:
  833. ME->setupNextSubsession(rtspClient);
  834. MLOG("Done ContAfterSetup");
  835. }
  836. void videoLIVE555Source::continueAfterPLAY(RTSPClient * rtspClient, int resultCode, char * resultString)
  837. {
  838. Boolean success = False;
  839. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  840. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  841. MLOG("After Play EVT");
  842. do
  843. {
  844. UsageEnvironment & env = rtspClient->envir(); // alias
  845. StreamClientState & scs = ((CustomRTSPClient *) rtspClient)->getStreamClientState(); // alias
  846. if (resultCode != 0)
  847. {
  848. MLOG("Failed to start playing session: ");
  849. MLOG(resultString);
  850. break;
  851. };
  852. // Set a timer to be handled at the end of the stream's expected duration (if the stream does not already signal its end
  853. // using a RTCP "BYE"). This is optional. If, instead, you want to keep the stream active - e.g., so you can later
  854. // 'seek' back within it and do another RTSP "PLAY" - then you can omit this code.
  855. // (Alternatively, if you don't want to receive the entire stream, you could set this timer for some shorter value.)
  856. if (scs.duration > 0)
  857. {
  858. const unsigned delaySlop = 2; // number of seconds extra to delay, after the stream's expected duration. (This is optional.)
  859. scs.duration += delaySlop;
  860. unsigned uSecsToDelay = (unsigned) (scs.duration * 1000000);
  861. scs.streamTimerTask = env.taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc *) streamTimerHandler, rtspClient);
  862. }
  863. MLOG("Started playing session");
  864. // if (scs.duration > 0) {
  865. // env << " (for up to " << scs.duration << " seconds)";
  866. // }
  867. success = True;
  868. }
  869. while (0);
  870. // delete[] resultString;
  871. if (! success)
  872. {
  873. MLOG("Shutdown!");
  874. // An unrecoverable error occurred with this stream.
  875. ME->shutdownStream(rtspClient);
  876. };
  877. }
  878. // Other event handler functions:
  879. // called when a stream's subsession (e.g., audio or video substream) ends
  880. void videoLIVE555Source::subsessionAfterPlaying(void * clientData)
  881. {
  882. MediaSubsession * subsession = (MediaSubsession *) clientData;
  883. RTSPClient * rtspClient = (RTSPClient *) (subsession->miscPtr);
  884. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  885. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  886. // Begin by closing this subsession's stream:
  887. Medium::close(subsession->sink);
  888. subsession->sink = NULL;
  889. // Next, check whether *all* subsessions' streams have now been closed:
  890. MediaSession & session = subsession->parentSession();
  891. MediaSubsessionIterator iter(session);
  892. while ((subsession = iter.next()) != NULL)
  893. {
  894. if (subsession->sink != NULL)
  895. {
  896. return; // this subsession is still active
  897. }
  898. }
  899. // All subsessions' streams have now been closed, so shutdown the client:
  900. ME->shutdownStream(rtspClient);
  901. }
  902. void videoLIVE555Source::sessionAfterPlaying(void * clientData)
  903. {
  904. MediaSession * session = (MediaSession *) clientData;
  905. if (session->hasSubsessions())
  906. {
  907. MediaSubsessionIterator * itr = new MediaSubsessionIterator(*session);
  908. if (itr != NULL)
  909. {
  910. MediaSubsession * subsession = itr->next();
  911. while (subsession != NULL)
  912. {
  913. RTSPClient * rtspClient = (RTSPClient *) subsession->miscPtr;
  914. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  915. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  916. //UsageEnvironment & env = rtspClient->envir();
  917. MLOG("sessionAfterPlaying!");
  918. subsession = itr->next();
  919. };
  920. delete itr;
  921. };
  922. };
  923. }
  924. // called when a RTCP "BYE" is received for a subsession
  925. void videoLIVE555Source::subsessionByeHandler(void * clientData)
  926. { //, char const* reason ){
  927. MediaSubsession * subsession = (MediaSubsession *) clientData;
  928. RTSPClient * rtspClient = (RTSPClient *) subsession->miscPtr;
  929. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  930. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  931. //UsageEnvironment & env = rtspClient->envir(); // alias
  932. MLOG("Received RTCP \"BYE\" on subsession");
  933. MLOG(subsession->mediumName());
  934. MLOG(subsession->codecName());
  935. // Now act as if the subsession had closed:
  936. subsessionAfterPlaying(subsession);
  937. }
  938. void videoLIVE555Source::streamTimerHandler(void * clientData)
  939. {
  940. CustomRTSPClient * rtspClient = (CustomRTSPClient *) clientData;
  941. StreamClientState & scs = rtspClient->getStreamClientState(); // alias
  942. videoLIVE555Source * ME = (videoLIVE555Source *) rtspClient->getSession();
  943. scs.streamTimerTask = NULL;
  944. // Shut down the stream:
  945. ME->shutdownStream(rtspClient);
  946. }
  947. // The main streaming routine (for each "rtsp://" URL):
  948. void videoLIVE555Source::openURL(UsageEnvironment & env, const char * progName, const char * rtspURL)
  949. {
  950. int a = 0;
  951. if ( env.getErrno() ) a = 1;
  952. if ( progName ) a = 2;
  953. if ( rtspURL ) a = 3;
  954. a = a - 1;
  955. if ( a ) a = 0;
  956. LOG("openURL Called!");
  957. }
  958. // Used to iterate through each stream's 'subsessions', setting up each one:
  959. void videoLIVE555Source::setupNextSubsession(RTSPClient * rtspClient)
  960. {
  961. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  962. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  963. MLOG("Next Subsession EVT");
  964. UsageEnvironment & env = rtspClient->envir(); // alias
  965. StreamClientState & scs = MM->getStreamClientState(); // alias
  966. scs.subsession = scs.iter->next();
  967. if (scs.subsession != NULL)
  968. {
  969. if (! scs.subsession->initiate())
  970. {
  971. MLOG("Failed to initiate the subsession:");
  972. MLOG(scs.subsession->mediumName());
  973. MLOG(scs.subsession->codecName());
  974. MLOG(env.getResultMsg());
  975. setupNextSubsession(rtspClient); // give up on this subsession; go to the next one
  976. }
  977. else
  978. {
  979. MLOG("Initiated the subsession");
  980. MLOG(scs.subsession->mediumName());
  981. MLOG(scs.subsession->codecName());
  982. if (strstr(scs.subsession->mediumName(), "video") != NULL)
  983. {
  984. if (scs.subsession->rtcpIsMuxed())
  985. {
  986. char tB[64];
  987. sprintf(tB, "client port %d", scs.subsession->clientPortNum());
  988. MLOG(tB);
  989. }
  990. else
  991. {
  992. char tB[64];
  993. sprintf(tB, "client ports %d-%d", scs.subsession->clientPortNum(), scs.subsession->clientPortNum() + 1);
  994. MLOG(tB);
  995. };
  996. // Continue setting up this subsession, by sending a RTSP "SETUP" command:
  997. rtspClient->sendSetupCommand(*scs.subsession, continueAfterSETUP, False, REQUEST_STREAMING_OVER_TCP);
  998. }
  999. else
  1000. {
  1001. // Skip all Not Video subsession go to the next one
  1002. setupNextSubsession(rtspClient);
  1003. };
  1004. };
  1005. return;
  1006. };
  1007. // We've finished setting up all of the subsessions. Now, send a RTSP "PLAY" command to start the streaming:
  1008. if (scs.session->absStartTime() != NULL)
  1009. {
  1010. // Special case: The stream is indexed by 'absolute' time, so send an appropriate "PLAY" command:
  1011. rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY, scs.session->absStartTime(), scs.session->absEndTime());
  1012. }
  1013. else
  1014. {
  1015. scs.duration = scs.session->playEndTime() - scs.session->playStartTime();
  1016. rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY);
  1017. };
  1018. }
  1019. // Used to shut down and close a stream (including its "RTSPClient" object):
  1020. void videoLIVE555Source::shutdownStream(RTSPClient * rtspClient, int exitCode)
  1021. {
  1022. CustomRTSPClient * MM = (CustomRTSPClient *) rtspClient;
  1023. videoLIVE555Source * ME = (videoLIVE555Source *) MM->getSession();
  1024. if ( exitCode ) exitCode = exitCode;
  1025. #ifdef DEBUG
  1026. MLOG("Shutdown EVT");
  1027. #endif
  1028. StreamClientState & streamClientState = MM->getStreamClientState(); // alias
  1029. // if( resultCode != 0 ){
  1030. // MLOG( "Failed to set up the subsession:");
  1031. // MLOG( streamClientState.subsession->mediumName() );
  1032. // MLOG( streamClientState.subsession->codecName() );
  1033. // MLOG( resultString );
  1034. // break;
  1035. //};
  1036. //UsageEnvironment & env = rtspClient->envir();
  1037. MLOG("sendTearDown");
  1038. rtspClient->sendTeardownCommand(*streamClientState.session, NULL);
  1039. MLOG("Close Client");
  1040. Medium::close(rtspClient);
  1041. MLOG("SetLOOP");
  1042. _eventLoopWatchVariable = 1;
  1043. // MLOG( "Close Session" );
  1044. // Medium::close( streamClientState.session );
  1045. // MLOG( "Abort Thread" );
  1046. // waitThreadEnd( true );
  1047. // close RTSP client
  1048. // MLOG( "recalm Env" );
  1049. // env.reclaim();
  1050. // MLOG( "Delete Client" );
  1051. // delete MM;
  1052. // MLOG( "Delete Sink" );
  1053. // delete( (DummySink*) streamClientState.subsession->sink );
  1054. //*/
  1055. MLOG("Delete Scheduler");
  1056. m_pUsageEnvironment->reclaim();
  1057. m_pUsageEnvironment = NULL;
  1058. delete m_pScheduler;
  1059. m_pScheduler = NULL;
  1060. MLOG("All Done!");
  1061. m_eMediaStatus = MS_CLOSED;
  1062. }
  1063. // https://chowdera.com/2021/01/20210102084512591N.html
  1064. // https://github.com/drriguz/Kamera
  1065. bool videoLIVE555Source::_open(CSTR URI, bool ShowDeviceMenu, float framerate, int inputPin, int width, int height, int s_width, int s_height)
  1066. {
  1067. if ( ShowDeviceMenu ) ShowDeviceMenu = false;
  1068. if ( framerate ) framerate = framerate;
  1069. if ( inputPin ) inputPin = inputPin;
  1070. if (URI == NULL)
  1071. {
  1072. LOG_ERROR("Trying to open MediaSource without MRL!");
  1073. return false;
  1074. };
  1075. // if( !m_bIsParamsSet ) {
  1076. // LOG_ERROR("Trying to open MediaSource without all needded parameters!");
  1077. // return false;
  1078. // };
  1079. m_nInHeight = height;
  1080. m_nInWidth = width;
  1081. m_nOutHeight = s_height;
  1082. m_nOutWidth = s_width;
  1083. m_pRtspClient = CustomRTSPClient::createNew(this, *m_pUsageEnvironment, URI, RTSP_CLIENT_VERBOSITY_LEVEL, "ARGUS CLIENT");
  1084. if (m_pRtspClient == NULL)
  1085. {
  1086. char tB[256];
  1087. sprintf(tB, "Failed to create a RTSP client for URL \"%s\":%s", URI, m_pUsageEnvironment->getResultMsg());
  1088. LOG_ERROR(tB);
  1089. return false;
  1090. };
  1091. m_pRtspClient->sendDescribeCommand(continueAfterDESCRIBE);
  1092. return init();
  1093. }
  1094. void videoLIVE555Source::consumeFrame(cv::Mat * frm)
  1095. {
  1096. if (m_pMediaDestination == NULL)
  1097. {
  1098. return;
  1099. }
  1100. if (! m_pMediaDestination->pushFrame(*frm, m_pOpaque))
  1101. {
  1102. m_pMediaDestination = NULL;
  1103. LOG_ERROR("Error Consume Frame by Media Destination!");
  1104. };
  1105. }
  1106. bool videoLIVE555Source::_close(void)
  1107. {
  1108. LOG("CLOSE!");
  1109. return _stop();
  1110. }
  1111. bool videoLIVE555Source::_stop(void)
  1112. {
  1113. LOG("STOP!");
  1114. shutdownStream(m_pRtspClient);
  1115. return true;
  1116. }
  1117. bool videoLIVE555Source::isFinished(void)
  1118. {
  1119. return (m_eMediaStatus == MS_CLOSED);
  1120. }
  1121. MediaStateStatus videoLIVE555Source::getStatus(void)
  1122. {
  1123. return m_eMediaStatus;
  1124. }
  1125. bool videoLIVE555Source::setSize(int Width, int Height)
  1126. {
  1127. if( Width || Height ) return false;
  1128. return false;
  1129. }
  1130. bool videoLIVE555Source::setProportionalByWidth(int Width)
  1131. {
  1132. if( !Width ) return false;
  1133. return false;
  1134. }
  1135. bool videoLIVE555Source::setProportionalByHeight(int Height)
  1136. {
  1137. if( !Height ) return false;
  1138. return false;
  1139. }
  1140. bool videoLIVE555Source::setFPS(int A )
  1141. {
  1142. if( !A ) return false;
  1143. return false;
  1144. }
  1145. bool videoLIVE555Source::setName(CSTR Name)
  1146. {
  1147. if( !Name ) return false;
  1148. return false;
  1149. }
  1150. bool videoLIVE555Source::setFrameAspectRatio(FrameAspectRatio AspectRatio)
  1151. {
  1152. if( AspectRatio ) AspectRatio = AspectRatio;
  1153. return false;
  1154. }
  1155. #undef MLOG
  1156. #undef LOG
  1157. #undef LOG_ERROR
  1158. #undef FF_DISABLE_DEPRECATION_WARNINGS
  1159. #endif //!LRF_PROXY_ONLY