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.
 
 
 
 
 
 

463 lines
20 KiB

#include "servaMediaEncoder.h"
#include "servaKernel.h"
#define LOG( X ) m_pLog->Log( "MEN", this, X )
#ifdef DEBUG
#define LOG_ERROR( X ) {\
char _tBfrErrMSG234[256];\
sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
m_pLog->Log( "MEN", this, _LOG_ERROR, _tBfrErrMSG234 );\
}
#else
#define LOG_ERROR( X ) m_pLog->Log( "MEN", this, _LOG_ERROR, X );
#endif
servaMediaEncoder::servaMediaEncoder( uint64_t Ref ):basicThread(){
m_pLog = basicLogCollection::getInstance();
m_pMaster = servaKernel::getInstance();
m_nRefID = Ref;
m_nInFileSize = 0;
m_nOutFileSize = 0;
m_bStatus = ENCODER_NONE;
DBC_SERVA_MEDIA_ENCODER_SETTINGS *tData = NULL;//m_pDBC->getMediaEncoderSettings();
if( tData ){
memcpy( &m_sEncoderSettings, tData, sizeof( DBC_SERVA_MEDIA_ENCODER_SETTINGS ) );
} else {
memset( &m_sEncoderSettings, 0, sizeof( DBC_SERVA_MEDIA_ENCODER_SETTINGS ));
m_sEncoderSettings.CRF = 20;
strncpy( m_sEncoderSettings.preset, "medium", 15 );
strncpy( m_sEncoderSettings.tune, "fastdecode", 15 );
strncpy( m_sEncoderSettings.profile, "high422", 15 );
m_sEncoderSettings.TH_MODE = FF_THREAD_FRAME;
m_sEncoderSettings.bitrate = 400000;
strncpy( m_sEncoderSettings.CONTAINER, "mp4", 4 );
strncpy( m_sEncoderSettings.CODEC, "h264", 4 );
}
memset( &m_sDecoderVS, 0, sizeof(LIBAV_VS));
memset( &m_sEncoderVS, 0, sizeof(LIBAV_VS));
};
servaMediaEncoder::~servaMediaEncoder(){
if ( m_sEncoderVS.m_pFormatCtx ) {
/* Free the streams. */
for (int i = 0; i < m_sEncoderVS.m_pFormatCtx->nb_streams; i++) {
av_freep(&m_sEncoderVS.m_pFormatCtx->streams[i]->codec);
av_freep(&m_sEncoderVS.m_pFormatCtx->streams[i]);
};
av_free( m_sEncoderVS.m_pFormatCtx );
};
if (m_sEncoderVS.m_pCodecCtx) {
avcodec_close( m_sEncoderVS.m_pCodecCtx );
avcodec_free_context( &m_sEncoderVS.m_pCodecCtx );
};
if (m_sEncoderVS.m_pFormatOpts) av_free( m_sEncoderVS.m_pFormatOpts );
};
#include <sys/stat.h>
bool servaMediaEncoder::create( CSTR src, CSTR dst, uint8_t fps, int width, int height, CSTR custom ){
char Buffer[1024] = {0};
int RetVal;
if ( !initLibAV() ) return false;
strncpy( m_sDecoderVS.m_pFileName, src, MAX_PATH_LEN);
strncpy( m_sEncoderVS.m_pFileName, dst, MAX_PATH_LEN);
struct stat st;
stat( m_sDecoderVS.m_pFileName, &st );
m_nInFileSize = st.st_size;
//LOG("Before Open1");
if( ( RetVal = avformat_open_input( &m_sDecoderVS.m_pFormatCtx, m_sDecoderVS.m_pFileName, NULL, &m_sDecoderVS.m_pFormatOpts) ) != 0 ){
//av_dict_free(&options);
char tBuffer[1024];
av_strerror( RetVal, tBuffer, 1024 );
sprintf(Buffer, "VideoSource Couldn't open input stream[%s](Code:%d): %s", tBuffer, RetVal, m_sDecoderVS.m_pFileName );
LOG_ERROR(Buffer);
return false;
};
//LOG("After Open1");
AVDictionaryEntry *e;
if( e = av_dict_get( m_sDecoderVS.m_pFormatOpts, "", NULL, AV_DICT_IGNORE_SUFFIX )){
sprintf( Buffer, "Option %s not recognized by the demuxer", e->key );
LOG_ERROR(Buffer);
};
#ifdef DEBUG
LOG("DataStream Opened");
#endif
m_sDecoderVS.m_bStatus = MS_OPENED;
if( avformat_find_stream_info( m_sDecoderVS.m_pFormatCtx, NULL ) < 0 ){
sprintf(Buffer, "Couldn't find stream information: %s", m_sDecoderVS.m_pFileName );
LOG_ERROR( Buffer );
return false;
};
#if ( LIBAVCODEC_VERSION_MAJOR < 58 ) // && ( LIBAVCODEC_VERSION_MINOR < 50 )
for( unsigned int i=0; i < m_sDecoderVS.m_pFormatCtx->nb_streams; i++ ){
//if( m_pVideoState->m_pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ){
if( m_sDecoderVS.m_pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO ){
LOG( "VIDEO stream detected." );
if( m_sDecoderVS.m_iVideoStreamID <0 ){
LOG( "VIDEO stream assigned." );
m_pVideoState->m_iVideoStreamID=i;
};
};
};
if( m_sDecoderVS.m_iVideoStreamID == -1 ){
LOG_ERROR( "Didn't find a video stream.");
return false;
};
// Stream found
m_sDecoderVS.m_pCodecCtx = m_sDecoderVS.m_pFormatCtx->streams[m_sDecoderVS.m_iVideoStreamID]->codec;
//m_pVideoState->m_pFormatCtx->streams[m_pVideoState->m_iVideoStreamID]->codecpar->codec_id
m_sDecoderVS.m_pVideoCodec = avcodec_find_decoder( m_sDecoderVS.m_pCodecCtx->codec_id );
#else
# ifdef DEBUG_EXTRA
LOG("YABABA-2!");
# endif
/* find the video stream information */
m_sDecoderVS.m_iVideoStreamID = av_find_best_stream( m_sDecoderVS.m_pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &m_sDecoderVS.m_pVideoCodec, 0);
if (m_sDecoderVS.m_iVideoStreamID == -1){
LOG_ERROR("Didn't find a video stream.");
return false;
};
if (!(m_sDecoderVS.m_pCodecCtx = avcodec_alloc_context3(m_sDecoderVS.m_pVideoCodec))){
LOG_ERROR("Can not create decoder context!");
return false;
};
m_sDecoderVS.m_pVideoStr = m_sDecoderVS.m_pFormatCtx->streams[m_sDecoderVS.m_iVideoStreamID];
if ( avcodec_parameters_to_context( m_sDecoderVS.m_pCodecCtx, m_sDecoderVS.m_pVideoStr->codecpar ) < 0 ){
LOG_ERROR("Can not set Context parameters!");
return false;
};
#endif
if( m_sDecoderVS.m_pVideoCodec == NULL ){
sprintf(Buffer, "Codec [%d] not found for %s", m_sDecoderVS.m_pCodecCtx->codec_id, m_sDecoderVS.m_pFileName );
LOG_ERROR( Buffer );
return false;
};
/*
End-user application may configure the number of threads to utilize (via AVCodecContext::thread_count property set before avcodec_open2())
and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE).
Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool.
*/
//m_sDecoderVS.m_pCodecCtx->thread_count = 4;
m_sDecoderVS.m_pCodecCtx->thread_type = m_sEncoderSettings.TH_MODE;//FF_THREAD_FRAME;
//if (is_live)
//m_sDecoderVS.m_pCodecCtx->thread_count = FF_THREAD_SLICE;
//else
//m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE | FF_THREAD_FRAME;
#ifdef DEBUG_EXTRA
LOG("Before Open2");
#endif
if( avcodec_open2( m_sDecoderVS.m_pCodecCtx, m_sDecoderVS.m_pVideoCodec, NULL ) < 0 ){
sprintf(Buffer, "Could not open Video codec[%d] for %s", m_sDecoderVS.m_pCodecCtx->codec_id, m_sDecoderVS.m_pFileName );
LOG_ERROR( Buffer );
return false;
};
/* we do not send complete frames */
if( m_sDecoderVS.m_pVideoCodec->capabilities & AV_CODEC_CAP_TRUNCATED ) m_sDecoderVS.m_pCodecCtx->flags |= AV_CODEC_CAP_TRUNCATED;
#ifdef DEBUG
char tB[256];
sprintf( tB, "Setting Frame [%dx%d]", width, height );
LOG( tB );
sprintf( tB, "Source Frame [%dx%d]", m_sDecoderVS.m_pCodecCtx->width, m_sDecoderVS.m_pCodecCtx->height );
LOG( tB );
#endif
/*
if( ( width > 0 ) && ( height > 0 ) ){
m_nOutWidth = width;
m_nOutHeight = height;
} else {
if( m_bSizeIsAutomatic ){
#ifdef DEBUG_EXTRA
LOG("Size is Automatic");
#endif
if(( m_nOutWidth == -1 )&&( m_nOutHeight == -1 )){
m_nOutWidth = m_pVideoState->m_pCodecCtx->width;
m_nOutHeight = m_pVideoState->m_pCodecCtx->height;
} else {
// Proportional
if( m_nOutHeight == -1 ){
float k = ((float)m_pVideoState->m_pCodecCtx->height) / ((float)m_pVideoState->m_pCodecCtx->width);
m_nOutHeight = (int)(((float)m_nOutWidth ) * k );
} else {
float k = ((float)m_pVideoState->m_pCodecCtx->width) / ((float)m_pVideoState->m_pCodecCtx->height);
m_nOutWidth = (int)(((float)m_nOutHeight ) * k );
};
};
} else {
#ifdef DEBUG_EXTRA
LOG("Size is Manual");
#endif
if( ( width > 0 ) && ( height > 0 ) ){
m_nOutWidth = width;
m_nOutHeight = height;
} else {
m_nOutWidth = m_pVideoState->m_pCodecCtx->width;
m_nOutHeight = m_pVideoState->m_pCodecCtx->height;
};
};
};
#ifdef DEBUG_EXTRA
sprintf( tB, "Using Size [%dx%d]", m_nOutWidth, m_nOutHeight );
LOG( tB );
sprintf(tB,"swsPar: IN: %dx%d [%d] OUT: %dx%d [%d] {%d}", m_pVideoState->m_pCodecCtx->width,
m_pVideoState->m_pCodecCtx->height,
m_pVideoState->m_pCodecCtx->pix_fmt,
m_nOutWidth,
m_nOutHeight,
AV_PIX_FMT_BGR24,
SWS_BICUBIC );
LOG( tB );
#endif
m_pVideoState->m_pSwsCtx = sws_getContext(
m_pVideoState->m_pCodecCtx->width,
m_pVideoState->m_pCodecCtx->height,
m_pVideoState->m_pCodecCtx->pix_fmt,
m_nOutWidth,
m_nOutHeight,
AV_PIX_FMT_BGR24,
SWS_BICUBIC, //SWS_FAST_BILINEAR,// | SWS_ACCURATE_RND,//SWS_BILINEAR,//SWS_BICUBIC,
NULL,
NULL,
NULL
);
if ( m_pVideoState->m_pSwsCtx == NULL ){
LOG_ERROR("Error Allocating SwsCtx!");
return false;
};
*/
m_bStatus = DECODER_INIT;
/* Encoder */
m_sEncoderVS.m_pFormatCtx = NULL;
m_sEncoderVS.m_pFormatOpts = NULL;
int ret = avformat_alloc_output_context2( &m_sEncoderVS.m_pFormatCtx, NULL, NULL, m_sEncoderVS.m_pFileName );
if (ret < 0) {
LOG_ERROR("VideoFormat Context Memory Allocation Error");
return false;
};
LOG(m_sEncoderVS.m_pFileName);
m_sEncoderVS.m_pFormatCtx->oformat = av_guess_format( NULL, m_sEncoderVS.m_pFileName, NULL);
if (m_sEncoderVS.m_pFormatCtx->oformat == NULL){
LOG_ERROR("VideoFormat Format Not Guessed!");
return false;
} else {
LOG("Video Container Format Guessed");
};
//In Case mp4
if ( strcasestr( m_sEncoderSettings.CONTAINER, "mp4" ) ) {
if (av_dict_set(&m_sEncoderVS.m_pFormatOpts, "brand", "mp42", 0) < 0) {
LOG_ERROR( "av_dict_set brand!" );
};
};
m_sEncoderVS.m_pVideoStr = avformat_new_stream( m_sEncoderVS.m_pFormatCtx, m_sEncoderVS.m_pVideoCodec );
if( m_sEncoderVS.m_pVideoStr == NULL ){
LOG_ERROR("VideoStream Not Created!");
}else{
LOG("VideoStream is Created");
};
//m_sEncoderVS.m_pVideoCodec = avcodec_find_encoder(av_guess_codec(m_sEncoderVS.m_pFormatCtx->oformat, NULL, m_sEncoderVS.m_pFileName, NULL, AVMEDIA_TYPE_VIDEO));
if ( strcasestr( m_sEncoderSettings.CODEC, "h264" ) ) {
m_sEncoderVS.m_pVideoCodec = avcodec_find_encoder( AV_CODEC_ID_H264 );
} else {
m_sEncoderVS.m_pVideoCodec = avcodec_find_encoder( AV_CODEC_ID_H265 );
};
if( m_sEncoderVS.m_pVideoCodec == NULL ){
LOG_ERROR("VideoCodec Not Found!");
return false;
} else {
LOG("Video Codec Found");
};
m_sEncoderVS.m_pCodecCtx = avcodec_alloc_context3( m_sEncoderVS.m_pVideoCodec );
if (m_sEncoderVS.m_pCodecCtx == NULL){
LOG_ERROR("VideoCodec Context Memory Allocation Error");
return false;
} else {
LOG("Codec Context3 Allocated");
};
m_sEncoderVS.m_pCodecCtx->width = m_sDecoderVS.m_pCodecCtx->width;
m_sEncoderVS.m_pCodecCtx->height = m_sDecoderVS.m_pCodecCtx->height;
//const AVRational dst_fps = { fps, 1 };
m_sEncoderVS.m_pVideoStr->time_base = av_make_q( 1, 10000 );// .num = 1;//av_inv_q(dst_fps);
//m_sEncoderVS.m_pVideoStr->time_base.den = fps;
m_sEncoderVS.m_pVideoStr->r_frame_rate = av_make_q( fps, 1);//.num = fps;
//m_sEncoderVS.m_pVideoStr->r_frame_rate.den = 1;
m_sEncoderVS.m_pVideoStr->avg_frame_rate = av_make_q( fps, 1); //.num = fps;
//m_sEncoderVS.m_pVideoStr->avg_frame_rate.den = 1;
m_sEncoderVS.m_pCodecCtx->time_base = av_make_q( 1, 10000 );//.num = 1;
//m_sEncoderVS.m_pCodecCtx->time_base.den = fps;
m_sEncoderVS.m_pCodecCtx->gop_size = fps << 1; // emit one intra frame every fps*2 frames
m_sEncoderVS.m_pCodecCtx->bit_rate = m_sEncoderSettings.bitrate; //400000;
m_sEncoderVS.m_pCodecCtx->pix_fmt = AV_PIX_FMT_YUV420P;
//if (codec_id == AV_CODEC_ID_H264)
//av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "slow", 0);
av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "preset", m_sEncoderSettings.preset, 0 );
av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "profile", m_sEncoderSettings.profile, 0 );
//m_pCodecCtx->max_b_frames = 1;
//m_pCodecCtx->level = 31;
/// P-frames, generated by referencing data from prev and future frames.
/// [Compression up, CPU usage up]
/// [use 3/gop]
m_sEncoderVS.m_pCodecCtx->max_b_frames = 5;
/// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
/// [use 3–5 ref per P]
m_sEncoderVS.m_pCodecCtx->refs = 3;
/// Compression efficiency (slower -> better quality + higher cpu%)
/// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
/// Set this option to "ultrafast" is critical for realtime encoding
//av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
//av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "fast", 0 );
//av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "preset", "slow", 0 );
/// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
/// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
//av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "crf", "20", 0);
char tBuf[16]; sprintf( tBuf, "%d", m_sEncoderSettings.CRF );
av_opt_set(m_sEncoderVS.m_pCodecCtx->priv_data, "crf", tBuf, 0 );
/// Change settings based upon the specifics of input
/// [psnr, ssim, grain, zerolatency, fastdecode, animation]
/// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
//av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "tune", m_sEncoderSettings.tune, 0);
/// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
/// Because Quicktime (ie. iOS) doesn't support this option
av_opt_set( m_sEncoderVS.m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
if( avcodec_is_open( m_sEncoderVS.m_pCodecCtx ) == 0 ){
LOG("output codec context is closed, opening");
int ret = avcodec_open2( m_sEncoderVS.m_pCodecCtx, m_sEncoderVS.m_pVideoCodec, NULL );
if( ret < 0 ){
LOG_ERROR("Error opening2 encoder");
char buffer[30];
sprintf(buffer, "Error code: %i", ret );
LOG_ERROR(buffer);
return false;
};
} else {
LOG("output codec context is opened");
};
m_sEncoderVS.m_pVideoStr->codec = m_sEncoderVS.m_pCodecCtx; //---->see next page
if (avio_open(&m_sEncoderVS.m_pFormatCtx->pb, m_sEncoderVS.m_pFileName, AVIO_FLAG_WRITE ) < 0){
LOG_ERROR("Could not open output file.");
return false;
};
if (avformat_write_header(m_sEncoderVS.m_pFormatCtx, &m_sEncoderVS.m_pFormatOpts ) < 0){
LOG_ERROR("Error occurred when writing header to output file.");
return false;
};
m_sEncoderVS.m_iVideoStreamID = -1;
#ifdef DEBUG
LOG("Allocation Done");
#endif
m_bStatus = ENCODER_INIT;
return init();
};
void servaMediaEncoder::m_fThreadProc( void ){
AVPacket read_packet;
AVPacket encoded_packet;
uint32_t current_frame_num = 0;
uint32_t frame_count = 0;
uint8_t operc = 0;
uint64_t pack_duration = m_sEncoderVS.m_pCodecCtx->time_base.den / m_sEncoderVS.m_pCodecCtx->time_base.num / m_sEncoderVS.m_pVideoStr->avg_frame_rate.num * m_sEncoderVS.m_pVideoStr->avg_frame_rate.den;
int got_frame;
int test;
m_bStatus = THREAD_INIT;
// Allocate video frame
AVFrame *decoded_frame = av_frame_alloc();
m_bThreadStatus = TH_WORKING;
m_bStatus = ENCODER_ENCODING;
m_nReadSize = 0;
while( av_read_frame( m_sDecoderVS.m_pFormatCtx, &read_packet ) >= 0 && m_bThreadStatus < TH_ENDED ){
m_nReadSize += read_packet.size;
// Is this a packet from the video stream?
if( read_packet.stream_index == m_sDecoderVS.m_iVideoStreamID ){
// Decode video frame
if( avcodec_decode_video2( m_sDecoderVS.m_pCodecCtx, decoded_frame, &got_frame, &read_packet ) < 0 ){
m_bThreadStatus = TH_ENDED;
continue;
};
// Did we get a video frame?
if( got_frame ){
av_init_packet( &encoded_packet );
encoded_packet.data = NULL;
encoded_packet.size = 0;
decoded_frame->pts = (int64_t)current_frame_num * pack_duration;
uint8_t perc = ( 100 * m_nReadSize ) / m_nInFileSize;
if ( operc!= perc ) {
operc == perc;
m_pMaster->updateEncodeStatus(m_nRefID, MEDIA_ENCODE_PROGRESS, perc);
};
if( avcodec_encode_video2( m_sEncoderVS.m_pCodecCtx, &encoded_packet, decoded_frame, &got_frame) < 0 ){
m_bThreadStatus = TH_ENDED;
continue;
};
if( got_frame ){
//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 );
if( m_sEncoderVS.m_pCodecCtx->coded_frame->key_frame ) encoded_packet.flags |= AV_PKT_FLAG_KEY;
encoded_packet.stream_index = m_sEncoderVS.m_pVideoStr->index;
//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 );
encoded_packet.duration = pack_duration;
if( av_interleaved_write_frame( m_sEncoderVS.m_pFormatCtx, &encoded_packet ) < 0 ){
m_bThreadStatus = TH_ENDED;
continue;
} else {
m_nOutFileSize += encoded_packet.size;
current_frame_num++;
};
};
frame_count++;
av_free_packet( &encoded_packet );
};
};
// Free the packet that was allocated by av_read_frame
av_free_packet( &read_packet );
};
// Close the video file
avformat_close_input( &m_sDecoderVS.m_pFormatCtx );
// Free the YUV frame
av_frame_free( &decoded_frame );
av_write_trailer( m_sEncoderVS.m_pFormatCtx );
avio_close( m_sEncoderVS.m_pFormatCtx->pb );
m_pMaster->updateEncodeStatus( m_nRefID, MEDIA_ENCODE_PROGRESS, 100 );
m_pMaster->updateEncodeStatus( m_nRefID, MEDIA_READY, 100 );
unlink( m_sDecoderVS.m_pFileName );
m_bStatus = ENCODER_FINISHED;
};
uint8_t servaMediaEncoder::getStatus(){
return m_bStatus;
};
#undef LOG
#undef LOG_ERROR