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.

752 lines
25 KiB

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