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.

744 lines
24 KiB

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