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.

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