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.

742 lines
24 KiB

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