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.

549 lines
23 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "servaMediaEncoder.h"
  2. #include "servaKernel.h"
  3. #define LOG( X ) m_pLog->Log( "MEN", this, X )
  4. #ifdef DEBUG
  5. #define LOG_ERROR( X ) {\
  6. char _tBfrErrMSG234[256];\
  7. sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  8. m_pLog->Log( "MEN", this, _LOG_ERROR, _tBfrErrMSG234 );\
  9. }
  10. #else
  11. #define LOG_ERROR( X ) m_pLog->Log( "MEN", this, _LOG_ERROR, X );
  12. #endif
  13. servaMediaEncoder::servaMediaEncoder( uint64_t Ref ):basicThread(){
  14. m_pLog = basicLogCollection::getInstance();
  15. m_pMaster = servaKernel::getInstance();
  16. m_nRefID = Ref;
  17. m_nInFileSize = 0;
  18. m_nOutFileSize = 0;
  19. m_bStatus = ENCODER_NONE;
  20. DBC_SERVA_MEDIA_ENCODER_SETTINGS *tData = NULL;//m_pDBC->getMediaEncoderSettings();
  21. if( tData ){
  22. memcpy( &m_sEncoderSettings, tData, sizeof( DBC_SERVA_MEDIA_ENCODER_SETTINGS ) );
  23. } else {
  24. memset( &m_sEncoderSettings, 0, sizeof( DBC_SERVA_MEDIA_ENCODER_SETTINGS ));
  25. m_sEncoderSettings.CRF = 28;//20;
  26. strncpy( m_sEncoderSettings.preset, "slow", 15 );
  27. strncpy( m_sEncoderSettings.tune, "fastdecode", 15 );
  28. strncpy( m_sEncoderSettings.profile, "main", 15 );
  29. m_sEncoderSettings.TH_MODE = FF_THREAD_FRAME;
  30. m_sEncoderSettings.bitrate = 666;
  31. strncpy( m_sEncoderSettings.CONTAINER, "mp4", 4 );
  32. strncpy( m_sEncoderSettings.CODEC, "h264", 4 );
  33. }
  34. memset( &m_sDecoderVS, 0, sizeof(LIBAV_VS));
  35. memset( &m_sEncoderVS, 0, sizeof(LIBAV_VS));
  36. };
  37. CSTR servaMediaEncoder::getDstFormat(){ return m_sEncoderSettings.CONTAINER; };
  38. servaMediaEncoder::~servaMediaEncoder(){
  39. #ifndef STEPHANE_OPENCV_ENCODE
  40. if (m_sEncoderVS.m_pCodecCtx) {
  41. avcodec_close( m_sEncoderVS.m_pCodecCtx );
  42. avcodec_free_context( &m_sEncoderVS.m_pCodecCtx );
  43. };
  44. if ( m_sEncoderVS.m_pFormatCtx ) {
  45. /* Free the streams. */
  46. for (int i = 0; i < m_sEncoderVS.m_pFormatCtx->nb_streams; i++) {
  47. //av_freep(&m_sEncoderVS.m_pFormatCtx->streams[i]->codec);
  48. av_freep(&m_sEncoderVS.m_pFormatCtx->streams[i]);
  49. };
  50. av_free( m_sEncoderVS.m_pFormatCtx );
  51. };
  52. if (m_sEncoderVS.m_pFormatOpts) av_free( m_sEncoderVS.m_pFormatOpts );
  53. #endif //!STEPHANE_OPENCV_ENCODE
  54. LOG("Destructor Exit");
  55. };
  56. #include <sys/stat.h>
  57. bool servaMediaEncoder::create( CSTR src, CSTR dst, uint8_t fps, int width, int height, CSTR custom ){
  58. #ifndef STEPHANE_OPENCV_ENCODE
  59. int RetVal;
  60. char Buffer[1024] = {0};
  61. if ( !initLibAV() ) return false;
  62. #endif
  63. strncpy( m_sDecoderVS.m_pFileName, src, MAX_PATH_LEN);
  64. strncpy( m_sEncoderVS.m_pFileName, dst, MAX_PATH_LEN);
  65. struct stat st;
  66. stat( m_sDecoderVS.m_pFileName, &st );
  67. m_nInFileSize = st.st_size;
  68. #ifndef STEPHANE_OPENCV_ENCODE
  69. //LOG("Before Open1");
  70. if( ( RetVal = avformat_open_input( &m_sDecoderVS.m_pFormatCtx, m_sDecoderVS.m_pFileName, NULL, &m_sDecoderVS.m_pFormatOpts) ) != 0 ){
  71. //av_dict_free(&options);
  72. char tBuffer[1024];
  73. av_strerror( RetVal, tBuffer, 1024 );
  74. sprintf(Buffer, "VideoSource Couldn't open input stream[%s](Code:%d): %s", tBuffer, RetVal, m_sDecoderVS.m_pFileName );
  75. LOG_ERROR(Buffer);
  76. return false;
  77. };
  78. //LOG("After Open1");
  79. AVDictionaryEntry *e;
  80. if( e = av_dict_get( m_sDecoderVS.m_pFormatOpts, "", NULL, AV_DICT_IGNORE_SUFFIX )){
  81. sprintf( Buffer, "Option %s not recognized by the demuxer", e->key );
  82. LOG_ERROR(Buffer);
  83. };
  84. #ifdef DEBUG_EXTRA
  85. LOG("DataStream Opened");
  86. #endif
  87. m_sDecoderVS.m_bStatus = MS_OPENED;
  88. if( avformat_find_stream_info( m_sDecoderVS.m_pFormatCtx, NULL ) < 0 ){
  89. sprintf(Buffer, "Couldn't find stream information: %s", m_sDecoderVS.m_pFileName );
  90. LOG_ERROR( Buffer );
  91. return false;
  92. };
  93. #if ( LIBAVCODEC_VERSION_MAJOR < 58 ) // && ( LIBAVCODEC_VERSION_MINOR < 50 )
  94. for( unsigned int i=0; i < m_sDecoderVS.m_pFormatCtx->nb_streams; i++ ){
  95. //if( m_pVideoState->m_pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ){
  96. if( m_sDecoderVS.m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ){
  97. #ifdef DEBUG_EXTRA
  98. LOG( "VIDEO stream detected." );
  99. #endif
  100. if( m_sDecoderVS.m_iVideoStreamID <0 ){
  101. #ifdef DEBUG_EXTRA
  102. LOG( "VIDEO stream assigned." );
  103. #endif
  104. m_pVideoState->m_iVideoStreamID=i;
  105. };
  106. };
  107. };
  108. if( m_sDecoderVS.m_iVideoStreamID == -1 ){
  109. LOG_ERROR( "Didn't find a video stream.");
  110. return false;
  111. };
  112. // Stream found
  113. m_sDecoderVS.m_pCodecCtx = m_sDecoderVS.m_pFormatCtx->streams[m_sDecoderVS.m_iVideoStreamID]->codec;
  114. //m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iVideoStreamID]->codecpar->codec_id
  115. m_sDecoderVS.m_pVideoCodec = avcodec_find_decoder( m_sDecoderVS.m_pCodecCtx->codec_id );
  116. #else
  117. # ifdef DEBUG_EXTRA
  118. LOG("YABABA-2!");
  119. # endif
  120. /* find the video stream information */
  121. m_sDecoderVS.m_iVideoStreamID = av_find_best_stream( m_sDecoderVS.m_pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &m_sDecoderVS.m_pVideoCodec, 0);
  122. if (m_sDecoderVS.m_iVideoStreamID == -1){
  123. LOG_ERROR("Didn't find a video stream.");
  124. return false;
  125. };
  126. if (!(m_sDecoderVS.m_pCodecCtx = avcodec_alloc_context3(m_sDecoderVS.m_pVideoCodec))){
  127. LOG_ERROR("Can not create decoder context!");
  128. return false;
  129. };
  130. m_sDecoderVS.m_pVideoStr = m_sDecoderVS.m_pFormatCtx->streams[m_sDecoderVS.m_iVideoStreamID];
  131. if ( avcodec_parameters_to_context( m_sDecoderVS.m_pCodecCtx, m_sDecoderVS.m_pVideoStr->codecpar ) < 0 ){
  132. LOG_ERROR("Can not set Context parameters!");
  133. return false;
  134. };
  135. #endif
  136. if( m_sDecoderVS.m_pVideoCodec == NULL ){
  137. sprintf(Buffer, "Codec [%d] not found for %s", m_sDecoderVS.m_pCodecCtx->codec_id, m_sDecoderVS.m_pFileName );
  138. LOG_ERROR( Buffer );
  139. return false;
  140. };
  141. /*
  142. End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2())
  143. and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE).
  144. Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool.
  145. */
  146. //m_sDecoderVS.m_pCodecCtx->thread_count = 4;
  147. m_sDecoderVS.m_pCodecCtx->thread_type = m_sEncoderSettings.TH_MODE;//FF_THREAD_FRAME;
  148. //if (is_live)
  149. //m_sDecoderVS.m_pCodecCtx->thread_count = FF_THREAD_SLICE;
  150. //else
  151. //m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE | FF_THREAD_FRAME;
  152. #ifdef DEBUG_EXTRA
  153. LOG("Before Open2");
  154. #endif
  155. if( avcodec_open2( m_sDecoderVS.m_pCodecCtx, m_sDecoderVS.m_pVideoCodec, NULL ) < 0 ){
  156. sprintf(Buffer, "Could not open Video codec[%d] for %s", m_sDecoderVS.m_pCodecCtx->codec_id, m_sDecoderVS.m_pFileName );
  157. LOG_ERROR( Buffer );
  158. return false;
  159. };
  160. /* we do not send complete frames */
  161. if( m_sDecoderVS.m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) m_sDecoderVS.m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED;
  162. #ifdef DEBUG_EXTRA
  163. char tB[256];
  164. sprintf( tB, "Setting Frame [%dx%d]", width, height );
  165. LOG( tB );
  166. sprintf( tB, "Source Frame [%dx%d]", m_sDecoderVS.m_pCodecCtx->width, m_sDecoderVS.m_pCodecCtx->height );
  167. LOG( tB );
  168. #endif
  169. /*
  170. if( ( width > 0 ) && ( height > 0 ) ){
  171. m_nOutWidth = width;
  172. m_nOutHeight = height;
  173. } else {
  174. if( m_bSizeIsAutomatic ){
  175. #ifdef DEBUG_EXTRA
  176. LOG("Size is Automatic");
  177. #endif
  178. if(( m_nOutWidth == -1 )&&( m_nOutHeight == -1 )){
  179. m_nOutWidth = m_pVideoState->m_pCodecCtx->width;
  180. m_nOutHeight = m_pVideoState->m_pCodecCtx->height;
  181. } else {
  182. // Proportional
  183. if( m_nOutHeight == -1 ){
  184. float k = ((float)m_pVideoState->m_pCodecCtx->height) / ((float)m_pVideoState->m_pCodecCtx->width);
  185. m_nOutHeight = (int)(((float)m_nOutWidth ) * k );
  186. } else {
  187. float k = ((float)m_pVideoState->m_pCodecCtx->width) / ((float)m_pVideoState->m_pCodecCtx->height);
  188. m_nOutWidth = (int)(((float)m_nOutHeight ) * k );
  189. };
  190. };
  191. } else {
  192. #ifdef DEBUG_EXTRA
  193. LOG("Size is Manual");
  194. #endif
  195. if( ( width > 0 ) && ( height > 0 ) ){
  196. m_nOutWidth = width;
  197. m_nOutHeight = height;
  198. } else {
  199. m_nOutWidth = m_pVideoState->m_pCodecCtx->width;
  200. m_nOutHeight = m_pVideoState->m_pCodecCtx->height;
  201. };
  202. };
  203. };
  204. #ifdef DEBUG_EXTRA
  205. sprintf( tB, "Using Size [%dx%d]", m_nOutWidth, m_nOutHeight );
  206. LOG( tB );
  207. sprintf(tB,"swsPar: IN: %dx%d [%d] OUT: %dx%d [%d] {%d}", m_pVideoState->m_pCodecCtx->width,
  208. m_pVideoState->m_pCodecCtx->height,
  209. m_pVideoState->m_pCodecCtx->pix_fmt,
  210. m_nOutWidth,
  211. m_nOutHeight,
  212. AV_PIX_FMT_BGR24,
  213. SWS_BICUBIC );
  214. LOG( tB );
  215. #endif
  216. m_pVideoState->m_pSwsCtx = sws_getContext(
  217. m_pVideoState->m_pCodecCtx->width,
  218. m_pVideoState->m_pCodecCtx->height,
  219. m_pVideoState->m_pCodecCtx->pix_fmt,
  220. m_nOutWidth,
  221. m_nOutHeight,
  222. AV_PIX_FMT_BGR24,
  223. SWS_BICUBIC, //SWS_FAST_BILINEAR,// | SWS_ACCURATE_RND,//SWS_BILINEAR,//SWS_BICUBIC,
  224. NULL,
  225. NULL,
  226. NULL
  227. );
  228. if ( m_pVideoState->m_pSwsCtx == NULL ){
  229. LOG_ERROR("Error Allocating SwsCtx!");
  230. return false;
  231. };
  232. */
  233. m_bStatus = DECODER_INIT;
  234. /* Encoder */
  235. m_sEncoderVS.m_pFormatCtx = NULL;
  236. m_sEncoderVS.m_pFormatOpts = NULL;
  237. int ret = avformat_alloc_output_context2( &m_sEncoderVS.m_pFormatCtx, NULL, NULL, m_sEncoderVS.m_pFileName );
  238. if (ret < 0) {
  239. LOG_ERROR("VideoFormat Context Memory Allocation Error");
  240. return false;
  241. };
  242. LOG(m_sEncoderVS.m_pFileName);
  243. m_sEncoderVS.m_pFormatCtx->oformat = av_guess_format( NULL, m_sEncoderVS.m_pFileName, NULL);
  244. if (m_sEncoderVS.m_pFormatCtx->oformat == NULL){
  245. LOG_ERROR("VideoFormat Format Not Guessed!");
  246. return false;
  247. #ifdef DEBUG_EXTRA
  248. } else {
  249. LOG("Video Container Format Guessed");
  250. #endif
  251. };
  252. //In Case mp4
  253. if ( strcasestr( m_sEncoderSettings.CONTAINER, "mp4" ) ) {
  254. if (av_dict_set(&m_sEncoderVS.m_pFormatOpts, "brand", "mp42", 0) < 0) {
  255. LOG_ERROR( "av_dict_set brand!" );
  256. };
  257. };
  258. m_sEncoderVS.m_pVideoStr = avformat_new_stream( m_sEncoderVS.m_pFormatCtx, m_sEncoderVS.m_pVideoCodec );
  259. if( m_sEncoderVS.m_pVideoStr == NULL ){
  260. LOG_ERROR("VideoStream Not Created!");
  261. return false;
  262. #ifdef DEBUG_EXTRA
  263. }else{
  264. LOG("VideoStream is Created");
  265. #endif
  266. };
  267. //m_sEncoderVS.m_pVideoCodec = avcodec_find_encoder(av_guess_codec(m_sEncoderVS.m_pFormatCtx->oformat, NULL, m_sEncoderVS.m_pFileName, NULL, AVMEDIA_TYPE_VIDEO));
  268. if ( strcasestr( m_sEncoderSettings.CODEC, "h264" ) ) {
  269. m_sEncoderVS.m_pVideoCodec = avcodec_find_encoder( AV_CODEC_ID_H264 );
  270. } else {
  271. m_sEncoderVS.m_pVideoCodec = avcodec_find_encoder( AV_CODEC_ID_H265 );
  272. };
  273. if( m_sEncoderVS.m_pVideoCodec == NULL ){
  274. LOG_ERROR("VideoCodec Not Found!");
  275. return false;
  276. #ifdef DEBUG_EXTRA
  277. } else {
  278. LOG("Video Codec Found");
  279. #endif
  280. };
  281. m_sEncoderVS.m_pCodecCtx = avcodec_alloc_context3( m_sEncoderVS.m_pVideoCodec );
  282. if (m_sEncoderVS.m_pCodecCtx == NULL){
  283. LOG_ERROR("VideoCodec Context Memory Allocation Error");
  284. return false;
  285. #ifdef DEBUG_EXTRA
  286. } else {
  287. LOG("Codec Context3 Allocated");
  288. #endif
  289. };
  290. m_sEncoderVS.m_pCodecCtx->width = m_sDecoderVS.m_pCodecCtx->width;
  291. m_sEncoderVS.m_pCodecCtx->height = m_sDecoderVS.m_pCodecCtx->height;
  292. //const AVRational dst_fps = { fps, 1 };
  293. m_sEncoderVS.m_pVideoStr->time_base = av_make_q( 1, 150000 );// .num = 1;//av_inv_q(dst_fps);
  294. //m_sEncoderVS.m_pVideoStr->time_base.den = fps;
  295. m_sEncoderVS.m_pVideoStr->r_frame_rate = av_make_q( fps, 1 );//.num = fps;
  296. //m_sEncoderVS.m_pVideoStr->r_frame_rate.den = 1;
  297. m_sEncoderVS.m_pVideoStr->avg_frame_rate = av_make_q( fps, 1 ); //.num = fps;
  298. //m_sEncoderVS.m_pVideoStr->avg_frame_rate.den = 1;
  299. m_sEncoderVS.m_pCodecCtx->time_base = av_make_q( 1, 150000 );//.num = 1;
  300. //m_sEncoderVS.m_pCodecCtx->time_base.den = fps;
  301. m_sEncoderVS.m_pCodecCtx->gop_size = fps << 1; // emit one intra frame every fps*2 frames
  302. m_sEncoderVS.m_pCodecCtx->bit_rate = m_sEncoderSettings.bitrate; //400000;
  303. m_sEncoderVS.m_pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
  304. //if (codec_id == AV_CODEC_ID_H264)
  305. //av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "slow", 0);
  306. av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "preset", m_sEncoderSettings.preset, 0 );
  307. av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "profile", m_sEncoderSettings.profile, 0 );
  308. m_sEncoderVS.m_pCodecCtx->max_b_frames = m_sEncoderVS.m_pCodecCtx->gop_size * 3;
  309. m_sEncoderVS.m_pCodecCtx->level = 31;
  310. /// P-frames, generated by referencing data from prev and future frames.
  311. /// [Compression up, CPU usage up]
  312. /// [use 3/gop]
  313. //m_sEncoderVS.m_pCodecCtx->max_b_frames = 5;
  314. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  315. /// [use 3�5 ref per P]
  316. m_sEncoderVS.m_pCodecCtx->refs = 3;
  317. /// Compression efficiency (slower -> better quality + higher cpu%)
  318. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  319. /// Set this option to "ultrafast" is critical for realtime encoding
  320. //av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  321. //av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "fast", 0 );
  322. //av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "slow", 0 );
  323. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  324. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  325. //av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "crf", "20", 0);
  326. char tBuf[16]; sprintf( tBuf, "%d", m_sEncoderSettings.CRF );
  327. av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "crf", tBuf, 0 );
  328. /// Change settings based upon the specifics of input
  329. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  330. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  331. //av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  332. av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "tune", m_sEncoderSettings.tune, 0);
  333. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  334. /// Because Quicktime (ie. iOS) doesn't support this option
  335. av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
  336. if( avcodec_is_open( m_sEncoderVS.m_pCodecCtx ) == 0 ){
  337. #ifdef DEBUG_EXTRA
  338. LOG("output codec context is closed, opening");
  339. #endif
  340. int ret = avcodec_open2( m_sEncoderVS.m_pCodecCtx, m_sEncoderVS.m_pVideoCodec, NULL );
  341. if( ret < 0 ){
  342. LOG_ERROR("Error opening2 encoder");
  343. char buffer[30];
  344. sprintf(buffer, "Error code: %i", ret );
  345. LOG_ERROR(buffer);
  346. return false;
  347. };
  348. #ifdef DEBUG_EXTRA
  349. } else {
  350. LOG("output codec context is opened");
  351. #endif
  352. };
  353. m_sEncoderVS.m_pVideoStr->codec = m_sEncoderVS.m_pCodecCtx; //---->see next page
  354. if (avio_open(&m_sEncoderVS.m_pFormatCtx->pb, m_sEncoderVS.m_pFileName, AVIO_FLAG_WRITE ) < 0){
  355. LOG_ERROR("Could not open output file.");
  356. return false;
  357. };
  358. if (avformat_write_header(m_sEncoderVS.m_pFormatCtx, &m_sEncoderVS.m_pFormatOpts ) < 0){
  359. LOG_ERROR("Error occurred when writing header to output file.");
  360. return false;
  361. };
  362. m_sEncoderVS.m_iVideoStreamID = -1;
  363. #ifdef DEBUG_EXTRA
  364. LOG("Allocation Done");
  365. #endif
  366. #endif //!STEPHANE_OPENCV_ENCODE
  367. m_bStatus = ENCODER_INIT;
  368. return init();
  369. };
  370. void servaMediaEncoder::m_fThreadProc( void ){
  371. #ifdef STEPHANE_OPENCV_ENCODE
  372. uint8_t operc = 0;
  373. #ifdef DEBUG_EXTRA
  374. char tB[1024];
  375. sprintf( tB, "Converting %s to %s", m_sDecoderVS.m_pFileName, m_sEncoderVS.m_pFileName );
  376. LOG( tB );
  377. #endif
  378. cv::VideoCapture cap( m_sDecoderVS.m_pFileName );
  379. if( cap.isOpened() ) {
  380. cv::Mat mat;
  381. cap >> mat;
  382. if( !mat.empty() ){
  383. cap.set( cv::VideoCaptureProperties::CAP_PROP_POS_FRAMES, 0.0 );
  384. cv::VideoWriter out( m_sEncoderVS.m_pFileName, cv::VideoWriter::fourcc('a', 'v', 'c', '1'), 15.0, mat.size() );
  385. size_t number_of_frames = 0;
  386. m_bStatus = THREAD_INIT;
  387. m_bThreadStatus = TH_WORKING;
  388. while( cap.isOpened() && out.isOpened() && m_bThreadStatus < TH_ENDED ){
  389. cap >> mat;
  390. m_bStatus = ENCODER_ENCODING;
  391. if( mat.empty() ){
  392. m_bThreadStatus = TH_ENDED;
  393. } else {
  394. number_of_frames ++;
  395. out.write(mat);
  396. };
  397. uint8_t perc = ( 100 * number_of_frames ) / 900;
  398. if ( operc!= perc ) {
  399. if ( perc > 100 ) perc = 100;
  400. operc = perc;
  401. m_pMaster->updateEncodeStatus(m_nRefID, MEDIA_ENCODE_PROGRESS, perc);
  402. };
  403. };
  404. cap.release();
  405. // Does it look reasonable?� If so, then we can go ahead and delete the original file.
  406. if( number_of_frames > 100 ){
  407. unlink( m_sDecoderVS.m_pFileName );
  408. };
  409. };
  410. };
  411. #else //!STEPHANE_OPENCV_ENCODE
  412. AVPacket read_packet;
  413. AVPacket encoded_packet;
  414. uint64_t current_frame_num = 0;
  415. uint64_t frame_count = 0;
  416. uint8_t operc = 0;
  417. uint64_t pack_duration = m_sEncoderVS.m_pCodecCtx->time_base.den / m_sEncoderVS.m_pCodecCtx->time_base.num
  418. / m_sEncoderVS.m_pVideoStr->avg_frame_rate.num *
  419. m_sEncoderVS.m_pVideoStr->avg_frame_rate.den + 666;
  420. int got_frame;
  421. //int test;
  422. m_bStatus = THREAD_INIT;
  423. // Allocate video frame
  424. AVFrame *decoded_frame = av_frame_alloc();
  425. m_bThreadStatus = TH_WORKING;
  426. m_bStatus = ENCODER_ENCODING;
  427. m_nReadSize = 0;
  428. char tB[128];
  429. sprintf( tB, "Pack Duration: %" PRIu64, pack_duration );
  430. LOG(tB);
  431. while( av_read_frame( m_sDecoderVS.m_pFormatCtx, &read_packet ) >= 0 && m_bThreadStatus < TH_ENDED ){
  432. m_nReadSize += read_packet.size;
  433. // Is this a packet from the video stream?
  434. if( read_packet.stream_index == m_sDecoderVS.m_iVideoStreamID ){
  435. // Decode video frame
  436. if( avcodec_decode_video2( m_sDecoderVS.m_pCodecCtx, decoded_frame, &got_frame, &read_packet ) < 0 ){
  437. m_bThreadStatus = TH_ENDED;
  438. continue;
  439. };
  440. // Did we get a video frame?
  441. if( got_frame ){
  442. av_init_packet( &encoded_packet );
  443. encoded_packet.data = NULL;
  444. encoded_packet.size = 0;
  445. decoded_frame->pts = current_frame_num * pack_duration;
  446. uint8_t perc = ( 100 * m_nReadSize ) / m_nInFileSize;
  447. if ( operc!= perc ) {
  448. operc = perc;
  449. m_pMaster->updateEncodeStatus(m_nRefID, MEDIA_ENCODE_PROGRESS, perc);
  450. };
  451. if( avcodec_encode_video2( m_sEncoderVS.m_pCodecCtx, &encoded_packet, decoded_frame, &got_frame) < 0 ){
  452. m_bThreadStatus = TH_ENDED;
  453. continue;
  454. };
  455. if( got_frame ){
  456. if( m_sEncoderVS.m_pCodecCtx->coded_frame->key_frame ) encoded_packet.flags |= AV_PKT_FLAG_KEY;
  457. encoded_packet.stream_index = m_sEncoderVS.m_pVideoStr->index;
  458. //if( m_sEncoderVS.m_pCodecCtx->coded_frame->pts != AV_NOPTS_VALUE ) encoded_packet.pts = av_rescale_q( m_sEncoderVS.m_pCodecCtx->coded_frame->pts, m_sEncoderVS.m_pCodecCtx->time_base, m_sEncoderVS.m_pVideoStr->time_base );
  459. //encoded_packet.pts = av_rescale_q( m_sEncoderVS.m_pCodecCtx->coded_frame->pts, m_sEncoderVS.m_pCodecCtx->time_base, m_sEncoderVS.m_pVideoStr->time_base );
  460. //encoded_packet.dts = av_rescale_q( m_sEncoderVS.m_pCodecCtx->coded_frame->pts, m_sEncoderVS.m_pCodecCtx->time_base, m_sEncoderVS.m_pVideoStr->time_base );
  461. //if( m_sEncoderVS.m_pCodecCtx->coded_frame->pts != AV_NOPTS_VALUE )
  462. encoded_packet.duration = pack_duration;
  463. if( av_interleaved_write_frame( m_sEncoderVS.m_pFormatCtx, &encoded_packet ) < 0 ){
  464. m_bThreadStatus = TH_ENDED;
  465. continue;
  466. } else {
  467. m_nOutFileSize += encoded_packet.size;
  468. current_frame_num++;
  469. };
  470. };
  471. frame_count++;
  472. av_free_packet( &encoded_packet );
  473. };
  474. };
  475. // Free the packet that was allocated by av_read_frame
  476. av_free_packet( &read_packet );
  477. };
  478. // Close the video file
  479. avformat_close_input( &m_sDecoderVS.m_pFormatCtx );
  480. // Free the YUV frame
  481. av_frame_free( &decoded_frame );
  482. av_write_trailer( m_sEncoderVS.m_pFormatCtx );
  483. avio_close( m_sEncoderVS.m_pFormatCtx->pb );
  484. unlink( m_sDecoderVS.m_pFileName );
  485. #endif //!STEPHANE_OPENCV_ENCODE
  486. m_pMaster->updateEncodeStatus( m_nRefID, MEDIA_ENCODE_PROGRESS, 100 );
  487. m_pMaster->updateEncodeStatus( m_nRefID, MEDIA_READY, 100 );
  488. #ifdef DEBUG
  489. LOG("Encoding Done!");
  490. #endif
  491. m_bStatus = ENCODER_FINISHED;
  492. };
  493. uint8_t servaMediaEncoder::getStatus(){
  494. return m_bStatus;
  495. };
  496. #undef LOG
  497. #undef LOG_ERROR