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.

552 lines
23 KiB

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