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.

746 lines
24 KiB

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