core/vidl/vidl_ffmpeg_ostream_v3.txx
Go to the documentation of this file.
00001 // This is core/vidl/vidl_ffmpeg_ostream_v3.txx
00002 #ifndef vidl_ffmpeg_ostream_v3_txx_
00003 #define vidl_ffmpeg_ostream_v3_txx_
00004 #include "vidl_ffmpeg_ostream.h"
00005 //:
00006 // \file
00007 // \author Matt Leotta
00008 // \author Amitha Perera
00009 // \author David Law
00010 // \date   26 Jan 2009
00011 //
00012 // Updated for ffmpeg based on -r16810
00013 //
00014 //-----------------------------------------------------------------------------
00015 
00016 #include "vidl_ffmpeg_init.h"
00017 #include "vidl_ffmpeg_convert.h"
00018 #include "vidl_frame.h"
00019 #include "vidl_convert.h"
00020 #include <vcl_cstring.h>
00021 #include <vcl_climits.h>
00022 #include <vil/vil_memory_chunk.h>
00023 
00024 extern "C" {
00025 #if FFMPEG_IN_SEVERAL_DIRECTORIES
00026 #include <libavformat/avformat.h>
00027 #else
00028 #include <ffmpeg/avformat.h>
00029 #endif
00030 }
00031 
00032 //-----------------------------------------------------------------------------
00033 
00034 
00035 struct vidl_ffmpeg_ostream::pimpl
00036 {
00037   pimpl()
00038   : fmt_cxt_( 0 ),
00039     file_opened_( false ),
00040     codec_opened_( false ),
00041     cur_frame_( 0 ),
00042     video_rc_eq_(NULL)
00043   { }
00044 
00045 
00046   AVFormatContext* fmt_cxt_;
00047   bool file_opened_;
00048   bool codec_opened_;
00049   vil_memory_chunk_sptr bit_buf_;
00050   unsigned int cur_frame_;
00051   char* video_rc_eq_;
00052 };
00053 
00054 
00055 //-----------------------------------------------------------------------------
00056 
00057 
00058 //: Constructor
00059 vidl_ffmpeg_ostream::
00060 vidl_ffmpeg_ostream()
00061   : os_( new vidl_ffmpeg_ostream::pimpl )
00062 {
00063   vidl_ffmpeg_init();
00064 }
00065 
00066 
00067 //: Destructor
00068 vidl_ffmpeg_ostream::
00069 ~vidl_ffmpeg_ostream()
00070 {
00071   close();
00072   delete os_;
00073 }
00074 
00075 
00076 //: Constructor - opens a stream
00077 vidl_ffmpeg_ostream::
00078 vidl_ffmpeg_ostream(const vcl_string& filename,
00079                     const vidl_ffmpeg_ostream_params& params)
00080   : os_( new vidl_ffmpeg_ostream::pimpl ),
00081     filename_(filename), params_(params)
00082 {
00083   vidl_ffmpeg_init();
00084 }
00085 
00086 
00087 //: Open the stream
00088 bool
00089 vidl_ffmpeg_ostream::
00090 open()
00091 {
00092   // Close any open files
00093   close();
00094 
00095   // a raw video packet is the same size as the input image. Others
00096   // are smaller.
00097   os_->bit_buf_ = new vil_memory_chunk( params_.ni_ * params_.nj_ * 3, VIL_PIXEL_FORMAT_BYTE );
00098 
00099   os_->fmt_cxt_ = avformat_alloc_context();
00100 
00101   AVOutputFormat* file_oformat = 0;
00102   if ( params_.file_format_ == vidl_ffmpeg_ostream_params::GUESS ) {
00103     file_oformat = guess_format(NULL, filename_.c_str(), NULL);
00104     if (!file_oformat) {
00105       vcl_cerr << "ffmpeg: Unable for find a suitable output format for "
00106                << filename_ << '\n';
00107       close();
00108       return false;
00109     }
00110   }
00111   else {
00112     close();
00113     return false;
00114   }
00115 
00116   os_->fmt_cxt_->oformat = file_oformat;
00117   os_->fmt_cxt_->nb_streams = 0;
00118 
00119   // Create stream
00120   AVStream* st = av_new_stream( os_->fmt_cxt_, 0 );
00121   if ( !st ) {
00122     vcl_cerr << "ffmpeg: could not alloc stream\n";
00123     close();
00124     return false;
00125   }
00126 
00127   //os_->fmt_cxt_->nb_streams = 1;
00128 
00129   AVCodecContext *video_enc = st->codec;
00130 
00131   if (vcl_strcmp(file_oformat->name, "mp4") != 0 ||
00132       vcl_strcmp(file_oformat->name, "mov") != 0 ||
00133       vcl_strcmp(file_oformat->name, "3gp") != 0 )
00134     video_enc->flags |= CODEC_FLAG_GLOBAL_HEADER;
00135 
00136   video_enc->codec_type = CODEC_TYPE_VIDEO;
00137 
00138   switch ( params_.encoder_ )
00139   {
00140    case vidl_ffmpeg_ostream_params::DEFAULT:
00141     video_enc->codec_id = file_oformat->video_codec;
00142     break;
00143    case vidl_ffmpeg_ostream_params::MPEG4:
00144     video_enc->codec_id = CODEC_ID_MPEG4;
00145     break;
00146    case vidl_ffmpeg_ostream_params::MPEG2VIDEO:
00147     video_enc->codec_id = CODEC_ID_MPEG2VIDEO;
00148     break;
00149    case vidl_ffmpeg_ostream_params::MSMPEG4V2:
00150     video_enc->codec_id = CODEC_ID_MSMPEG4V2;
00151     break;
00152    case vidl_ffmpeg_ostream_params::RAWVIDEO:
00153     video_enc->codec_id = CODEC_ID_RAWVIDEO;
00154     break;
00155    case vidl_ffmpeg_ostream_params::LJPEG:
00156     video_enc->codec_id = CODEC_ID_LJPEG;
00157     break;
00158    case vidl_ffmpeg_ostream_params::HUFFYUV:
00159     video_enc->codec_id = CODEC_ID_HUFFYUV;
00160     break;
00161    case vidl_ffmpeg_ostream_params::DVVIDEO:
00162     video_enc->codec_id = CODEC_ID_DVVIDEO;
00163     break;
00164    default:
00165     vcl_cout << "ffmpeg: Unknown encoder type\n";
00166     return false;
00167   }
00168 
00169   AVCodec* codec = avcodec_find_encoder( video_enc->codec_id );
00170   if ( !codec )
00171   {
00172     vcl_cerr << "ffmpeg_writer:: couldn't find encoder for " << video_enc->codec_id << '\n';
00173     return false;
00174   }
00175 
00176   video_enc->bit_rate = params_.bit_rate_ * 1000;
00177   video_enc->bit_rate_tolerance = params_.video_bit_rate_tolerance_;
00178   video_enc->time_base.num = 1000;
00179   video_enc->time_base.den = int(params_.frame_rate_*1000);
00180 
00181   if ( codec && codec->supported_framerates )
00182   {
00183     AVRational const* p = codec->supported_framerates;
00184     AVRational req = { video_enc->time_base.den, video_enc->time_base.num };
00185     AVRational const* best = NULL;
00186     AVRational best_error = { INT_MAX, 1 };
00187     for (; p->den!=0; p++)
00188     {
00189       AVRational error = av_sub_q(req, *p);
00190       if ( error.num < 0 )   error.num *= -1;
00191       if ( av_cmp_q( error, best_error ) < 0 )
00192       {
00193         best_error= error;
00194         best= p;
00195       }
00196     }
00197     video_enc->time_base.den= best->num;
00198     video_enc->time_base.num= best->den;
00199   }
00200 
00201   video_enc->width  = params_.ni_;
00202   video_enc->height = params_.nj_;
00203   video_enc->sample_aspect_ratio = av_d2q(params_.frame_aspect_ratio_*params_.ni_/params_.nj_, 255);
00204 
00205   // Our source is packed RGB. Use that if possible.
00206   video_enc->pix_fmt = PIX_FMT_RGB24;
00207   if ( codec && codec->pix_fmts )
00208   {
00209     const enum PixelFormat* p= codec->pix_fmts;
00210     for ( ; *p != -1; p++ )
00211     {
00212       if ( *p == video_enc->pix_fmt )
00213         break;
00214     }
00215     if ( *p == -1 )
00216       video_enc->pix_fmt = codec->pix_fmts[0];
00217   }
00218   else if ( codec && ( codec->id == CODEC_ID_RAWVIDEO ||
00219                       codec->id == CODEC_ID_HUFFYUV ) )
00220   {
00221     // these formats only support the YUV input image formats
00222     video_enc->pix_fmt = PIX_FMT_YUV420P;
00223   }
00224 
00225   if (!params_.intra_only_)
00226     video_enc->gop_size = params_.gop_size_;
00227   else
00228     video_enc->gop_size = 0;
00229   if (params_.video_qscale_ || params_.same_quality_)
00230   {
00231     video_enc->flags |= CODEC_FLAG_QSCALE;
00232     st->quality = FF_QP2LAMBDA * params_.video_qscale_;
00233   }
00234   // if (bitexact)
00235   //   video_enc->flags |= CODEC_FLAG_BITEXACT;
00236 
00237   video_enc->mb_decision = params_.mb_decision_;
00238   video_enc->mb_cmp = params_.mb_cmp_;
00239   video_enc->ildct_cmp = params_.ildct_cmp_;
00240   video_enc->me_sub_cmp = params_.sub_cmp_;
00241   video_enc->me_cmp = params_.cmp_;
00242   video_enc->me_pre_cmp = params_.pre_cmp_;
00243   video_enc->pre_me = params_.pre_me_;
00244   video_enc->lumi_masking = params_.lumi_mask_;
00245   video_enc->dark_masking = params_.dark_mask_;
00246   video_enc->spatial_cplx_masking = params_.scplx_mask_;
00247   video_enc->temporal_cplx_masking = params_.tcplx_mask_;
00248   video_enc->p_masking = params_.p_mask_;
00249   video_enc->quantizer_noise_shaping= params_.qns_;
00250 
00251   if (params_.use_umv_)
00252   {
00253     video_enc->flags |= CODEC_FLAG_H263P_UMV;
00254   }
00255   if (params_.use_ss_)
00256   {
00257     video_enc->flags |= CODEC_FLAG_H263P_SLICE_STRUCT;
00258   }
00259   if (params_.use_aiv_)
00260   {
00261     video_enc->flags |= CODEC_FLAG_H263P_AIV;
00262   }
00263   if (params_.use_4mv_)
00264   {
00265     video_enc->flags |= CODEC_FLAG_4MV;
00266   }
00267   if (params_.use_obmc_)
00268   {
00269     video_enc->flags |= CODEC_FLAG_OBMC;
00270   }
00271   if (params_.use_loop_)
00272   {
00273     video_enc->flags |= CODEC_FLAG_LOOP_FILTER;
00274   }
00275 
00276   if (params_.use_part_)
00277   {
00278     video_enc->flags |= CODEC_FLAG_PART;
00279   }
00280   if (params_.use_alt_scan_)
00281   {
00282     video_enc->flags |= CODEC_FLAG_ALT_SCAN;
00283   }
00284   if (params_.use_scan_offset_)
00285   {
00286     video_enc->flags |= CODEC_FLAG_SVCD_SCAN_OFFSET;
00287   }
00288   if (params_.closed_gop_)
00289   {
00290     video_enc->flags |= CODEC_FLAG_CLOSED_GOP;
00291   }
00292   if (params_.use_qpel_)
00293   {
00294     video_enc->flags |= CODEC_FLAG_QPEL;
00295   }
00296   if (params_.use_qprd_)
00297   {
00298     video_enc->flags |= CODEC_FLAG_QP_RD;
00299   }
00300   if (params_.use_cbprd_)
00301   {
00302     video_enc->flags |= CODEC_FLAG_CBP_RD;
00303   }
00304   if (params_.b_frames_)
00305   {
00306     video_enc->max_b_frames = params_.b_frames_;
00307     video_enc->b_frame_strategy = 0;
00308     video_enc->b_quant_factor = 2.0;
00309   }
00310   if (params_.do_interlace_dct_)
00311   {
00312     video_enc->flags |= CODEC_FLAG_INTERLACED_DCT;
00313   }
00314   if (params_.do_interlace_me_)
00315   {
00316     video_enc->flags |= CODEC_FLAG_INTERLACED_ME;
00317   }
00318   video_enc->qmin = params_.video_qmin_;
00319   video_enc->qmax = params_.video_qmax_;
00320   video_enc->lmin = params_.video_lmin_;
00321   video_enc->lmax = params_.video_lmax_;
00322   video_enc->mb_qmin = params_.video_mb_qmin_;
00323   video_enc->mb_qmax = params_.video_mb_qmax_;
00324   video_enc->max_qdiff = params_.video_qdiff_;
00325   video_enc->qblur = params_.video_qblur_;
00326   video_enc->qcompress = params_.video_qcomp_;
00327 
00328   // delete when the stream is closed
00329   os_->video_rc_eq_ = new char[params_.video_rc_eq_.length()+1];
00330   vcl_strcpy(os_->video_rc_eq_, params_.video_rc_eq_.c_str());
00331   video_enc->rc_eq = os_->video_rc_eq_;
00332 
00333   video_enc->debug = params_.debug_;
00334   video_enc->debug_mv = params_.debug_mv_;
00335   video_enc->thread_count = 1;
00336 
00337   video_enc->rc_max_rate = params_.video_rc_max_rate_;
00338   video_enc->rc_min_rate = params_.video_rc_min_rate_;
00339   video_enc->rc_buffer_size = params_.video_rc_buffer_size_;
00340   video_enc->rc_buffer_aggressivity= params_.video_rc_buffer_aggressivity_;
00341   video_enc->rc_initial_cplx= params_.video_rc_initial_cplx_;
00342   video_enc->i_quant_factor = params_.video_i_qfactor_;
00343   video_enc->b_quant_factor = params_.video_b_qfactor_;
00344   video_enc->i_quant_offset = params_.video_i_qoffset_;
00345   video_enc->b_quant_offset = params_.video_b_qoffset_;
00346   video_enc->intra_quant_bias = params_.video_intra_quant_bias_;
00347   video_enc->inter_quant_bias = params_.video_inter_quant_bias_;
00348   video_enc->dct_algo = params_.dct_algo_;
00349   video_enc->idct_algo = params_.idct_algo_;
00350   video_enc->me_threshold= params_.me_threshold_;
00351   video_enc->mb_threshold= params_.mb_threshold_;
00352   video_enc->intra_dc_precision= params_.intra_dc_precision_ - 8;
00353   video_enc->strict_std_compliance = params_.strict_;
00354   video_enc->error_rate = params_.error_rate_;
00355   video_enc->noise_reduction= params_.noise_reduction_;
00356   video_enc->scenechange_threshold= params_.sc_threshold_;
00357   video_enc->me_range = params_.me_range_;
00358   video_enc->coder_type= params_.coder_;
00359   video_enc->context_model= params_.context_;
00360   video_enc->prediction_method= params_.predictor_;
00361 
00362   if (params_.do_psnr_)
00363     video_enc->flags|= CODEC_FLAG_PSNR;
00364 
00365   video_enc->me_method = params_.me_method_;
00366 
00367   // two pass mode
00368   if (params_.do_pass_)
00369   {
00370     if (params_.do_pass_ == 1)
00371     {
00372       video_enc->flags |= CODEC_FLAG_PASS1;
00373     }
00374     else
00375     {
00376       video_enc->flags |= CODEC_FLAG_PASS2;
00377     }
00378   }
00379 
00380   os_->fmt_cxt_->timestamp = 0;
00381   os_->fmt_cxt_->title[0] = '\0';
00382   os_->fmt_cxt_->author[0] = '\0';
00383   os_->fmt_cxt_->copyright[0] = '\0';
00384   os_->fmt_cxt_->comment[0] = '\0';
00385 
00386   vcl_strncpy( os_->fmt_cxt_->filename, filename_.c_str(), 1023 );
00387 
00388   if ( url_fopen( &os_->fmt_cxt_->pb, filename_.c_str(), URL_WRONLY) < 0 )
00389   {
00390     vcl_cerr << "ffmpeg: couldn't open " << filename_ << " for writing\n";
00391     close();
00392     return false;
00393   }
00394   os_->file_opened_ = true;
00395 
00396   AVFormatParameters fmt_param;
00397   vcl_memset( &fmt_param, 0, sizeof(fmt_param) );
00398   if ( av_set_parameters( os_->fmt_cxt_, &fmt_param ) < 0 )
00399   {
00400     vcl_cerr << "ffmpeg: invalid encoding parameter\n";
00401     close();
00402     return false;
00403   }
00404 
00405   //dump_format( os_->fmt_cxt_, 1, filename_, 1 );
00406 
00407   if ( avcodec_open( video_enc, codec ) < 0 )
00408   {
00409     vcl_cerr << "ffmpeg: couldn't open codec\n";
00410     close();
00411     return false;
00412   }
00413   os_->codec_opened_ = true;
00414 
00415   if ( av_write_header( os_->fmt_cxt_ ) < 0 )
00416   {
00417     vcl_cerr << "ffmpeg: couldn't write header\n";
00418     close();
00419     return false;
00420   }
00421 
00422   return true;
00423 }
00424 
00425 
00426 //: Close the stream
00427 void
00428 vidl_ffmpeg_ostream::
00429 close()
00430 {
00431   delete os_->video_rc_eq_;
00432   os_->video_rc_eq_ = NULL;
00433 
00434   if ( os_->fmt_cxt_ ) {
00435     if ( os_->file_opened_ ) {
00436       av_write_trailer( os_->fmt_cxt_ );
00437       url_fclose( os_->fmt_cxt_->pb );
00438       os_->file_opened_ = false;
00439     }
00440     if ( os_->fmt_cxt_->nb_streams > 0 ) {
00441       if ( os_->codec_opened_ ) {
00442         for ( unsigned i = 0; i < os_->fmt_cxt_->nb_streams; ++i ) {
00443           AVCodecContext* codec = os_->fmt_cxt_->streams[i]->codec;
00444           if ( codec->stats_in ) {
00445             av_freep( codec->stats_in );
00446           }
00447           avcodec_close( codec );
00448         }
00449       }
00450       os_->codec_opened_ = false;
00451       for ( unsigned i = 0; i < os_->fmt_cxt_->nb_streams; ++i ) {
00452         av_free( os_->fmt_cxt_->streams[i] );
00453       }
00454     }
00455     av_free( os_->fmt_cxt_ );
00456     os_->fmt_cxt_ = 0;
00457   }
00458 }
00459 
00460 
00461 //: Return true if the stream is open for writing
00462 bool
00463 vidl_ffmpeg_ostream::
00464 is_open() const
00465 {
00466   return os_->file_opened_;
00467 }
00468 
00469 
00470 //: Write and image to the stream
00471 // \retval false if the image could not be written
00472 bool
00473 vidl_ffmpeg_ostream::
00474 write_frame(const vidl_frame_sptr& frame)
00475 {
00476   if (!is_open()) {
00477     // resize to the first frame
00478     params_.size(frame->ni(),frame->nj());
00479     open();
00480   }
00481 
00482   AVCodecContext* codec = os_->fmt_cxt_->streams[0]->codec;
00483 
00484   if (unsigned( codec->width ) != frame->ni() ||
00485       unsigned( codec->height) != frame->nj() ) {
00486     vcl_cerr << "ffmpeg: Input image has wrong size. Expecting ("
00487              << codec->width << 'x' << codec->height << "), got ("
00488              << frame->ni() << 'x' << frame->nj() << ")\n";
00489     return false;
00490   }
00491 
00492 
00493   PixelFormat fmt = vidl_pixel_format_to_ffmpeg(frame->pixel_format());
00494 
00495   vidl_pixel_format target_fmt = vidl_pixel_format_from_ffmpeg(codec->pix_fmt);
00496   static vidl_frame_sptr temp_frame = new vidl_shared_frame(NULL,frame->ni(),frame->nj(),target_fmt);
00497 
00498   AVFrame out_frame;
00499   avcodec_get_frame_defaults( &out_frame );
00500 
00501   // The frame is in the correct format to encode directly
00502   if ( codec->pix_fmt == fmt )
00503   {
00504     avpicture_fill((AVPicture*)&out_frame, (uint8_t*) frame->data(),
00505                    fmt, frame->ni(), frame->nj());
00506   }
00507   else
00508   {
00509     if (!temp_frame->data()) {
00510       unsigned ni = frame->ni();
00511       unsigned nj = frame->nj();
00512       unsigned out_size = vidl_pixel_format_buffer_size(ni,nj,target_fmt);
00513       temp_frame = new vidl_memory_chunk_frame(ni, nj, target_fmt,
00514                                                new vil_memory_chunk(out_size, VIL_PIXEL_FORMAT_BYTE));
00515     }
00516     // try conversion with FFMPEG functions
00517     if (!vidl_ffmpeg_convert(frame, temp_frame)) {
00518       // try conversion with vidl functions
00519       if (!vidl_convert_frame(*frame, *temp_frame)) {
00520         vcl_cout << "unable to convert " << frame->pixel_format() << " to "<<target_fmt<<vcl_endl;
00521         return false;
00522       }
00523     }
00524     avpicture_fill((AVPicture*)&out_frame, (uint8_t*) temp_frame->data(),
00525                    codec->pix_fmt, frame->ni(), frame->nj());
00526   }
00527 
00528   AVPacket pkt;
00529   av_init_packet( &pkt );
00530   pkt.stream_index = 0;
00531 
00532   out_frame.pts = os_->cur_frame_;
00533 
00534   int ret = avcodec_encode_video( codec, (uint8_t*)os_->bit_buf_->data(), os_->bit_buf_->size(), &out_frame );
00535 
00536   if ( ret ) {
00537     pkt.data = (uint8_t*)os_->bit_buf_->data();
00538     pkt.size = ret;
00539     if ( codec->coded_frame ) {
00540       pkt.pts = codec->coded_frame->pts;
00541     }
00542     if ( codec->coded_frame && codec->coded_frame->key_frame ) {
00543       pkt.flags |= PKT_FLAG_KEY;
00544     }
00545     av_interleaved_write_frame( os_->fmt_cxt_, &pkt );
00546   }
00547   else {
00548     return false;
00549   }
00550 
00551   ++os_->cur_frame_;
00552   return true;
00553 }
00554 
00555 #endif // vidl_ffmpeg_ostream_v3_txx_