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.

1292 lines
41 KiB

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