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.

1285 lines
41 KiB

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