core/vidl/vidl_ffmpeg_ostream_v4.txx
Go to the documentation of this file.
00001 // This is core/vidl/vidl_ffmpeg_ostream_v4.txx
00002 #ifndef vidl_ffmpeg_ostream_v4_txx_
00003 #define vidl_ffmpeg_ostream_v4_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 // Update implementation based on
00013 // ffmpeg git hash 139f3ac42dcf24eb8c59af4aaab4e9afdccbc996
00014 //
00015 //-----------------------------------------------------------------------------
00016 
00017 #include "vidl_ffmpeg_init.h"
00018 #include "vidl_ffmpeg_convert.h"
00019 #include "vidl_frame.h"
00020 #include "vidl_convert.h"
00021 #include <vcl_cstring.h>
00022 #include <vcl_climits.h>
00023 #include <vil/vil_memory_chunk.h>
00024 
00025 extern "C" {
00026 #if FFMPEG_IN_SEVERAL_DIRECTORIES
00027 #include <libavformat/avformat.h>
00028 #else
00029 #include <ffmpeg/avformat.h>
00030 #endif
00031 }
00032 
00033 //-----------------------------------------------------------------------------
00034 
00035 
00036 struct vidl_ffmpeg_ostream::pimpl
00037 {
00038   pimpl()
00039   : fmt_cxt_( 0 ),
00040   file_opened_( false ),
00041   codec_opened_( false ),
00042   cur_frame_( 0 ),
00043   video_rc_eq_(NULL)
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 = av_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 = AVMEDIA_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->max_qdiff = params_.video_qdiff_;
00323   video_enc->qblur = params_.video_qblur_;
00324   video_enc->qcompress = params_.video_qcomp_;
00325 
00326   // delete when the stream is closed
00327   os_->video_rc_eq_ = new char[params_.video_rc_eq_.length()+1];
00328   vcl_strcpy(os_->video_rc_eq_, params_.video_rc_eq_.c_str());
00329   video_enc->rc_eq = os_->video_rc_eq_;
00330 
00331   video_enc->debug = params_.debug_;
00332   video_enc->debug_mv = params_.debug_mv_;
00333   video_enc->thread_count = 1;
00334 
00335   video_enc->rc_max_rate = params_.video_rc_max_rate_;
00336   video_enc->rc_min_rate = params_.video_rc_min_rate_;
00337   video_enc->rc_buffer_size = params_.video_rc_buffer_size_;
00338   video_enc->rc_buffer_aggressivity= params_.video_rc_buffer_aggressivity_;
00339   video_enc->rc_initial_cplx= params_.video_rc_initial_cplx_;
00340   video_enc->i_quant_factor = params_.video_i_qfactor_;
00341   video_enc->b_quant_factor = params_.video_b_qfactor_;
00342   video_enc->i_quant_offset = params_.video_i_qoffset_;
00343   video_enc->b_quant_offset = params_.video_b_qoffset_;
00344   video_enc->intra_quant_bias = params_.video_intra_quant_bias_;
00345   video_enc->inter_quant_bias = params_.video_inter_quant_bias_;
00346   video_enc->dct_algo = params_.dct_algo_;
00347   video_enc->idct_algo = params_.idct_algo_;
00348   video_enc->me_threshold= params_.me_threshold_;
00349   video_enc->mb_threshold= params_.mb_threshold_;
00350   video_enc->intra_dc_precision= params_.intra_dc_precision_ - 8;
00351   video_enc->strict_std_compliance = params_.strict_;
00352   video_enc->error_rate = params_.error_rate_;
00353   video_enc->noise_reduction= params_.noise_reduction_;
00354   video_enc->scenechange_threshold= params_.sc_threshold_;
00355   video_enc->me_range = params_.me_range_;
00356   video_enc->coder_type= params_.coder_;
00357   video_enc->context_model= params_.context_;
00358   video_enc->prediction_method= params_.predictor_;
00359 
00360   if (params_.do_psnr_)
00361     video_enc->flags|= CODEC_FLAG_PSNR;
00362 
00363   video_enc->me_method = params_.me_method_;
00364 
00365   // two pass mode
00366   if (params_.do_pass_)
00367   {
00368     if (params_.do_pass_ == 1)
00369     {
00370       video_enc->flags |= CODEC_FLAG_PASS1;
00371     }
00372     else
00373     {
00374       video_enc->flags |= CODEC_FLAG_PASS2;
00375     }
00376   }
00377 
00378   vcl_strncpy( os_->fmt_cxt_->filename, filename_.c_str(), 1023 );
00379 
00380   if ( avio_open( &os_->fmt_cxt_->pb, filename_.c_str(), URL_WRONLY) < 0 )
00381   {
00382     vcl_cerr << "ffmpeg: couldn't open " << filename_ << " for writing\n";
00383     close();
00384     return false;
00385   }
00386   os_->file_opened_ = true;
00387 
00388   //dump_format( os_->fmt_cxt_, 1, filename_, 1 );
00389 
00390   if ( avcodec_open( video_enc, codec ) < 0 )
00391   {
00392     vcl_cerr << "ffmpeg: couldn't open codec\n";
00393     close();
00394     return false;
00395   }
00396   os_->codec_opened_ = true;
00397 
00398   if ( avformat_write_header( os_->fmt_cxt_, NULL ) < 0 )
00399   {
00400     vcl_cerr << "ffmpeg: couldn't write header\n";
00401     close();
00402     return false;
00403   }
00404 
00405   return true;
00406 }
00407 
00408 
00409 //: Close the stream
00410 void
00411 vidl_ffmpeg_ostream::
00412 close()
00413 {
00414   delete os_->video_rc_eq_;
00415   os_->video_rc_eq_ = NULL;
00416 
00417   if ( os_->fmt_cxt_ ) {
00418 
00419     if ( os_->file_opened_ ) {
00420       av_write_trailer( os_->fmt_cxt_ );
00421       avio_close( os_->fmt_cxt_->pb );
00422       os_->file_opened_ = false;
00423     }
00424 
00425     if ( os_->fmt_cxt_->nb_streams > 0 ) {
00426       if ( os_->codec_opened_ ) {
00427         for ( unsigned i = 0; i < os_->fmt_cxt_->nb_streams; ++i ) {
00428           AVCodecContext* codec = os_->fmt_cxt_->streams[i]->codec;
00429           if ( codec->stats_in ) {
00430             av_freep( codec->stats_in );
00431           }
00432           avcodec_close( codec );
00433         }
00434       }
00435       os_->codec_opened_ = false;
00436       for ( unsigned i = 0; i < os_->fmt_cxt_->nb_streams; ++i ) {
00437         av_free( os_->fmt_cxt_->streams[i] );
00438       }
00439     }
00440 
00441     av_free( os_->fmt_cxt_ );
00442     os_->fmt_cxt_ = 0;
00443   }
00444 }
00445 
00446 
00447 //: Return true if the stream is open for writing
00448 bool
00449 vidl_ffmpeg_ostream::
00450 is_open() const
00451 {
00452   return os_->file_opened_;
00453 }
00454 
00455 
00456 //: Write and image to the stream
00457 // \retval false if the image could not be written
00458 bool
00459 vidl_ffmpeg_ostream::
00460 write_frame(const vidl_frame_sptr& frame)
00461 {
00462   if (!is_open()) {
00463     // resize to the first frame
00464     params_.size(frame->ni(),frame->nj());
00465     open();
00466   }
00467 
00468   AVCodecContext* codec = os_->fmt_cxt_->streams[0]->codec;
00469 
00470   if (unsigned( codec->width ) != frame->ni() ||
00471       unsigned( codec->height) != frame->nj() ) {
00472     vcl_cerr << "ffmpeg: Input image has wrong size. Expecting ("
00473              << codec->width << 'x' << codec->height << "), got ("
00474              << frame->ni() << 'x' << frame->nj() << ")\n";
00475     return false;
00476   }
00477 
00478   PixelFormat fmt = vidl_pixel_format_to_ffmpeg(frame->pixel_format());
00479 
00480   vidl_pixel_format target_fmt = vidl_pixel_format_from_ffmpeg(codec->pix_fmt);
00481   static vidl_frame_sptr temp_frame = new vidl_shared_frame(NULL,frame->ni(),frame->nj(),target_fmt);
00482 
00483   AVFrame out_frame;
00484   avcodec_get_frame_defaults( &out_frame );
00485 
00486   // The frame is in the correct format to encode directly
00487   if ( codec->pix_fmt == fmt )
00488   {
00489     avpicture_fill((AVPicture*)&out_frame, (uint8_t*) frame->data(),
00490                    fmt, frame->ni(), frame->nj());
00491   }
00492   else
00493   {
00494     if (!temp_frame->data()) {
00495       unsigned ni = frame->ni();
00496       unsigned nj = frame->nj();
00497       unsigned out_size = vidl_pixel_format_buffer_size(ni,nj,target_fmt);
00498       temp_frame = new vidl_memory_chunk_frame(ni, nj, target_fmt,
00499                                                new vil_memory_chunk(out_size, VIL_PIXEL_FORMAT_BYTE));
00500     }
00501     // try conversion with FFMPEG functions
00502     if (!vidl_ffmpeg_convert(frame, temp_frame)) {
00503       // try conversion with vidl functions
00504       if (!vidl_convert_frame(*frame, *temp_frame)) {
00505         vcl_cout << "unable to convert " << frame->pixel_format() << " to "<<target_fmt<<vcl_endl;
00506         return false;
00507       }
00508     }
00509     avpicture_fill((AVPicture*)&out_frame, (uint8_t*) temp_frame->data(),
00510                    codec->pix_fmt, frame->ni(), frame->nj());
00511   }
00512 
00513   AVPacket pkt;
00514   av_init_packet( &pkt );
00515   pkt.stream_index = 0;
00516 
00517   out_frame.pts = os_->cur_frame_;
00518 
00519   int ret = avcodec_encode_video( codec, (uint8_t*)os_->bit_buf_->data(), os_->bit_buf_->size(), &out_frame );
00520 
00521   if ( ret ) {
00522     pkt.data = (uint8_t*)os_->bit_buf_->data();
00523     pkt.size = ret;
00524     if ( codec->coded_frame ) {
00525       pkt.pts = codec->coded_frame->pts;
00526     }
00527     if ( codec->coded_frame && codec->coded_frame->key_frame ) {
00528       pkt.flags |= AV_PKT_FLAG_KEY;
00529     }
00530     av_interleaved_write_frame( os_->fmt_cxt_, &pkt );
00531   }
00532   else {
00533     return false;
00534   }
00535 
00536   ++os_->cur_frame_;
00537   return true;
00538 }
00539 
00540 #endif // vidl_ffmpeg_ostream_v4_txx_