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.

782 lines
23 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "videoAVLIBDestination.h"
  2. #include <libavutil/avassert.h>
  3. #include <libavutil/channel_layout.h>
  4. #include <libavutil/mathematics.h>
  5. #include <libavutil/opt.h>
  6. // #include <libavutil/timestamp.h>
  7. #include <libswresample/swresample.h>
  8. #include <libswscale/swscale.h>
  9. #define LOG(X) m_pLog->Log("LibAV_DST", this, X)
  10. #define LOG_ERROR(X) m_pLog->Log("LibAV_DST", this, _LOG_ERROR, X)
  11. // https://gist.github.com/yohhoy/52b31522dbb751e5296e
  12. // https://gist.github.com/sdumetz/961585ea70f82e4fb27aadf66b2c9cb2
  13. // https://gist.github.com/victusfate/9420226
  14. videoAVLIBDestination::videoAVLIBDestination()
  15. {
  16. m_nPTS = 0;
  17. m_nDTS = 0;
  18. m_pLog = basicLogCollection::getInstance();
  19. img_convert_ctx = NULL;
  20. m_nWidth = VIDEO_OUTPUT_WIDTH;
  21. m_nHeight = VIDEO_OUTPUT_HEIGHT;
  22. LOG("Constructor Done!");
  23. m_bRecordIsStarted = false;
  24. }
  25. videoAVLIBDestination::~videoAVLIBDestination() {}
  26. /*
  27. ctx->bit_rate = 500*1000;
  28. ctx->bit_rate_tolerance = 0;
  29. ctx->rc_max_rate = 0;
  30. ctx->rc_buffer_size = 0;
  31. ctx->gop_size = 40;
  32. ctx->max_b_frames = 3;
  33. ctx->b_frame_strategy = 1;
  34. ctx->coder_type = 1;
  35. ctx->me_cmp = 1;
  36. ctx->me_range = 16;
  37. ctx->qmin = 10;
  38. ctx->qmax = 51;
  39. ctx->scenechange_threshold = 40;
  40. ctx->flags |= CODEC_FLAG_LOOP_FILTER;
  41. ctx->me_method = ME_HEX;
  42. ctx->me_subpel_quality = 5;
  43. ctx->i_quant_factor = 0.71;
  44. ctx->qcompress = 0.6;
  45. ctx->max_qdiff = 4;
  46. ctx->directpred = 1;
  47. ctx->flags2 |= CODEC_FLAG2_FASTPSKIP;
  48. c->profile = FF_PROFILE_H264_BASELINE;
  49. Don't forget to use x264 private options. You can always set a profile:
  50. av_dict_set(&This->opts, "vprofile", "baseline", 0)
  51. Or set the lowest encoding latency:
  52. av_dict_set(&This->opts, "tune", "zerolatency", 0);
  53. Or select a preset:
  54. av_dict_set(&This->opts, "preset","ultrafast",0);
  55. Before opening a codec
  56. avcodec_open2(This->context, This->codec, &This->opts)
  57. shareedit
  58. // libx264-medium.ffpreset preset
  59. ctx->coder_type = 1; // coder = 1
  60. ctx->flags|=CODEC_FLAG_LOOP_FILTER; // flags=+loop
  61. ctx->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1
  62. ctx->partitions|=X264_PART_I8X8+X264_PART_I4X4+X264_PART_P8X8+X264_PART_B8X8; // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
  63. ctx->me_method=ME_HEX; // me_method=hex
  64. ctx->me_subpel_quality = 7; // subq=7
  65. ctx->me_range = 16; // me_range=16
  66. ctx->gop_size = 250; // g=250
  67. ctx->keyint_min = 25; // keyint_min=25
  68. ctx->scenechange_threshold = 40; // sc_threshold=40
  69. ctx->i_quant_factor = 0.71; // i_qfactor=0.71
  70. ctx->b_frame_strategy = 1; // b_strategy=1
  71. ctx->qcompress = 0.6; // qcomp=0.6
  72. ctx->qmin = 10; // qmin=10
  73. ctx->qmax = 51; // qmax=51
  74. ctx->max_qdiff = 4; // qdiff=4
  75. ctx->max_b_frames = 3; // bf=3
  76. ctx->refs = 3; // refs=3
  77. ctx->directpred = 1; // directpred=1
  78. ctx->trellis = 1; // trellis=1
  79. ctx->flags2|=CODEC_FLAG2_BPYRAMID+CODEC_FLAG2_MIXED_REFS+CODEC_FLAG2_WPRED+CODEC_FLAG2_8X8DCT+CODEC_FLAG2_FASTPSKIP; // flags2=+bpyramid+mixed_refs+wpred+dct8x8+fastpskip
  80. ctx->weighted_p_pred = 2; // wpredp=2
  81. // libx264-main.ffpreset preset
  82. ctx->flags2|=CODEC_FLAG2_8X8DCT;c->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
  83. */
  84. void videoAVLIBDestination::startRecord(CSTR fileName)
  85. {
  86. if (init())
  87. {
  88. m_bRecordIsStarted = open(fileName);
  89. };
  90. }
  91. int videoAVLIBDestination::stopRecord(void)
  92. {
  93. if (m_bRecordIsStarted)
  94. {
  95. close();
  96. m_bRecordIsStarted = false;
  97. };
  98. return 0;
  99. }
  100. /*
  101. formatParams.device = "/dev/video0";
  102. formatParams.channel = 0;
  103. formatParams.standard = "pal";
  104. formatParams.width = 324;
  105. formatParams.height = 248;
  106. formatParams.time_base= (AVRational){1,10};
  107. pInputFormat = av_find_input_format("video4linux");
  108. av_dict_set(&options, "b", "2.5M", 0);
  109. */
  110. /*
  111. typedef struct EncodeCallback {
  112. int (*pull_frame)(void *priv, AVFrame *frame);
  113. int (*push_packet)(void *priv, AVPacket *packet);
  114. void *priv_data_push, *priv_data_pull;
  115. } EncodeCallback;
  116. int encode_loop( AVCodecContext *avctx, EncodeCallback *cb ){
  117. AVPacket *pkt = av_packet_alloc();
  118. AVFrame *frame = av_frame_alloc();
  119. int ret;
  120. while ((ret = avcodec_encode_need_data(avctx)) > 0) {
  121. ret = cb->pull_frame(cb->priv_data_pull, frame);
  122. if (ret < 0) goto end;
  123. ret = avcodec_encode_push(avctx, frame);
  124. if (ret < 0) goto end;
  125. };
  126. while ((ret = avcodec_encode_have_data(avctx)) > 0) {
  127. ret = avcodec_encode_pull(avctx, pkt);
  128. if (ret < 0) goto end;
  129. ret = cb->push_packet(cb->priv_data_push, pkt);
  130. if (ret < 0) goto end;
  131. };
  132. end:
  133. av_frame_free(&frame);
  134. av_packet_free(&pkt);
  135. return ret;
  136. };
  137. */
  138. /*
  139. // Decode
  140. int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt);
  141. int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame);
  142. // Encode
  143. int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame);
  144. int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt);
  145. int encode(AVCodecContext *avctx, AVPacket *pkt, int *got_packet, AVFrame *frame){
  146. int ret;
  147. *got_packet = 0;
  148. ret = avcodec_send_frame(avctx, frame);
  149. if (ret < 0) return ret;
  150. ret = avcodec_receive_packet(avctx, pkt);
  151. if (!ret) *got_packet = 1;
  152. if (ret == AVERROR(EAGAIN)) return 0;
  153. return ret;
  154. };
  155. // return 0 on success, negative on error
  156. typedef int (*process_packet_cb)(void *ctx, AVPacket *pkt);
  157. int encode(AVCodecContext *avctx, AVFrame *frame, process_packet_cb cb, void *priv){
  158. AVPacket *pkt = av_packet_alloc();
  159. int ret;
  160. ret = avcodec_send_frame(avctx, frame);
  161. if (ret < 0) goto out;
  162. while (!ret) {
  163. ret = avcodec_receive_packet(avctx, pkt);
  164. if (!ret) ret = cb(priv, pkt);
  165. };
  166. out: av_packet_free(&pkt);
  167. if (ret == AVERROR(EAGAIN)) return 0;
  168. return ret;
  169. };
  170. */
  171. /*
  172. AVFrame.format is not set
  173. AVFrame.width or height is not set
  174. AVFrame.format is not set
  175. AVFrame.width or height is not set
  176. AVFrame.format is not set
  177. */
  178. bool videoAVLIBDestination::init(void)
  179. {
  180. initLibAV();
  181. m_pVideoState = (VideoState *) av_mallocz(sizeof(VideoState));
  182. LOG("INIT!!!");
  183. if (m_pVideoState == NULL)
  184. {
  185. LOG_ERROR("VideoState Memory Allocation Error");
  186. return false;
  187. };
  188. m_pVideoState->m_bStatus = MS_UNDEFINED;
  189. m_pVideoState->m_pVideoCodec = avcodec_find_encoder(VIDEO_OUTPUT_CODEC);
  190. if (m_pVideoState->m_pVideoCodec == NULL)
  191. {
  192. LOG_ERROR("VideoCodec Not Found!");
  193. return false;
  194. }
  195. else
  196. {
  197. LOG("Video Codec Found");
  198. };
  199. m_pVideoState->m_pCodecCtx = avcodec_alloc_context3(m_pVideoState->m_pVideoCodec);
  200. if (m_pVideoState->m_pCodecCtx == NULL)
  201. {
  202. LOG_ERROR("VideoCodec Context Memory Allocation Error");
  203. return false;
  204. }
  205. else
  206. {
  207. LOG("Codec Context3 Allocated");
  208. };
  209. /*
  210. m_pVideoState->m_pFormatCtx = avformat_alloc_context();
  211. if (m_pVideoState->m_pFormatCtx == NULL){
  212. LOG_ERROR("VideoFormat Context Memory Allocation Error");
  213. return false;
  214. } else {
  215. LOG("Format Context Allocated");
  216. };
  217. //avformat_alloc_output_context2(&flv_format_context, NULL, NULL, output_filename.c_str());
  218. m_pVideoState->m_pFormatCtx->oformat = av_guess_format( VIDEO_OUTPUT_CONTAINER, NULL, NULL);
  219. if (m_pVideoState->m_pFormatCtx->oformat == NULL){
  220. LOG_ERROR("VideoFormat Format Not Guessed!");
  221. return false;
  222. } else {
  223. LOG("Video Container Format Guessed");
  224. };
  225. //av_dict_set(&m_pVideoState->m_pFormatCtx->metadata, "Author", "Gagua", 0);
  226. //m_pVideoState->m_pFormatCtx->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  227. */
  228. m_pVideoState->m_pFormatCtx = NULL;
  229. m_pVideoState->m_pFormatOpts = NULL;
  230. LOG("NULL !!");
  231. int ret = avformat_alloc_output_context2(&m_pVideoState->m_pFormatCtx, NULL, NULL, "test.flv");
  232. if (ret < 0)
  233. {
  234. LOG_ERROR("VideoFormat Context Memory Allocation Error");
  235. return false;
  236. };
  237. m_pVideoState->m_pFormatCtx->oformat = av_guess_format(VIDEO_OUTPUT_CONTAINER, NULL, NULL);
  238. if (m_pVideoState->m_pFormatCtx->oformat == NULL)
  239. {
  240. LOG_ERROR("VideoFormat Format Not Guessed!");
  241. return false;
  242. }
  243. else
  244. {
  245. LOG("Video Container Format Guessed");
  246. };
  247. /* */
  248. AVDictionary * fmt_opts = NULL;
  249. m_pVideoState->m_pVideoStr = avformat_new_stream(m_pVideoState->m_pFormatCtx, m_pVideoState->m_pVideoCodec);
  250. if (m_pVideoState->m_pVideoStr == NULL)
  251. {
  252. LOG_ERROR("VideoStream Not Created!");
  253. }
  254. else
  255. {
  256. LOG("VideoStream is Created");
  257. };
  258. // m_pVideoState->m_pVideoStr->codec = m_pVideoState->m_pCodecCtx; //---->see next page
  259. /*
  260. // on versions 55+ (win and mac) we use pEncodedFormat = AV_PIX_FMT_YUV420P and need
  261. // to set color_range and FF_COMPLIANCE_EXPERIMENTAL
  262. // TODO!!! CHANGE
  263. #if (LIBAVCODEC_VERSION_INT >= ((55<<16)+(0<<8)+0))
  264. m_pVideoState->m_pCodecCtx->color_range = AVCOL_RANGE_JPEG;
  265. // ffmpeg way: to define PIX_FMT_YUVJ420P as deprecated, but
  266. // allow using of PIX_FMT_YUV420P + AVCOL_RANGE_JPEG only with
  267. // experimental flag. Well, ok.
  268. m_pVideoState->m_pCodecCtx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
  269. #endif
  270. m_pVideoState->m_pCodecCtx->bit_rate = 400000;
  271. m_pVideoState->m_pCodecCtx->width = m_nWidth;// 352;// resolution must be a multiple of two
  272. m_pVideoState->m_pCodecCtx->height = m_nHeight;//288;
  273. m_pVideoState->m_pCodecCtx->time_base.num = 1; // frames per second
  274. m_pVideoState->m_pCodecCtx->time_base.den = 25;
  275. m_pVideoState->m_pCodecCtx->gop_size = 10; // emit one intra frame every ten frames
  276. m_pVideoState->m_pCodecCtx->max_b_frames = 1;
  277. m_pVideoState->m_pCodecCtx->pix_fmt = MJPEG_PIX_FMT;// PIX_FMT_YUV420P;
  278. m_pVideoState->m_pCodecCtx->qmin = 1;
  279. m_pVideoState->m_pCodecCtx->qmax = 1;
  280. m_pVideoState->m_pCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
  281. // 14.04+ ,win, mac
  282. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  283. //m_pVideoState->m_pCodecCtx->time_base = (AVRational){ 1, 1000 };
  284. m_pVideoState->m_pCodecCtx->codec_id = AV_CODEC_ID_MJPEG;
  285. m_pVideoState->m_pCodecCtx->codec_tag = av_codec_get_tag( m_pVideoState->m_pFormatCtx->oformat->codec_tag, AV_CODEC_ID_MJPEG );
  286. #endif
  287. */
  288. m_pVideoState->m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  289. m_pVideoState->m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  290. m_pVideoState->m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  291. m_pVideoState->m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  292. // m_pVideoState->m_pCodecCtx->bit_rate_tolerance = 1;
  293. // m_pVideoState->m_pCodecCtx->global_quality = 100;
  294. // m_pVideoState->m_pCodecCtx->compression_level = 2;
  295. m_pVideoState->m_pCodecCtx->width = m_nWidth;
  296. m_pVideoState->m_pCodecCtx->height = m_nHeight;
  297. m_pVideoState->m_pCodecCtx->time_base.num = 1;
  298. m_pVideoState->m_pCodecCtx->time_base.den = VIDEO_OUTPUT_FPS;
  299. m_pVideoState->m_pCodecCtx->gop_size = VIDEO_OUTPUT_GOP; // emit one intra frame every ten frames
  300. // m_pVideoState->m_pCodecCtx->qmin = 15;
  301. // m_pVideoState->m_pCodecCtx->qmax = 30;
  302. m_pVideoState->m_pCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;
  303. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  304. m_pVideoState->m_pCodecCtx->codec_tag = av_codec_get_tag(m_pVideoState->m_pFormatCtx->oformat->codec_tag, VIDEO_OUTPUT_CODEC);
  305. #endif
  306. if (m_pVideoState->m_pCodecCtx->codec_id == AV_CODEC_ID_H264)
  307. {
  308. // Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  309. // Set format's privater options, to be passed to avformat_write_header()
  310. LOG("Begin Options!");
  311. int RetVal = 0;
  312. // RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "movflags", "faststart", 0);
  313. // if( RetVal < 0 ){
  314. // LOG_ERROR( "av_dict_set movflags!");
  315. // };
  316. // default brand is "isom", which fails on some devices
  317. RetVal = av_dict_set(&m_pVideoState->m_pFormatOpts, "brand", "mp42", 0);
  318. if (RetVal < 0)
  319. {
  320. LOG_ERROR("av_dict_set brand!");
  321. };
  322. // m_pVideoState->m_pCodecCtx->max_b_frames = 1;
  323. m_pVideoState->m_pCodecCtx->level = 31;
  324. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "crf", "12", 0);
  325. if (RetVal < 0)
  326. {
  327. LOG_ERROR("av_opt_set crf");
  328. };
  329. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "profile", "main", 0);
  330. if (RetVal < 0)
  331. {
  332. LOG_ERROR("av_opt_set profile");
  333. };
  334. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "preset", "slow", 0);
  335. if (RetVal < 0)
  336. {
  337. LOG_ERROR("av_opt_set preset");
  338. };
  339. // Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  340. // Because Quicktime (ie. iOS) doesn't support this option
  341. RetVal = av_opt_set(m_pVideoState->m_pCodecCtx->priv_data, "b-pyramid", "0", 0);
  342. if (RetVal < 0)
  343. {
  344. LOG_ERROR("av_opt_set b-pyramid");
  345. };
  346. LOG("End Options!");
  347. };
  348. // See up one page ->
  349. avcodec_get_context_defaults3(m_pVideoState->m_pVideoStr->codec, m_pVideoState->m_pVideoCodec);
  350. const AVRational dst_fps = {VIDEO_OUTPUT_FPS, 1};
  351. m_pVideoState->m_pVideoStr->codec->width = m_nWidth;
  352. m_pVideoState->m_pVideoStr->codec->height = m_nHeight;
  353. m_pVideoState->m_pVideoStr->codec->pix_fmt = m_pVideoState->m_pVideoCodec->pix_fmts[0];
  354. m_pVideoState->m_pVideoStr->codec->time_base = m_pVideoState->m_pVideoStr->time_base = av_inv_q(dst_fps);
  355. m_pVideoState->m_pVideoStr->r_frame_rate = m_pVideoState->m_pVideoStr->avg_frame_rate = dst_fps;
  356. if (m_pVideoState->m_pFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
  357. {
  358. m_pVideoState->m_pVideoStr->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  359. }
  360. //---->>
  361. if (avcodec_is_open(m_pVideoState->m_pCodecCtx) == 0)
  362. {
  363. LOG("output codec context is closed, opening");
  364. int ret = avcodec_open2(m_pVideoState->m_pCodecCtx, m_pVideoState->m_pVideoCodec, NULL);
  365. if (ret < 0)
  366. {
  367. LOG_ERROR("Error opening2 encoder");
  368. char buffer[200];
  369. sprintf(buffer, "Error code: %i", ret);
  370. LOG_ERROR(buffer);
  371. return false;
  372. }
  373. }
  374. else
  375. {
  376. LOG("output codec context is opened");
  377. };
  378. m_pVideoState->m_iVideoStreamID = -1;
  379. #ifndef _NOAUDIO_
  380. m_pVideoState->m_iAudioStreamID = -1;
  381. #endif
  382. m_nOut_bufferSize = 1048576; // 1Mb
  383. m_pOut_buffer = (uint8_t *) av_malloc(m_nOut_bufferSize);
  384. if (m_pOut_buffer == NULL)
  385. {
  386. LOG_ERROR("Error Memory Allocation Output Buffer.");
  387. return false;
  388. };
  389. m_pVideoState->m_bStatus = MS_ALOCATED; // All seems to be good -> allocating mem
  390. m_pVideoState->m_bStatus = MS_INIT;
  391. LOG("Init Done.");
  392. return true;
  393. }
  394. // https://www.ffmpeg.org/doxygen/0.6/output-example_8c-source.html
  395. // https://github.com/ugcs/vstreamer/blob/master/src/ffmpeg_save_mjpeg.cpp
  396. bool videoAVLIBDestination::open(CSTR URI)
  397. {
  398. if (m_pVideoState != NULL)
  399. {
  400. if (m_pVideoState->m_bStatus < MS_OPENING)
  401. {
  402. if (m_pVideoState->m_bStatus == MS_INIT)
  403. {
  404. m_pVideoState->m_bStatus = MS_OPENING;
  405. strncpy(m_pVideoState->m_pFileName, URI, MAX_PATH_LEN);
  406. m_pVideoState->m_pFileName[MAX_PATH_LEN - 1] = (char) 0;
  407. if (avio_open(&m_pVideoState->m_pFormatCtx->pb, m_pVideoState->m_pFileName, AVIO_FLAG_WRITE) < 0)
  408. {
  409. LOG_ERROR("Could not open output file.");
  410. return false;
  411. };
  412. if (avformat_write_header(m_pVideoState->m_pFormatCtx, &m_pVideoState->m_pFormatOpts) < 0)
  413. {
  414. LOG_ERROR("Error occurred when writing header to output file.");
  415. return false;
  416. };
  417. m_pVideoState->m_bStatus = MS_OPENED;
  418. m_nDTS = 0;
  419. m_nPTS = 0;
  420. LOG("File Is Opened.");
  421. return true;
  422. };
  423. }
  424. else
  425. {
  426. LOG_ERROR("Alredy Opened.");
  427. };
  428. };
  429. return false;
  430. }
  431. void videoAVLIBDestination::close(void)
  432. {
  433. if (m_pVideoState->m_bStatus > MS_OPENING)
  434. {
  435. av_write_trailer(m_pVideoState->m_pFormatCtx);
  436. avio_close(m_pVideoState->m_pFormatCtx->pb);
  437. m_pVideoState->m_bStatus = MS_ALOCATED;
  438. };
  439. }
  440. static void log_packet(CSTR tBuff, const AVFormatContext * fmt_ctx, const AVPacket * pkt)
  441. {
  442. AVRational * time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
  443. /* sprintf( tBuff, "pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d",
  444. av_ts_make_string( " ", pkt->pts),
  445. //av_ts2str(pkt->pts),
  446. av_ts_make_time_string( " ", pkt->pts, time_base),
  447. //av_ts2timestr(pkt->pts, time_base),
  448. av_ts_make_string( " ", pkt->dts),
  449. //av_ts2str(pkt->dts),
  450. av_ts_make_time_string( " ", pkt->dts, time_base),
  451. //av_ts2timestr(pkt->dts, time_base),
  452. av_ts_make_string( " ", pkt->duration),
  453. //av_ts2str(pkt->duration),
  454. av_ts_make_time_string( " ", pkt->duration, time_base),
  455. //av_ts2timestr(pkt->duration, time_base),
  456. pkt->stream_index
  457. );
  458. */
  459. }
  460. void videoAVLIBDestination::pushFrame(cv::Mat * m_mFrame, void * src)
  461. {
  462. if (! m_bRecordIsStarted)
  463. {
  464. return;
  465. }
  466. if (m_mFrame != NULL)
  467. {
  468. if (img_convert_ctx == NULL)
  469. {
  470. // Allocating Context and sizes at first frame pushed thru the Bus
  471. img_convert_ctx = sws_getContext(m_mFrame->cols, m_mFrame->rows, AV_PIX_FMT_BGR24, m_nWidth, m_nHeight, VIDEO_OUTPUT_PIX_FMT, SWS_BICUBIC, NULL, NULL, NULL);
  472. if (img_convert_ctx == NULL)
  473. {
  474. m_pVideoState->m_bStatus = MS_STOPED;
  475. return;
  476. };
  477. // Buffer to scale and convert Pictures
  478. m_pFrame = av_frame_alloc();
  479. if (m_pFrame == NULL)
  480. {
  481. m_pVideoState->m_bStatus = MS_STOPED;
  482. return;
  483. };
  484. m_pIn_buffer = (uint8_t *) av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_nWidth, m_nHeight, BUFFER_ALIGN));
  485. if (m_pIn_buffer == NULL)
  486. {
  487. m_pVideoState->m_bStatus = MS_STOPED;
  488. return;
  489. };
  490. m_pFrame->width = m_nWidth;
  491. m_pFrame->height = m_nHeight;
  492. m_pFrame->format = VIDEO_OUTPUT_PIX_FMT;
  493. avpicture_fill((AVPicture *) m_pFrame, m_pIn_buffer, VIDEO_OUTPUT_PIX_FMT, m_nWidth, m_nHeight);
  494. };
  495. int linesize[2];
  496. linesize[0] = m_mFrame->cols * 3;
  497. linesize[1] = 0;
  498. const uint8_t * dataPTR[2];
  499. dataPTR[0] = (uint8_t *) m_mFrame->data;
  500. dataPTR[1] = NULL;
  501. sws_scale(img_convert_ctx, dataPTR, linesize, 0, m_mFrame->rows, m_pFrame->data, m_pFrame->linesize);
  502. int bGotPacket;
  503. m_nPTS++;
  504. m_nDTS++;
  505. m_pFrame->pts = m_nPTS;
  506. AVPacket mPacket;
  507. mPacket.data = NULL;
  508. mPacket.size = 0;
  509. av_init_packet(&mPacket);
  510. m_nOut_Size = avcodec_encode_video2(m_pVideoState->m_pCodecCtx, &mPacket, m_pFrame, &bGotPacket);
  511. if (bGotPacket)
  512. {
  513. // rescale packet timestamp
  514. mPacket.duration = 1;
  515. av_packet_rescale_ts(&mPacket, m_pVideoState->m_pVideoStr->codec->time_base, m_pVideoState->m_pVideoStr->time_base);
  516. // write packet
  517. // int ret = av_interleaved_write_frame(m_pVideoState->m_pFormatCtx, &mPacket);
  518. int ret = av_write_frame(m_pVideoState->m_pFormatCtx, &mPacket);
  519. if (ret < 0)
  520. {
  521. LOG_ERROR("Trouble with Video Output!");
  522. }
  523. };
  524. av_free_packet(&mPacket);
  525. };
  526. }
  527. /*
  528. void videoAVLIBDestination::m_fThreadProc(void){
  529. uint32_t tBufferSize;
  530. int counter = 500;
  531. m_bThreadStatus = TH_WORKING;
  532. LOG("Thread Started.");
  533. cv::setBreakOnError(true);
  534. while ( m_pMediaSource == NULL && m_bThreadStatus == TH_WORKING){
  535. m_pVideoState->m_bStatus = MS_STOPED;
  536. #ifdef __linux__
  537. usleep(2000);
  538. #else
  539. Sleep(2);
  540. #endif
  541. };
  542. m_pVideoState->m_bStatus = MS_PRESENT;
  543. m_nOut_Size = 0;
  544. while (m_bThreadStatus == TH_WORKING){
  545. if ((counter--) < 0) {
  546. LOG("Test Done!");
  547. m_bThreadStatus = TH_ENDED;
  548. };
  549. if (m_pMediaSource->getConnectionStatus() == AS_BOTH){
  550. m_mFrame = m_pMediaInput->getPackage();
  551. if(m_mFrame != NULL) {
  552. if( img_convert_ctx == NULL ) {
  553. // Allocating Context and sizes at first frame pushed thru the Bus
  554. img_convert_ctx = sws_getContext(m_mFrame->cols, m_mFrame->rows,
  555. AV_PIX_FMT_BGR24,
  556. m_nWidth, m_nHeight,
  557. MJPEG_PIX_FMT,
  558. SWS_BICUBIC, NULL, NULL, NULL);
  559. if (img_convert_ctx == NULL) {
  560. m_pVideoState->m_bStatus = MS_STOPED;
  561. m_bThreadStatus = TH_ENDED;
  562. continue;
  563. };
  564. // Buffer to scale and convert Pictures
  565. m_pFrame = av_frame_alloc();
  566. if (m_pFrame == NULL) {
  567. m_pVideoState->m_bStatus = MS_STOPED;
  568. m_bThreadStatus = TH_ENDED;
  569. continue;
  570. };
  571. m_pIn_buffer = (uint8_t *)av_malloc(av_image_get_buffer_size(MJPEG_PIX_FMT, m_nWidth, m_nHeight, BUFFER_ALIGN));
  572. if (m_pIn_buffer == NULL) {
  573. m_pVideoState->m_bStatus = MS_STOPED;
  574. m_bThreadStatus = TH_ENDED;
  575. continue;
  576. };
  577. avpicture_fill((AVPicture *)m_pFrame, m_pIn_buffer, MJPEG_PIX_FMT, m_nWidth, m_nHeight);
  578. // Temporary Input Buffer
  579. m_tFrame = av_frame_alloc();
  580. if (m_tFrame == NULL) {
  581. m_pVideoState->m_bStatus = MS_STOPED;
  582. m_bThreadStatus = TH_ENDED;
  583. continue;
  584. };
  585. //tBufferSize = m_mFrame->cols * m_mFrame->rows * m_mFrame->channels();
  586. //tBufferSize = av_image_get_buffer_size(AV_PIX_FMT_BGR24, m_mFrame->cols, m_mFrame->rows, BUFFER_ALIGN );
  587. //m_pTemp_buffer = NULL; // (uint8_t *)av_malloc(tBufferSize);
  588. //memset(m_pTemp_buffer, 0, tBufferSize);
  589. //if (m_pTemp_buffer == NULL) {
  590. // m_pVideoState->m_bStatus = MS_STOPED;
  591. // m_bThreadStatus = TH_ENDED;
  592. // continue;
  593. //};
  594. avpicture_fill((AVPicture *)m_tFrame, NULL, AV_PIX_FMT_BGR24, m_mFrame->cols, m_mFrame->rows);
  595. };
  596. //memcpy(m_tFrame->data[0], m_mFrame->data, m_mFrame->step[0] * m_mFrame->rows);
  597. //sws_scale(img_convert_ctx, (const uint8_t* const*)m_pFrame->data, m_pFrame->linesize, 0, m_mFrame->col*m_mFrame->row, m_pFrame->data, m_pFrame->linesize);
  598. //int linesize[2];
  599. //linesize[0] = m_mFrame->cols*3;
  600. //linesize[1] = 0; (const uint8_t* const*)
  601. m_tFrame->data[0] = (uint8_t *) m_mFrame->data;
  602. sws_scale( img_convert_ctx,
  603. (const uint8_t* const*)m_tFrame->data,
  604. m_tFrame->linesize,
  605. 0, m_mFrame->rows,
  606. m_pFrame->data, m_pFrame->linesize );
  607. m_tFrame->data[0] = NULL;
  608. delete(m_mFrame);
  609. //Todo: reslove--> m_nOut_Size = avcodec_encode_video2(m_pVideoState->m_pCodecCtx, m_pOut_buffer, m_nOut_bufferSize, m_pFrame);
  610. //AVPacket OPacket;
  611. //pOPacket->data = NULL;
  612. //av_init_packet(&OPacket);
  613. //av_packet_from_data( pOPacket, m_pOut_buffer, m_nOut_Size );
  614. //fwrite(m_pOut_buffer, 1, m_nOut_Size, m_pOutputFile);
  615. //av_write_frame(m_pVideoState->m_pFormatCtx, pOPacket);
  616. //av_free_packet( pOPacket );
  617. if (m_pVideoState->m_pCodecCtx->coded_frame->pts != AV_NOPTS_VALUE)
  618. m_pPacket->pts = av_rescale_q(m_pVideoState->m_pCodecCtx->coded_frame->pts,
  619. m_pVideoState->m_pCodecCtx->time_base,
  620. m_pVideoState->m_pVideoStr->time_base);
  621. if (m_pVideoState->m_pCodecCtx->coded_frame->key_frame)
  622. m_pPacket->flags |= AV_PKT_FLAG_KEY;
  623. m_pPacket->stream_index = m_pVideoState->m_pVideoStr->index;
  624. m_pPacket->data = m_pOut_buffer;
  625. m_pPacket->size = m_nOut_Size;
  626. // write the compressed frame in the media file
  627. int ret = av_interleaved_write_frame(m_pVideoState->m_pFormatCtx, m_pPacket);
  628. } else {
  629. // get the delayed frames
  630. //while (m_nOut_Size) {
  631. // //fflush(stdout);
  632. // m_nOut_Size = avcodec_encode_video(m_pVideoState->m_pCodecCtx, m_pOut_buffer, m_nOut_bufferSize, NULL);
  633. // fwrite(m_pOut_buffer, 1, m_nOut_Size, m_pOutputFile);
  634. //};
  635. m_pVideoState->m_bStatus = MS_STOPED;
  636. #ifdef __linux__
  637. usleep(2000);
  638. #else
  639. Sleep(2);
  640. #endif
  641. };
  642. }else{
  643. #ifdef __linux__
  644. usleep(20000);
  645. #else
  646. Sleep(20);
  647. #endif
  648. };
  649. };
  650. this->close();
  651. LOG("Thread Ended.");
  652. m_bThreadStatus = TH_ENDED;
  653. };
  654. */
  655. /*
  656. while(av_read_frame(input_container, &decoded_packet)>=0) {
  657. if (decoded_packet.stream_index == video_stream_index) {
  658. len = avcodec_decode_video2(input_stream->codec, decoded_frame, &got_frame, &decoded_packet);
  659. if(len < 0) {
  660. exit(1);
  661. }
  662. if(got_frame) {
  663. av_init_packet(&encoded_packet);
  664. encoded_packet.data = NULL;
  665. encoded_packet.size = 0;
  666. if(avcodec_encode_video2(output_stream->codec, &encoded_packet, decoded_frame, &got_frame) < 0) {
  667. exit(1);
  668. }
  669. if(got_frame) {
  670. if (output_stream->codec->coded_frame->key_frame) {
  671. encoded_packet.flags |= AV_PKT_FLAG_KEY;
  672. }
  673. encoded_packet.stream_index = output_stream->index;
  674. encoded_packet.pts = av_rescale_q(current_frame_num, output_stream->codec->time_base, output_stream->time_base);
  675. encoded_packet.dts = av_rescale_q(current_frame_num, output_stream->codec->time_base, output_stream->time_base);
  676. if(av_interleaved_write_frame(output_container, &encoded_packet) < 0) {
  677. exit(1);
  678. }
  679. else {
  680. current_frame_num +=1;
  681. }
  682. }
  683. frame_count+=1;
  684. av_free_packet(&encoded_packet);
  685. }
  686. }
  687. }
  688. */
  689. #undef LOG
  690. #undef LOG_ERROR