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.

236 lines
6.6 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #ifndef LRF_PROXY_ONLY
  2. #include "streamLiveEncoder.h"
  3. extern "C"
  4. {
  5. #include <libavutil/opt.h>
  6. }
  7. #define LOG(X) m_pLog->Log("LIVE_ENC", this, X)
  8. #define LOG_ERROR(X) m_pLog->Log("LIVE_ENC", this, _LOG_ERROR, X)
  9. streamLiveEncoder::streamLiveEncoder(std::shared_ptr<mtx::MediaPath> path, int fps, int bitrateKbps) :
  10. m_pLog(basicLogCollection::getInstance()), m_pPath(std::move(path)), m_oFeeder(m_pPath.get()), m_nFps(fps > 0 ? fps : 15), m_nBitrateKbps(bitrateKbps > 0 ? bitrateKbps : 2000),
  11. m_bHavePending(false), m_bRun(true), m_nNextFrameUs(0), m_pCtx(NULL), m_pFrame(NULL), m_pPacket(NULL), m_pSws(NULL), m_nWidth(0), m_nHeight(0), m_nFrameIndex(0), m_nLastReaders(0),
  12. m_bOpenFailed(false)
  13. {
  14. m_thread = std::thread(&streamLiveEncoder::run, this);
  15. }
  16. streamLiveEncoder::~streamLiveEncoder()
  17. {
  18. {
  19. std::lock_guard<std::mutex> lock(m_mutex);
  20. m_bRun = false;
  21. }
  22. m_cond.notify_all();
  23. if (m_thread.joinable())
  24. {
  25. m_thread.join();
  26. }
  27. m_oFeeder.setParent(nullptr); // the path is not ready any more
  28. closeEncoder();
  29. }
  30. void streamLiveEncoder::push(const cv::Mat & bgr)
  31. {
  32. if (bgr.empty() || m_bOpenFailed)
  33. {
  34. return;
  35. }
  36. // Nobody watches, nothing is recorded: no CPU for encoding
  37. if (m_pPath->readerCount() == 0 && ! m_pPath->recording())
  38. {
  39. return;
  40. }
  41. int64_t tNow = mtx::nowUs();
  42. std::lock_guard<std::mutex> lock(m_mutex);
  43. if (tNow < m_nNextFrameUs)
  44. {
  45. return; // above the frame rate of the live stream
  46. }
  47. m_nNextFrameUs = (m_nNextFrameUs == 0 || tNow - m_nNextFrameUs > 1000000) ? tNow + 1000000 / m_nFps : m_nNextFrameUs + 1000000 / m_nFps;
  48. bgr.copyTo(m_mPending); // replaces a frame the encoder did not take yet (it is late: drop)
  49. m_bHavePending = true;
  50. m_cond.notify_one();
  51. }
  52. void streamLiveEncoder::run()
  53. {
  54. pthread_setname_np(pthread_self(), "LiveEncoder");
  55. cv::Mat tFrame;
  56. while (true)
  57. {
  58. {
  59. std::unique_lock<std::mutex> lock(m_mutex);
  60. m_cond.wait(lock, [this] { return ! m_bRun || m_bHavePending; });
  61. if (! m_bRun)
  62. {
  63. break;
  64. }
  65. cv::swap(tFrame, m_mPending);
  66. m_bHavePending = false;
  67. }
  68. size_t tReaders = m_pPath->readerCount();
  69. bool tIdr = tReaders > m_nLastReaders; // a new viewer: start it now, not at the next GOP
  70. m_nLastReaders = tReaders;
  71. if (m_pCtx != NULL && (tFrame.cols != m_nWidth || tFrame.rows != m_nHeight))
  72. {
  73. closeEncoder(); // the frame size changed (module settings)
  74. }
  75. if (m_pCtx == NULL)
  76. {
  77. if (! openEncoder(tFrame.cols, tFrame.rows))
  78. {
  79. m_bOpenFailed = true;
  80. break;
  81. }
  82. tIdr = true;
  83. }
  84. if (! encode(tFrame, tIdr))
  85. {
  86. closeEncoder(); // opened again with the next frame
  87. }
  88. }
  89. }
  90. bool streamLiveEncoder::openEncoder(int width, int height)
  91. {
  92. const AVCodec * tCodec = avcodec_find_encoder_by_name("libx264");
  93. if (tCodec == NULL)
  94. {
  95. tCodec = avcodec_find_encoder(AV_CODEC_ID_H264);
  96. }
  97. if (tCodec == NULL)
  98. {
  99. LOG_ERROR("No H264 encoder in libavcodec: live view of the processed frames is not possible");
  100. return false;
  101. }
  102. m_pCtx = avcodec_alloc_context3(tCodec);
  103. if (m_pCtx == NULL)
  104. {
  105. return false;
  106. }
  107. m_nWidth = width & ~1; // 4:2:0 needs even sizes
  108. m_nHeight = height & ~1;
  109. m_pCtx->width = m_nWidth;
  110. m_pCtx->height = m_nHeight;
  111. m_pCtx->pix_fmt = AV_PIX_FMT_YUV420P;
  112. m_pCtx->time_base = AVRational {1, 90000};
  113. m_pCtx->framerate = AVRational {m_nFps, 1};
  114. m_pCtx->gop_size = m_nFps * 2; // a new viewer waits at most 2 s (and gets one at once, see run())
  115. m_pCtx->max_b_frames = 0; // WebRTC / fMP4 writer: dts = pts
  116. m_pCtx->bit_rate = (int64_t) m_nBitrateKbps * 1000;
  117. m_pCtx->rc_max_rate = m_pCtx->bit_rate;
  118. m_pCtx->rc_buffer_size = (int) m_pCtx->bit_rate; // 1 s
  119. m_pCtx->thread_count = 2;
  120. m_pCtx->profile = FF_PROFILE_H264_CONSTRAINED_BASELINE;
  121. if (strcmp(tCodec->name, "libx264") == 0)
  122. {
  123. av_opt_set(m_pCtx->priv_data, "preset", "veryfast", 0);
  124. av_opt_set(m_pCtx->priv_data, "tune", "zerolatency", 0);
  125. av_opt_set(m_pCtx->priv_data, "profile", "baseline", 0);
  126. av_opt_set(m_pCtx->priv_data, "x264-params", "repeat-headers=1", 0); // SPS / PPS with every IDR
  127. av_opt_set(m_pCtx->priv_data, "forced-idr", "1", 0); // a forced key frame is an IDR
  128. }
  129. int tRet = avcodec_open2(m_pCtx, tCodec, NULL);
  130. if (tRet < 0)
  131. {
  132. char tE[128], tB[256];
  133. av_strerror(tRet, tE, sizeof(tE));
  134. snprintf(tB, sizeof(tB), "Cannot open the H264 encoder %s: %s", tCodec->name, tE);
  135. LOG_ERROR(tB);
  136. avcodec_free_context(&m_pCtx);
  137. return false;
  138. }
  139. m_pFrame = av_frame_alloc();
  140. m_pPacket = av_packet_alloc();
  141. m_pSws = sws_getContext(width, height, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, AV_PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL);
  142. if (m_pFrame == NULL || m_pPacket == NULL || m_pSws == NULL)
  143. {
  144. LOG_ERROR("Live encoder: allocation failed");
  145. closeEncoder();
  146. return false;
  147. }
  148. m_pFrame->format = AV_PIX_FMT_YUV420P;
  149. m_pFrame->width = m_nWidth;
  150. m_pFrame->height = m_nHeight;
  151. if (av_frame_get_buffer(m_pFrame, 32) < 0)
  152. {
  153. closeEncoder();
  154. return false;
  155. }
  156. if (m_pCtx->extradata != NULL && m_pCtx->extradata_size > 0)
  157. {
  158. m_oFeeder.setExtradata(m_pCtx->extradata, m_pCtx->extradata_size);
  159. }
  160. char tB[200];
  161. snprintf(tB, sizeof(tB), "H264 encoder %s opened: %dx%d, %d fps, %d kbit/s", tCodec->name, m_nWidth, m_nHeight, m_nFps, m_nBitrateKbps);
  162. LOG(tB);
  163. return true;
  164. }
  165. void streamLiveEncoder::closeEncoder()
  166. {
  167. if (m_pSws != NULL)
  168. {
  169. sws_freeContext(m_pSws);
  170. m_pSws = NULL;
  171. }
  172. av_frame_free(&m_pFrame);
  173. av_packet_free(&m_pPacket);
  174. avcodec_free_context(&m_pCtx);
  175. m_nWidth = 0;
  176. m_nHeight = 0;
  177. }
  178. bool streamLiveEncoder::encode(const cv::Mat & bgr, bool forceIdr)
  179. {
  180. if (av_frame_make_writable(m_pFrame) < 0)
  181. {
  182. return false;
  183. }
  184. const uint8_t * tSrc[1] = {bgr.data};
  185. int tStep[1] = {(int) bgr.step[0]};
  186. sws_scale(m_pSws, tSrc, tStep, 0, bgr.rows, m_pFrame->data, m_pFrame->linesize);
  187. int64_t tNowUs = mtx::nowUs();
  188. m_pFrame->pts = tNowUs * 9 / 100; // 90 kHz wall clock: the real frame timing
  189. m_pFrame->pict_type = forceIdr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE;
  190. int tRet = avcodec_send_frame(m_pCtx, m_pFrame);
  191. if (tRet < 0)
  192. {
  193. LOG_ERROR("Live encoder: send frame failed");
  194. return false;
  195. }
  196. while (true)
  197. {
  198. tRet = avcodec_receive_packet(m_pCtx, m_pPacket);
  199. if (tRet == AVERROR(EAGAIN) || tRet == AVERROR_EOF)
  200. {
  201. break;
  202. }
  203. if (tRet < 0)
  204. {
  205. LOG_ERROR("Live encoder: receive packet failed");
  206. return false;
  207. }
  208. int64_t tPtsUs = (m_pPacket->pts != AV_NOPTS_VALUE) ? m_pPacket->pts * 100 / 9 : tNowUs;
  209. if (m_oFeeder.avccLengthSize() > 0)
  210. {
  211. m_oFeeder.pushAvcc(m_pPacket->data, m_pPacket->size, m_oFeeder.avccLengthSize(), tPtsUs);
  212. }
  213. else
  214. {
  215. m_oFeeder.pushAnnexB(m_pPacket->data, m_pPacket->size, tPtsUs);
  216. }
  217. av_packet_unref(m_pPacket);
  218. }
  219. m_nFrameIndex++;
  220. return true;
  221. }
  222. #undef LOG
  223. #undef LOG_ERROR
  224. #endif // !LRF_PROXY_ONLY