Recherche avancée

Médias (1)

Mot : - Tags -/biographie

Autres articles (48)

  • Mise à jour de la version 0.1 vers 0.2

    24 juin 2013, par

    Explications des différents changements notables lors du passage de la version 0.1 de MediaSPIP à la version 0.3. Quelles sont les nouveautés
    Au niveau des dépendances logicielles Utilisation des dernières versions de FFMpeg (>= v1.2.1) ; Installation des dépendances pour Smush ; Installation de MediaInfo et FFprobe pour la récupération des métadonnées ; On n’utilise plus ffmpeg2theora ; On n’installe plus flvtool2 au profit de flvtool++ ; On n’installe plus ffmpeg-php qui n’est plus maintenu au (...)

  • Personnaliser en ajoutant son logo, sa bannière ou son image de fond

    5 septembre 2013, par

    Certains thèmes prennent en compte trois éléments de personnalisation : l’ajout d’un logo ; l’ajout d’une bannière l’ajout d’une image de fond ;

  • Publier sur MédiaSpip

    13 juin 2013

    Puis-je poster des contenus à partir d’une tablette Ipad ?
    Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir

Sur d’autres sites (10430)

  • increasing memory occupancy while recording screen save to disk with ffmpeg [on hold]

    19 mai 2016, par vbtang

    wonder if there are any resoures i didn’t free ?or do i need to do something special so that i can free these momery ?

    ps. run the demo step by step, and found it has the same problem, until it quit the main function, it still have 40MB memory occupancy. And i found the memory increase obviously in the screen capture thread,but when it increased to about 150MB, it won’t increase, until i quit the program, it will have 40MB memory left. i feel confused.

    pss. i download ffmpeg dev and shared version form here https://ffmpeg.zeranoe.com/builds/,it seems a dll of debug version ? do i need a release version ?
    here is my demo code.

       #include "stdafx.h"

    #ifdef  __cplusplus
    extern "C"
    {
    #endif
    #include "libavcodec/avcodec.h"
    #include "libavformat/avformat.h"
    #include "libswscale/swscale.h"
    #include "libavdevice/avdevice.h"
    #include "libavutil/audio_fifo.h"

    #pragma comment(lib, "avcodec.lib")
    #pragma comment(lib, "avformat.lib")
    #pragma comment(lib, "avutil.lib")
    #pragma comment(lib, "avdevice.lib")
    #pragma comment(lib, "avfilter.lib")

    //#pragma comment(lib, "avfilter.lib")
    //#pragma comment(lib, "postproc.lib")
    //#pragma comment(lib, "swresample.lib")
    #pragma comment(lib, "swscale.lib")
    #ifdef __cplusplus
    };
    #endif

    AVFormatContext *pFormatCtx_Video = NULL, *pFormatCtx_Audio = NULL, *pFormatCtx_Out = NULL;
    AVCodecContext  *pCodecCtx_Video;
    AVCodec         *pCodec_Video;
    AVFifoBuffer    *fifo_video = NULL;
    AVAudioFifo     *fifo_audio = NULL;
    int VideoIndex, AudioIndex;

    CRITICAL_SECTION AudioSection, VideoSection;



    SwsContext *img_convert_ctx;
    int frame_size = 0;

    uint8_t *picture_buf = NULL, *frame_buf = NULL;

    bool bCap = true;

    DWORD WINAPI ScreenCapThreadProc( LPVOID lpParam );
    DWORD WINAPI AudioCapThreadProc( LPVOID lpParam );

    int OpenVideoCapture()
    {
       AVInputFormat *ifmt=av_find_input_format("gdigrab");
       //
       AVDictionary *options = NULL;
       av_dict_set(&options, "framerate", "15", NULL);
       //av_dict_set(&options,"offset_x","20",0);
       //The distance from the top edge of the screen or desktop
       //av_dict_set(&options,"offset_y","40",0);
       //Video frame size. The default is to capture the full screen
       //av_dict_set(&options,"video_size","320x240",0);
       if(avformat_open_input(&pFormatCtx_Video, "desktop", ifmt, &options)!=0)
       {
           printf("Couldn't open input stream.(无法打开视频输入流)\n");
           return -1;
       }
       if(avformat_find_stream_info(pFormatCtx_Video,NULL)<0)
       {
           printf("Couldn't find stream information.(无法获取视频流信息)\n");
           return -1;
       }
       if (pFormatCtx_Video->streams[0]->codec->codec_type != AVMEDIA_TYPE_VIDEO)
       {
           printf("Couldn't find video stream information.(无法获取视频流信息)\n");
           return -1;
       }
       pCodecCtx_Video = pFormatCtx_Video->streams[0]->codec;
       pCodec_Video = avcodec_find_decoder(pCodecCtx_Video->codec_id);
       if(pCodec_Video == NULL)
       {
           printf("Codec not found.(没有找到解码器)\n");
           return -1;
       }
       if(avcodec_open2(pCodecCtx_Video, pCodec_Video, NULL) < 0)
       {
           printf("Could not open codec.(无法打开解码器)\n");
           return -1;
       }



       img_convert_ctx = sws_getContext(pCodecCtx_Video->width, pCodecCtx_Video->height, pCodecCtx_Video->pix_fmt,
           pCodecCtx_Video->width, pCodecCtx_Video->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);

       frame_size = avpicture_get_size(pCodecCtx_Video->pix_fmt, pCodecCtx_Video->width, pCodecCtx_Video->height);
       //
       fifo_video = av_fifo_alloc(30 * avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx_Video->width, pCodecCtx_Video->height));

       return 0;
    }

    static char *dup_wchar_to_utf8(wchar_t *w)
    {
       char *s = NULL;
       int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, 0, 0, 0, 0);
       s = (char *) av_malloc(l);
       if (s)
           WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, 0, 0);
       return s;
    }

    int OpenAudioCapture()
    {
       //
       AVInputFormat *pAudioInputFmt = av_find_input_format("dshow");

       //
       char * psDevName = dup_wchar_to_utf8(L"audio=virtual-audio-capturer");

       if (avformat_open_input(&pFormatCtx_Audio, psDevName, pAudioInputFmt,NULL) < 0)
       {
           printf("Couldn't open input stream.(无法打开音频输入流)\n");
           return -1;
       }

       if(avformat_find_stream_info(pFormatCtx_Audio,NULL)<0)  
           return -1;

       if(pFormatCtx_Audio->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO)
       {
           printf("Couldn't find video stream information.(无法获取音频流信息)\n");
           return -1;
       }

       AVCodec *tmpCodec = avcodec_find_decoder(pFormatCtx_Audio->streams[0]->codec->codec_id);
       if(0 > avcodec_open2(pFormatCtx_Audio->streams[0]->codec, tmpCodec, NULL))
       {
           printf("can not find or open audio decoder!\n");
       }



       return 0;
    }

    int OpenOutPut()
    {
       AVStream *pVideoStream = NULL, *pAudioStream = NULL;
       const char *outFileName = "test.mp4";
       avformat_alloc_output_context2(&pFormatCtx_Out, NULL, NULL, outFileName);

       if (pFormatCtx_Video->streams[0]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
       {
           VideoIndex = 0;
           pVideoStream = avformat_new_stream(pFormatCtx_Out, NULL);

           if (!pVideoStream)
           {
               printf("can not new stream for output!\n");
               return -1;
           }

           //set codec context param
           pVideoStream->codec->codec = avcodec_find_encoder(AV_CODEC_ID_MPEG4);
           pVideoStream->codec->height = pFormatCtx_Video->streams[0]->codec->height;
           pVideoStream->codec->width = pFormatCtx_Video->streams[0]->codec->width;

           pVideoStream->codec->time_base = pFormatCtx_Video->streams[0]->codec->time_base;
           pVideoStream->codec->sample_aspect_ratio = pFormatCtx_Video->streams[0]->codec->sample_aspect_ratio;
           // take first format from list of supported formats
           pVideoStream->codec->pix_fmt = pFormatCtx_Out->streams[VideoIndex]->codec->codec->pix_fmts[0];

           //open encoder
           if (!pVideoStream->codec->codec)
           {
               printf("can not find the encoder!\n");
               return -1;
           }

           if (pFormatCtx_Out->oformat->flags & AVFMT_GLOBALHEADER)
               pVideoStream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;

           if ((avcodec_open2(pVideoStream->codec, pVideoStream->codec->codec, NULL)) < 0)
           {
               printf("can not open the encoder\n");
               return -1;
           }
       }

       if(pFormatCtx_Audio->streams[0]->codec->codec_type == AVMEDIA_TYPE_AUDIO)
       {
           AVCodecContext *pOutputCodecCtx;
           AudioIndex = 1;
           pAudioStream = avformat_new_stream(pFormatCtx_Out, NULL);

           pAudioStream->codec->codec = avcodec_find_encoder(pFormatCtx_Out->oformat->audio_codec);

           pOutputCodecCtx = pAudioStream->codec;

           pOutputCodecCtx->sample_rate = pFormatCtx_Audio->streams[0]->codec->sample_rate;
           pOutputCodecCtx->channel_layout = pFormatCtx_Out->streams[0]->codec->channel_layout;
           pOutputCodecCtx->channels = av_get_channel_layout_nb_channels(pAudioStream->codec->channel_layout);
           if(pOutputCodecCtx->channel_layout == 0)
           {
               pOutputCodecCtx->channel_layout = AV_CH_LAYOUT_STEREO;
               pOutputCodecCtx->channels = av_get_channel_layout_nb_channels(pOutputCodecCtx->channel_layout);

           }
           pOutputCodecCtx->sample_fmt = pAudioStream->codec->codec->sample_fmts[0];
           AVRational time_base={1, pAudioStream->codec->sample_rate};
           pAudioStream->time_base = time_base;
           //audioCodecCtx->time_base = time_base;

           pOutputCodecCtx->codec_tag = 0;  
           if (pFormatCtx_Out->oformat->flags & AVFMT_GLOBALHEADER)  
               pOutputCodecCtx->flags |= CODEC_FLAG_GLOBAL_HEADER;

           if (avcodec_open2(pOutputCodecCtx, pOutputCodecCtx->codec, 0) < 0)
           {
               //
               return -1;
           }
       }

       if (!(pFormatCtx_Out->oformat->flags & AVFMT_NOFILE))
       {
           if(avio_open(&pFormatCtx_Out->pb, outFileName, AVIO_FLAG_WRITE) < 0)
           {
               printf("can not open output file handle!\n");
               return -1;
           }
       }

       if(avformat_write_header(pFormatCtx_Out, NULL) < 0)
       {
           printf("can not write the header of the output file!\n");
           return -1;
       }

       return 0;
    }

    int _tmain(int argc, _TCHAR* argv[])
    {
       av_register_all();
       avdevice_register_all();
       if (OpenVideoCapture() < 0)
       {
           return -1;
       }
       if (OpenAudioCapture() < 0)
       {
           return -1;
       }
       if (OpenOutPut() < 0)
       {
           return -1;
       }

       InitializeCriticalSection(&VideoSection);
       InitializeCriticalSection(&AudioSection);

       AVFrame *picture = av_frame_alloc();
       int size = avpicture_get_size(pFormatCtx_Out->streams[VideoIndex]->codec->pix_fmt,
           pFormatCtx_Out->streams[VideoIndex]->codec->width, pFormatCtx_Out->streams[VideoIndex]->codec->height);
       picture_buf = new uint8_t[size];

       avpicture_fill((AVPicture *)picture, picture_buf,
           pFormatCtx_Out->streams[VideoIndex]->codec->pix_fmt,
           pFormatCtx_Out->streams[VideoIndex]->codec->width,
           pFormatCtx_Out->streams[VideoIndex]->codec->height);



       //star cap screen thread
       CreateThread( NULL, 0, ScreenCapThreadProc, 0, 0, NULL);
       //star cap audio thread
       CreateThread( NULL, 0, AudioCapThreadProc, 0, 0, NULL);
       int64_t cur_pts_v=0,cur_pts_a=0;
       int VideoFrameIndex = 0, AudioFrameIndex = 0;

       while(1)
       {
           if (_kbhit() != 0 && bCap)
           {
               bCap = false;
               Sleep(2000);//
           }
           if (fifo_audio && fifo_video)
           {
               int sizeAudio = av_audio_fifo_size(fifo_audio);
               int sizeVideo = av_fifo_size(fifo_video);
               //
               if (av_audio_fifo_size(fifo_audio) <= pFormatCtx_Out->streams[AudioIndex]->codec->frame_size &&
                   av_fifo_size(fifo_video) <= frame_size && !bCap)
               {
                   break;
               }
           }

           if(av_compare_ts(cur_pts_v, pFormatCtx_Out->streams[VideoIndex]->time_base,
               cur_pts_a,pFormatCtx_Out->streams[AudioIndex]->time_base) <= 0)
           {
               //read data from fifo
               if (av_fifo_size(fifo_video) < frame_size && !bCap)
               {
                   cur_pts_v = 0x7fffffffffffffff;
               }
               if(av_fifo_size(fifo_video) >= size)
               {
                   EnterCriticalSection(&VideoSection);
                   av_fifo_generic_read(fifo_video, picture_buf, size, NULL);
                   LeaveCriticalSection(&VideoSection);

                   avpicture_fill((AVPicture *)picture, picture_buf,
                       pFormatCtx_Out->streams[VideoIndex]->codec->pix_fmt,
                       pFormatCtx_Out->streams[VideoIndex]->codec->width,
                       pFormatCtx_Out->streams[VideoIndex]->codec->height);

                   //pts = n * ((1 / timbase)/ fps);
                   picture->pts = VideoFrameIndex * ((pFormatCtx_Video->streams[0]->time_base.den / pFormatCtx_Video->streams[0]->time_base.num) / 15);

                   int got_picture = 0;
                   AVPacket pkt;
                   av_init_packet(&pkt);

                   pkt.data = NULL;
                   pkt.size = 0;
                   int ret = avcodec_encode_video2(pFormatCtx_Out->streams[VideoIndex]->codec, &pkt, picture, &got_picture);
                   if(ret < 0)
                   {
                       //
                       continue;
                   }

                   if (got_picture==1)
                   {
                       pkt.stream_index = VideoIndex;
                       pkt.pts = av_rescale_q_rnd(pkt.pts, pFormatCtx_Video->streams[0]->time_base,
                           pFormatCtx_Out->streams[VideoIndex]->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));  
                       pkt.dts = av_rescale_q_rnd(pkt.dts,  pFormatCtx_Video->streams[0]->time_base,
                           pFormatCtx_Out->streams[VideoIndex]->time_base, (AVRounding)(AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX));  

                       pkt.duration = ((pFormatCtx_Out->streams[0]->time_base.den / pFormatCtx_Out->streams[0]->time_base.num) / 15);

                       cur_pts_v = pkt.pts;

                       ret = av_interleaved_write_frame(pFormatCtx_Out, &pkt);
                       //delete[] pkt.data;
                       av_free_packet(&pkt);
                   }
                   VideoFrameIndex++;
               }
           }
           else
           {
               if (NULL == fifo_audio)
               {
                   continue;//
               }
               if (av_audio_fifo_size(fifo_audio) < pFormatCtx_Out->streams[AudioIndex]->codec->frame_size && !bCap)
               {
                   cur_pts_a = 0x7fffffffffffffff;
               }
               if(av_audio_fifo_size(fifo_audio) >=
                   (pFormatCtx_Out->streams[AudioIndex]->codec->frame_size > 0 ? pFormatCtx_Out->streams[AudioIndex]->codec->frame_size : 1024))
               {
                   AVFrame *frame;
                   frame = av_frame_alloc();
                   frame->nb_samples = pFormatCtx_Out->streams[AudioIndex]->codec->frame_size>0 ? pFormatCtx_Out->streams[AudioIndex]->codec->frame_size: 1024;
                   frame->channel_layout = pFormatCtx_Out->streams[AudioIndex]->codec->channel_layout;
                   frame->format = pFormatCtx_Out->streams[AudioIndex]->codec->sample_fmt;
                   frame->sample_rate = pFormatCtx_Out->streams[AudioIndex]->codec->sample_rate;
                   av_frame_get_buffer(frame, 0);

                   EnterCriticalSection(&AudioSection);
                   av_audio_fifo_read(fifo_audio, (void **)frame->data,
                       (pFormatCtx_Out->streams[AudioIndex]->codec->frame_size > 0 ? pFormatCtx_Out->streams[AudioIndex]->codec->frame_size : 1024));
                   LeaveCriticalSection(&AudioSection);

                   if (pFormatCtx_Out->streams[0]->codec->sample_fmt != pFormatCtx_Audio->streams[AudioIndex]->codec->sample_fmt
                       || pFormatCtx_Out->streams[0]->codec->channels != pFormatCtx_Audio->streams[AudioIndex]->codec->channels
                       || pFormatCtx_Out->streams[0]->codec->sample_rate != pFormatCtx_Audio->streams[AudioIndex]->codec->sample_rate)
                   {
                       //
                   }

                   AVPacket pkt_out;
                   av_init_packet(&pkt_out);
                   int got_picture = -1;
                   pkt_out.data = NULL;
                   pkt_out.size = 0;

                   frame->pts = AudioFrameIndex * pFormatCtx_Out->streams[AudioIndex]->codec->frame_size;
                   if (avcodec_encode_audio2(pFormatCtx_Out->streams[AudioIndex]->codec, &pkt_out, frame, &got_picture) < 0)
                   {
                       printf("can not decoder a frame");
                   }
                   av_frame_free(&frame);
                   if (got_picture)
                   {
                       pkt_out.stream_index = AudioIndex;
                       pkt_out.pts = AudioFrameIndex * pFormatCtx_Out->streams[AudioIndex]->codec->frame_size;
                       pkt_out.dts = AudioFrameIndex * pFormatCtx_Out->streams[AudioIndex]->codec->frame_size;
                       pkt_out.duration = pFormatCtx_Out->streams[AudioIndex]->codec->frame_size;

                       cur_pts_a = pkt_out.pts;

                       int ret = av_interleaved_write_frame(pFormatCtx_Out, &pkt_out);
                       av_free_packet(&pkt_out);
                   }
                   AudioFrameIndex++;
               }
           }
       }

       delete[] picture_buf;

       delete[]frame_buf;
       av_fifo_free(fifo_video);
       av_audio_fifo_free(fifo_audio);

       av_write_trailer(pFormatCtx_Out);

       avio_close(pFormatCtx_Out->pb);
       avformat_free_context(pFormatCtx_Out);

       if (pFormatCtx_Video != NULL)
       {
           avformat_close_input(&pFormatCtx_Video);
           pFormatCtx_Video = NULL;
       }
       if (pFormatCtx_Audio != NULL)
       {
           avformat_close_input(&pFormatCtx_Audio);
           pFormatCtx_Audio = NULL;
       }
       if (NULL != img_convert_ctx)
       {
           sws_freeContext(img_convert_ctx);
           img_convert_ctx = NULL;
       }

       return 0;
    }

    DWORD WINAPI ScreenCapThreadProc( LPVOID lpParam )
    {
       AVPacket packet;/* = (AVPacket *)av_malloc(sizeof(AVPacket))*/;
       int got_picture;
       AVFrame *pFrame;
       pFrame= av_frame_alloc();

       AVFrame *picture = av_frame_alloc();
       int size = avpicture_get_size(pFormatCtx_Out->streams[VideoIndex]->codec->pix_fmt,
           pFormatCtx_Out->streams[VideoIndex]->codec->width, pFormatCtx_Out->streams[VideoIndex]->codec->height);
       //picture_buf = new uint8_t[size];

       avpicture_fill((AVPicture *)picture, picture_buf,
           pFormatCtx_Out->streams[VideoIndex]->codec->pix_fmt,
           pFormatCtx_Out->streams[VideoIndex]->codec->width,
           pFormatCtx_Out->streams[VideoIndex]->codec->height);

    //  FILE *p = NULL;
    //  p = fopen("proc_test.yuv", "wb+");
       av_init_packet(&packet);
       int height = pFormatCtx_Out->streams[VideoIndex]->codec->height;
       int width = pFormatCtx_Out->streams[VideoIndex]->codec->width;
       int y_size=height*width;
       while(bCap)
       {
           packet.data = NULL;
           packet.size = 0;
           if (av_read_frame(pFormatCtx_Video, &packet) < 0)
           {
               av_free_packet(&packet);
               continue;
           }
           if(packet.stream_index == 0)
           {
               if (avcodec_decode_video2(pCodecCtx_Video, pFrame, &got_picture, &packet) < 0)
               {
                   printf("Decode Error.(解码错误)\n");
                   continue;
               }
               if (got_picture)
               {
                   sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0,
                       pFormatCtx_Out->streams[VideoIndex]->codec->height, picture->data, picture->linesize);

                   if (av_fifo_space(fifo_video) >= size)
                   {
                       EnterCriticalSection(&VideoSection);                    
                       av_fifo_generic_write(fifo_video, picture->data[0], y_size, NULL);
                       av_fifo_generic_write(fifo_video, picture->data[1], y_size/4, NULL);
                       av_fifo_generic_write(fifo_video, picture->data[2], y_size/4, NULL);
                       LeaveCriticalSection(&VideoSection);
                   }
               }
           }
           av_free_packet(&packet);
           //Sleep(50);
       }
       av_frame_free(&pFrame);
       av_frame_free(&picture);
       //delete[] picture_buf;
       return 0;
    }

    DWORD WINAPI AudioCapThreadProc( LPVOID lpParam )
    {
       AVPacket pkt;
       AVFrame *frame;
       frame = av_frame_alloc();
       int gotframe;
       while(bCap)
       {
           pkt.data = NULL;
           pkt.size = 0;
           if(av_read_frame(pFormatCtx_Audio,&pkt) < 0)
           {
               av_free_packet(&pkt);
               continue;
           }

           if (avcodec_decode_audio4(pFormatCtx_Audio->streams[0]->codec, frame, &gotframe, &pkt) < 0)
           {
               av_frame_free(&frame);
               printf("can not decoder a frame");
               break;
           }
           av_free_packet(&pkt);

           if (!gotframe)
           {
               continue;//
           }

           if (NULL == fifo_audio)
           {
               fifo_audio = av_audio_fifo_alloc(pFormatCtx_Audio->streams[0]->codec->sample_fmt,
                   pFormatCtx_Audio->streams[0]->codec->channels, 30 * frame->nb_samples);
           }

           int buf_space = av_audio_fifo_space(fifo_audio);
           if (av_audio_fifo_space(fifo_audio) >= frame->nb_samples)
           {
               EnterCriticalSection(&AudioSection);
               av_audio_fifo_write(fifo_audio, (void **)frame->data, frame->nb_samples);
               LeaveCriticalSection(&AudioSection);
           }
       }
       av_frame_free(&frame);
       return 0;
    }
  • How to resample an audio with ffmpeg API ?

    13 mai 2016, par tangren

    I’d like to decode audio file(.wav .aac etc.) into raw data(pcm) and then resample it with ffmpeg API.

    I try to do it with the help of the official examples. However, the result file always loses a little data at the end of the file compared to the file generated by ffmpeg command :

    ffmpeg -i audio.wav -f s16le -ac 1 -ar 8000 -acodec pcm_s16le out.pcm.

    In this case, the input audio metadata : pcm_s16le, 16000 Hz, 1 channels, s16, 256 kb/s

    And there are 32 bites lost at the end of result file.

    What’s more, I’d like to process audios in memory, so how do I calculate the size of audio’s raw data (pcm) ?

    My code :

    #include <libavutil></libavutil>opt.h>
    #include <libavutil></libavutil>imgutils.h>
    #include <libavutil></libavutil>samplefmt.h>
    #include <libavutil></libavutil>timestamp.h>
    #include <libavformat></libavformat>avformat.h>
    #include <libavutil></libavutil>channel_layout.h>
    #include <libswresample></libswresample>swresample.h>

    int convert_to_PCM(const char* src_audio_filename, const char* dst_pcm_filename, int dst_sample_rate)
    {
       FILE *audio_dst_file = NULL;

       // for demuxing and decoding
       int ret = 0, got_frame, decoded, tmp;
       AVFormatContext *fmt_ctx = NULL;
       AVCodecContext *audio_dec_ctx;
       AVStream *audio_stream = NULL;
       int audio_stream_idx = -1;
       AVFrame *frame = NULL;
       AVPacket pkt;

       // for resampling
       struct SwrContext *swr_ctx = NULL;
       int src_sample_rate;
       uint8_t **dst_data = NULL;
       int dst_nb_samples, max_dst_nb_samples;
       enum AVSampleFormat src_sample_fmt, dst_sample_fmt = AV_SAMPLE_FMT_S16;
       int nb_channels = 1;
       int dst_bufsize, dst_linesize;
       int64_t src_ch_layout, dst_ch_layout;
       dst_ch_layout = src_ch_layout = av_get_default_channel_layout(1);

       av_register_all();

       if (avformat_open_input(&amp;fmt_ctx, src_audio_filename, NULL, NULL) &lt; 0) {
           fprintf(stderr, "Could not open source file %s\n", src_audio_filename);
           return 1;
       }

       /* retrieve stream information */
       if (avformat_find_stream_info(fmt_ctx, NULL) &lt; 0) {
           fprintf(stderr, "Could not find stream information\n");
           return 1;
       }

       if (open_codec_context(&amp;audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
           audio_stream = fmt_ctx->streams[audio_stream_idx];
           audio_dec_ctx = audio_stream->codec;
           audio_dst_file = fopen(dst_pcm_filename, "wb");
           if (!audio_dst_file) {
               fprintf(stderr, "Could not open destination file %s\n", dst_pcm_filename);
               ret = 1;
               goto end;
           }
       }

       /* dump input information to stderr */
       av_dump_format(fmt_ctx, 0, src_audio_filename, 0);

       if (!audio_stream) {
           fprintf(stderr, "Could not find audio stream in the input, aborting\n");
           ret = 1;
           goto end;
       }

       src_sample_rate = audio_dec_ctx->sample_rate;
       if (src_sample_rate != dst_sample_rate) {
           /* create resampler context */
           swr_ctx = swr_alloc();
           if (!swr_ctx) {
               fprintf(stderr, "Could not allocate resampler context\n");
               ret = AVERROR(ENOMEM);
               goto end;
           }
           src_sample_fmt = audio_dec_ctx->sample_fmt;


           /* set options */
           av_opt_set_int(swr_ctx, "in_channel_layout",    src_ch_layout, 0);
           av_opt_set_int(swr_ctx, "in_sample_rate",       src_sample_rate, 0);
           av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", src_sample_fmt, 0);

           av_opt_set_int(swr_ctx, "out_channel_layout",    dst_ch_layout, 0);
           av_opt_set_int(swr_ctx, "out_sample_rate",       dst_sample_rate, 0);
           av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", dst_sample_fmt, 0);

           /* initialize the resampling context */
           if ((ret = swr_init(swr_ctx)) &lt; 0) {
               fprintf(stderr, "Failed to initialize the resampling context\n");
               goto end;
           }

       }

       frame = av_frame_alloc();
       if (!frame) {
           fprintf(stderr, "Could not allocate frame\n");
           ret = AVERROR(ENOMEM);
           goto end;
       }

       /* initialize packet, set data to NULL, let the demuxer fill it */
       av_init_packet(&amp;pkt);
       pkt.data = NULL;
       pkt.size = 0;

       printf("Convert audio from file '%s' into '%s'\n", src_audio_filename, dst_pcm_filename);

       /* read frames from the file */
       while (av_read_frame(fmt_ctx, &amp;pkt) >= 0) {
           AVPacket orig_pkt = pkt;
           do {
               decoded = pkt.size;
               got_frame = 0;
               tmp = 0;
               /* decode audio frame */
               tmp = avcodec_decode_audio4(audio_dec_ctx, frame, &amp;got_frame, &amp;pkt);
               if (tmp &lt; 0) {
                   fprintf(stderr, "Error decoding audio frame (%s)\n", av_err2str(tmp));
                   break;
               }
               decoded = FFMIN(tmp, pkt.size);
               if (got_frame) {
                   if (swr_ctx) {
                       if (dst_data == NULL) {
                           max_dst_nb_samples = dst_nb_samples = av_rescale_rnd(frame->nb_samples, dst_sample_rate, src_sample_rate, AV_ROUND_UP);
                           ret = av_samples_alloc_array_and_samples(&amp;dst_data, &amp;dst_linesize, nb_channels,
                                                                   dst_nb_samples, dst_sample_fmt, 0);
                           if (ret &lt; 0) {
                               fprintf(stderr, "Could not allocate destination samples\n");
                               goto end;
                           }
                       }
                       dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, src_sample_rate) + frame->nb_samples, dst_sample_rate, src_sample_rate, AV_ROUND_UP);
                       if (dst_nb_samples > max_dst_nb_samples) {
                           av_freep(&amp;dst_data[0]);
                           ret = av_samples_alloc(dst_data, &amp;dst_linesize, nb_channels, dst_nb_samples, dst_sample_fmt, 1);
                           if (ret &lt; 0)
                               break;
                           max_dst_nb_samples = dst_nb_samples;
                       }

                       /* convert to destination format */
                       ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)frame->data, frame->nb_samples);
                       if (ret &lt; 0) {
                           fprintf(stderr, "Error while converting\n");
                           goto end;
                       }
                       dst_bufsize = av_samples_get_buffer_size(&amp;dst_linesize, nb_channels, ret, dst_sample_fmt, 1);
                       if (dst_bufsize &lt; 0) {
                           fprintf(stderr, "Could not get sample buffer size\n");
                           goto end;
                       }
                       printf("Decoded size: %d, dst_nb_samples: %d, converted size: %d, sample buffer size: %d\n", decoded, dst_nb_samples, ret, dst_bufsize);
                       fwrite(dst_data[0], 1, dst_bufsize, audio_dst_file);
                   }
                   else {
                       size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
                       fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);
                   }
               }

               if (decoded &lt; 0)
                   break;
               pkt.data += tmp;
               pkt.size -= tmp;
           } while (pkt.size > 0);
           av_packet_unref(&amp;orig_pkt);
       }

       printf("Convert succeeded.\n");

    end:
       avcodec_close(audio_dec_ctx);
       avformat_close_input(&amp;fmt_ctx);
       if (audio_dst_file)
           fclose(audio_dst_file);
       av_frame_free(&amp;frame);
       if (dst_data)
           av_freep(&amp;dst_data[0]);
       av_freep(&amp;dst_data);
       swr_free(&amp;swr_ctx);

       return ret;
    }

    static int open_codec_context(int *stream_idx,
                               AVFormatContext *fmt_ctx, enum AVMediaType type)
    {
       int ret, stream_index;
       AVStream *st;
       AVCodecContext *dec_ctx = NULL;
       AVCodec *dec = NULL;
       AVDictionary *opts = NULL;

       ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
       if (ret &lt; 0) {
           fprintf(stderr, "Could not find %s stream in input file.\n",
                   av_get_media_type_string(type));
           return ret;
       } else {
           stream_index = ret;
           st = fmt_ctx->streams[stream_index];

           /* find decoder for the stream */
           dec_ctx = st->codec;
           dec = avcodec_find_decoder(dec_ctx->codec_id);
           if (!dec) {
               fprintf(stderr, "Failed to find %s codec\n",
                       av_get_media_type_string(type));
               return AVERROR(EINVAL);
           }

           if ((ret = avcodec_open2(dec_ctx, dec, &amp;opts)) &lt; 0) {
               fprintf(stderr, "Failed to open %s codec\n",
                       av_get_media_type_string(type));
               return ret;
           }
           *stream_idx = stream_index;
       }

       return 0;
    }

    static int get_format_from_sample_fmt(const char **fmt,
                                       enum AVSampleFormat sample_fmt)
    {
       int i;
       struct sample_fmt_entry {
           enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
       } sample_fmt_entries[] = {
           { AV_SAMPLE_FMT_U8,  "u8",    "u8"    },
           { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
           { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
           { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
           { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
       };
       *fmt = NULL;

       for (i = 0; i &lt; FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
           struct sample_fmt_entry *entry = &amp;sample_fmt_entries[i];
           if (sample_fmt == entry->sample_fmt) {
               *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
               return 0;
           }
       }

       fprintf(stderr,
               "sample format %s is not supported as output format\n",
               av_get_sample_fmt_name(sample_fmt));
       return -1;
    }
  • Encoding Exception during Transcode with audio files

    6 mai 2016, par Hakop Zakaryan

    I am attempting to transcode using an FFMPEG Wrapper Library called JAVE on Mac OSX 10.11.3 using Eclipse 4.50

    My Converter.java class looks something like this :

    package matador;

    import it.sauronsoftware.jave.AudioAttributes;
    import it.sauronsoftware.jave.EncodingAttributes;
    import it.sauronsoftware.jave.EncoderException;
    import it.sauronsoftware.jave.InputFormatException;
    import it.sauronsoftware.jave.Encoder;
    import java.io.*;

    public class Converter {

    public static void main(String[] args) throws InputFormatException, EncoderException {

       File source = new File("Classic.m4a");
       File target = new File("target.mp3");

       AudioAttributes audio = new AudioAttributes();
       audio.setCodec("libmp3lame");
       audio.setBitRate(new Integer(128000));
       audio.setChannels(new Integer(2));
       audio.setSamplingRate(new Integer(44100));

       EncodingAttributes attrs = new EncodingAttributes();
       attrs.setFormat("mp3");
       attrs.setAudioAttributes(audio);

       Encoder encoder = new Encoder(new MyFFMPEGExecutableLocator());
       try {
       encoder.encode(source, target, attrs, null);
       } catch (IllegalArgumentException e) {

           e.printStackTrace();
       } catch (InputFormatException e) {

           e.printStackTrace();
       } catch (EncoderException e) {

           e.printStackTrace();
       }

    }

    }

    The problem I am running into is that with specific audio files (regardless of format) give me this EncoderException :

    it.sauronsoftware.jave.EncoderException:   Metadata:
    at it.sauronsoftware.jave.Encoder.encode(Encoder.java:863)
    at matador.Converter.main(Converter.java:32)

    I have looked through Encoder.java and the EncoderException on line 863 is this specific code :

    } else if (!line.startsWith("Output #0")) {
    throw new EncoderException(line);

    I have been unable to figure out why this may be occurring but specific audio files (WAV/AAC/etc) do encode yet a majority just give this exception.

    Thank you for the help !

    Edit : As per request for possibly being able to help me further, here is the entirety of the Encoder.java code :

    package it.sauronsoftware.jave;

    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Hashtable;
    import java.util.StringTokenizer;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class Encoder {

    private static final Pattern FORMAT_PATTERN = Pattern
           .compile("^\\s*([D ])([E ])\\s+([\\w,]+)\\s+.+$");

    private static final Pattern ENCODER_DECODER_PATTERN = Pattern.compile(
           "^\\s*([D ])([E ])([AVS]).{3}\\s+(.+)$", Pattern.CASE_INSENSITIVE);

    private static final Pattern PROGRESS_INFO_PATTERN = Pattern.compile(
           "\\s*(\\w+)\\s*=\\s*(\\S+)\\s*", Pattern.CASE_INSENSITIVE);

    private static final Pattern SIZE_PATTERN = Pattern.compile(
           "(\\d+)x(\\d+)", Pattern.CASE_INSENSITIVE);

    private static final Pattern FRAME_RATE_PATTERN = Pattern.compile(
           "([\\d.]+)\\s+(?:fps|tb\\(r\\))", Pattern.CASE_INSENSITIVE);

    private static final Pattern BIT_RATE_PATTERN = Pattern.compile(
           "(\\d+)\\s+kb/s", Pattern.CASE_INSENSITIVE);

    private static final Pattern SAMPLING_RATE_PATTERN = Pattern.compile(
           "(\\d+)\\s+Hz", Pattern.CASE_INSENSITIVE);

    private static final Pattern CHANNELS_PATTERN = Pattern.compile(
           "(mono|stereo)", Pattern.CASE_INSENSITIVE);

    private static final Pattern SUCCESS_PATTERN = Pattern.compile(
           "^\\s*video\\:\\S+\\s+audio\\:\\S+\\s+global headers\\:\\S+.*$",
           Pattern.CASE_INSENSITIVE);

    private FFMPEGLocator locator;

    public Encoder() {
       this.locator = new DefaultFFMPEGLocator();
    }

    public Encoder(FFMPEGLocator locator) {
       this.locator = locator;
    }

    public String[] getAudioDecoders() throws EncoderException {
       ArrayList res = new ArrayList();
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       ffmpeg.addArgument("-formats");
       try {
           ffmpeg.execute();
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getInputStream()));
           String line;
           boolean evaluate = false;
           while ((line = reader.readLine()) != null) {
               if (line.trim().length() == 0) {
                   continue;
               }
               if (evaluate) {
                   Matcher matcher = ENCODER_DECODER_PATTERN.matcher(line);
                   if (matcher.matches()) {
                       String decoderFlag = matcher.group(1);
                       String audioVideoFlag = matcher.group(3);
                       if ("D".equals(decoderFlag)
                               &amp;&amp; "A".equals(audioVideoFlag)) {
                           String name = matcher.group(4);
                           res.add(name);
                       }
                   } else {
                       break;
                   }
               } else if (line.trim().equals("Codecs:")) {
                   evaluate = true;
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       } finally {
           ffmpeg.destroy();
       }
       int size = res.size();
       String[] ret = new String[size];
       for (int i = 0; i &lt; size; i++) {
           ret[i] = (String) res.get(i);
       }
       return ret;
    }

    public String[] getAudioEncoders() throws EncoderException {
       ArrayList res = new ArrayList();
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       ffmpeg.addArgument("-formats");
       try {
           ffmpeg.execute();
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getInputStream()));
           String line;
           boolean evaluate = false;
           while ((line = reader.readLine()) != null) {
               if (line.trim().length() == 0) {
                   continue;
               }
               if (evaluate) {
                   Matcher matcher = ENCODER_DECODER_PATTERN.matcher(line);
                   if (matcher.matches()) {
                       String encoderFlag = matcher.group(2);
                       String audioVideoFlag = matcher.group(3);
                       if ("E".equals(encoderFlag)
                               &amp;&amp; "A".equals(audioVideoFlag)) {
                           String name = matcher.group(4);
                           res.add(name);
                       }
                   } else {
                       break;
                   }
               } else if (line.trim().equals("Codecs:")) {
                   evaluate = true;
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       } finally {
           ffmpeg.destroy();
       }
       int size = res.size();
       String[] ret = new String[size];
       for (int i = 0; i &lt; size; i++) {
           ret[i] = (String) res.get(i);
       }
       return ret;
    }

    public String[] getVideoDecoders() throws EncoderException {
       ArrayList res = new ArrayList();
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       ffmpeg.addArgument("-formats");
       try {
           ffmpeg.execute();
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getInputStream()));
           String line;
           boolean evaluate = false;
           while ((line = reader.readLine()) != null) {
               if (line.trim().length() == 0) {
                   continue;
               }
               if (evaluate) {
                   Matcher matcher = ENCODER_DECODER_PATTERN.matcher(line);
                   if (matcher.matches()) {
                       String decoderFlag = matcher.group(1);
                       String audioVideoFlag = matcher.group(3);
                       if ("D".equals(decoderFlag)
                               &amp;&amp; "V".equals(audioVideoFlag)) {
                           String name = matcher.group(4);
                           res.add(name);
                       }
                   } else {
                       break;
                   }
               } else if (line.trim().equals("Codecs:")) {
                   evaluate = true;
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       } finally {
           ffmpeg.destroy();
       }
       int size = res.size();
       String[] ret = new String[size];
       for (int i = 0; i &lt; size; i++) {
           ret[i] = (String) res.get(i);
       }
       return ret;
    }

    public String[] getVideoEncoders() throws EncoderException {
       ArrayList res = new ArrayList();
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       ffmpeg.addArgument("-formats");
       try {
           ffmpeg.execute();
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getInputStream()));
           String line;
           boolean evaluate = false;
           while ((line = reader.readLine()) != null) {
               if (line.trim().length() == 0) {
                   continue;
               }
               if (evaluate) {
                   Matcher matcher = ENCODER_DECODER_PATTERN.matcher(line);
                   if (matcher.matches()) {
                       String encoderFlag = matcher.group(2);
                       String audioVideoFlag = matcher.group(3);
                       if ("E".equals(encoderFlag)
                               &amp;&amp; "V".equals(audioVideoFlag)) {
                           String name = matcher.group(4);
                           res.add(name);
                       }
                   } else {
                       break;
                   }
               } else if (line.trim().equals("Codecs:")) {
                   evaluate = true;
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       } finally {
           ffmpeg.destroy();
       }
       int size = res.size();
       String[] ret = new String[size];
       for (int i = 0; i &lt; size; i++) {
           ret[i] = (String) res.get(i);
       }
       return ret;
    }

    public String[] getSupportedEncodingFormats() throws EncoderException {
       ArrayList res = new ArrayList();
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       ffmpeg.addArgument("-formats");
       try {
           ffmpeg.execute();
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getInputStream()));
           String line;
           boolean evaluate = false;
           while ((line = reader.readLine()) != null) {
               if (line.trim().length() == 0) {
                   continue;
               }
               if (evaluate) {
                   Matcher matcher = FORMAT_PATTERN.matcher(line);
                   if (matcher.matches()) {
                       String encoderFlag = matcher.group(2);
                       if ("E".equals(encoderFlag)) {
                           String aux = matcher.group(3);
                           StringTokenizer st = new StringTokenizer(aux, ",");
                           while (st.hasMoreTokens()) {
                               String token = st.nextToken().trim();
                               if (!res.contains(token)) {
                                   res.add(token);
                               }
                           }
                       }
                   } else {
                       break;
                   }
               } else if (line.trim().equals("File formats:")) {
                   evaluate = true;
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       } finally {
           ffmpeg.destroy();
       }
       int size = res.size();
       String[] ret = new String[size];
       for (int i = 0; i &lt; size; i++) {
           ret[i] = (String) res.get(i);
       }
       return ret;
    }

    public String[] getSupportedDecodingFormats() throws EncoderException {
       ArrayList res = new ArrayList();
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       ffmpeg.addArgument("-formats");
       try {
           ffmpeg.execute();
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getInputStream()));
           String line;
           boolean evaluate = false;
           while ((line = reader.readLine()) != null) {
               if (line.trim().length() == 0) {
                   continue;
               }
               if (evaluate) {
                   Matcher matcher = FORMAT_PATTERN.matcher(line);
                   if (matcher.matches()) {
                       String decoderFlag = matcher.group(1);
                       if ("D".equals(decoderFlag)) {
                           String aux = matcher.group(3);
                           StringTokenizer st = new StringTokenizer(aux, ",");
                           while (st.hasMoreTokens()) {
                               String token = st.nextToken().trim();
                               if (!res.contains(token)) {
                                   res.add(token);
                               }
                           }
                       }
                   } else {
                       break;
                   }
               } else if (line.trim().equals("File formats:")) {
                   evaluate = true;
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       } finally {
           ffmpeg.destroy();
       }
       int size = res.size();
       String[] ret = new String[size];
       for (int i = 0; i &lt; size; i++) {
           ret[i] = (String) res.get(i);
       }
       return ret;
    }

    public MultimediaInfo getInfo(File source) throws InputFormatException,
           EncoderException {
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       ffmpeg.addArgument("-i");
       ffmpeg.addArgument(source.getAbsolutePath());
       try {
           ffmpeg.execute();
       } catch (IOException e) {
           throw new EncoderException(e);
       }
       try {
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getErrorStream()));
           return parseMultimediaInfo(source, reader);
       } finally {
           ffmpeg.destroy();
       }
    }

    private MultimediaInfo parseMultimediaInfo(File source,
           RBufferedReader reader) throws InputFormatException,
           EncoderException {
       Pattern p1 = Pattern.compile("^\\s*Input #0, (\\w+).+$\\s*",
               Pattern.CASE_INSENSITIVE);
       Pattern p2 = Pattern.compile(
               "^\\s*Duration: (\\d\\d):(\\d\\d):(\\d\\d)\\.(\\d).*$",
               Pattern.CASE_INSENSITIVE);
       Pattern p3 = Pattern.compile(
               "^\\s*Stream #\\S+: ((?:Audio)|(?:Video)|(?:Data)): (.*)\\s*$",
               Pattern.CASE_INSENSITIVE);
       MultimediaInfo info = null;
       try {
           int step = 0;
           while (true) {
               String line = reader.readLine();
               if (line == null) {
                   break;
               }
               if (step == 0) {
                   String token = source.getAbsolutePath() + ": ";
                   if (line.startsWith(token)) {
                       String message = line.substring(token.length());
                       throw new InputFormatException(message);
                   }
                   Matcher m = p1.matcher(line);
                   if (m.matches()) {
                       String format = m.group(1);
                       info = new MultimediaInfo();
                       info.setFormat(format);
                       step++;
                   }
               } else if (step == 1) {
                   Matcher m = p2.matcher(line);
                   if (m.matches()) {
                       long hours = Integer.parseInt(m.group(1));
                       long minutes = Integer.parseInt(m.group(2));
                       long seconds = Integer.parseInt(m.group(3));
                       long dec = Integer.parseInt(m.group(4));
                       long duration = (dec * 100L) + (seconds * 1000L)
                               + (minutes * 60L * 1000L)
                               + (hours * 60L * 60L * 1000L);
                       info.setDuration(duration);
                       step++;
                   } else {
                       step = 3;
                   }
               } else if (step == 2) {
                   Matcher m = p3.matcher(line);
                   if (m.matches()) {
                       String type = m.group(1);
                       String specs = m.group(2);
                       if ("Video".equalsIgnoreCase(type)) {
                           VideoInfo video = new VideoInfo();
                           StringTokenizer st = new StringTokenizer(specs, ",");
                           for (int i = 0; st.hasMoreTokens(); i++) {
                               String token = st.nextToken().trim();
                               if (i == 0) {
                                   video.setDecoder(token);
                               } else {
                                   boolean parsed = false;
                                   // Video size.
                                   Matcher m2 = SIZE_PATTERN.matcher(token);
                                   if (!parsed &amp;&amp; m2.find()) {
                                       int width = Integer.parseInt(m2
                                               .group(1));
                                       int height = Integer.parseInt(m2
                                               .group(2));
                                       video.setSize(new VideoSize(width,
                                               height));
                                       parsed = true;
                                   }
                                   // Frame rate.
                                   m2 = FRAME_RATE_PATTERN.matcher(token);
                                   if (!parsed &amp;&amp; m2.find()) {
                                       try {
                                           float frameRate = Float
                                                   .parseFloat(m2.group(1));
                                           video.setFrameRate(frameRate);
                                       } catch (NumberFormatException e) {
                                           ;
                                       }
                                       parsed = true;
                                   }
                                   // Bit rate.
                                   m2 = BIT_RATE_PATTERN.matcher(token);
                                   if (!parsed &amp;&amp; m2.find()) {
                                       int bitRate = Integer.parseInt(m2
                                               .group(1));
                                       video.setBitRate(bitRate);
                                       parsed = true;
                                   }
                               }
                           }
                           info.setVideo(video);
                       } else if ("Audio".equalsIgnoreCase(type)) {
                           AudioInfo audio = new AudioInfo();
                           StringTokenizer st = new StringTokenizer(specs, ",");
                           for (int i = 0; st.hasMoreTokens(); i++) {
                               String token = st.nextToken().trim();
                               if (i == 0) {
                                   audio.setDecoder(token);
                               } else {
                                   boolean parsed = false;
                                   // Sampling rate.
                                   Matcher m2 = SAMPLING_RATE_PATTERN
                                           .matcher(token);
                                   if (!parsed &amp;&amp; m2.find()) {
                                       int samplingRate = Integer.parseInt(m2
                                               .group(1));
                                       audio.setSamplingRate(samplingRate);
                                       parsed = true;
                                   }
                                   // Channels.
                                   m2 = CHANNELS_PATTERN.matcher(token);
                                   if (!parsed &amp;&amp; m2.find()) {
                                       String ms = m2.group(1);
                                       if ("mono".equalsIgnoreCase(ms)) {
                                           audio.setChannels(1);
                                       } else if ("stereo"
                                               .equalsIgnoreCase(ms)) {
                                           audio.setChannels(2);
                                       }
                                       parsed = true;
                                   }
                                   // Bit rate.
                                   m2 = BIT_RATE_PATTERN.matcher(token);
                                   if (!parsed &amp;&amp; m2.find()) {
                                       int bitRate = Integer.parseInt(m2
                                               .group(1));
                                       audio.setBitRate(bitRate);
                                       parsed = true;
                                   }
                               }
                           }
                           info.setAudio(audio);
                       }
                   } else {
                       step = 3;
                   }
               }
               if (step == 3) {
                   reader.reinsertLine(line);
                   break;
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       }
       if (info == null) {
           throw new InputFormatException();
       }
       return info;
    }

    private Hashtable parseProgressInfoLine(String line) {
       Hashtable table = null;
       Matcher m = PROGRESS_INFO_PATTERN.matcher(line);
       while (m.find()) {
           if (table == null) {
               table = new Hashtable();
           }
           String key = m.group(1);
           String value = m.group(2);
           table.put(key, value);
       }
       return table;
    }

    public void encode(File source, File target, EncodingAttributes attributes)
           throws IllegalArgumentException, InputFormatException,
           EncoderException {
       encode(source, target, attributes, null);
    }

    public void encode(File source, File target, EncodingAttributes attributes,
           EncoderProgressListener listener) throws IllegalArgumentException,
           InputFormatException, EncoderException {
       String formatAttribute = attributes.getFormat();
       Float offsetAttribute = attributes.getOffset();
       Float durationAttribute = attributes.getDuration();
       AudioAttributes audioAttributes = attributes.getAudioAttributes();
       VideoAttributes videoAttributes = attributes.getVideoAttributes();
       if (audioAttributes == null &amp;&amp; videoAttributes == null) {
           throw new IllegalArgumentException(
                   "Both audio and video attributes are null");
       }
       target = target.getAbsoluteFile();
       target.getParentFile().mkdirs();
       FFMPEGExecutor ffmpeg = locator.createExecutor();
       if (offsetAttribute != null) {
           ffmpeg.addArgument("-ss");
           ffmpeg.addArgument(String.valueOf(offsetAttribute.floatValue()));
       }
       ffmpeg.addArgument("-i");
       ffmpeg.addArgument(source.getAbsolutePath());
       if (durationAttribute != null) {
           ffmpeg.addArgument("-t");
           ffmpeg.addArgument(String.valueOf(durationAttribute.floatValue()));
       }
       if (videoAttributes == null) {
           ffmpeg.addArgument("-vn");
       } else {
           String codec = videoAttributes.getCodec();
           if (codec != null) {
               ffmpeg.addArgument("-vcodec");
               ffmpeg.addArgument(codec);
           }
           String tag = videoAttributes.getTag();
           if (tag != null) {
               ffmpeg.addArgument("-vtag");
               ffmpeg.addArgument(tag);
           }
           Integer bitRate = videoAttributes.getBitRate();
           if (bitRate != null) {
               ffmpeg.addArgument("-b");
               ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
           }
           Integer frameRate = videoAttributes.getFrameRate();
           if (frameRate != null) {
               ffmpeg.addArgument("-r");
               ffmpeg.addArgument(String.valueOf(frameRate.intValue()));
           }
           VideoSize size = videoAttributes.getSize();
           if (size != null) {
               ffmpeg.addArgument("-s");
               ffmpeg.addArgument(String.valueOf(size.getWidth()) + "x"
                       + String.valueOf(size.getHeight()));
           }
       }
       if (audioAttributes == null) {
           ffmpeg.addArgument("-an");
       } else {
           String codec = audioAttributes.getCodec();
           if (codec != null) {
               ffmpeg.addArgument("-acodec");
               ffmpeg.addArgument(codec);
           }
           Integer bitRate = audioAttributes.getBitRate();
           if (bitRate != null) {
               ffmpeg.addArgument("-ab");
               ffmpeg.addArgument(String.valueOf(bitRate.intValue()));
           }
           Integer channels = audioAttributes.getChannels();
           if (channels != null) {
               ffmpeg.addArgument("-ac");
               ffmpeg.addArgument(String.valueOf(channels.intValue()));
           }
           Integer samplingRate = audioAttributes.getSamplingRate();
           if (samplingRate != null) {
               ffmpeg.addArgument("-ar");
               ffmpeg.addArgument(String.valueOf(samplingRate.intValue()));
           }
           Integer volume = audioAttributes.getVolume();
           if (volume != null) {
               ffmpeg.addArgument("-vol");
               ffmpeg.addArgument(String.valueOf(volume.intValue()));
           }
       }
       ffmpeg.addArgument("-f");
       ffmpeg.addArgument(formatAttribute);
       ffmpeg.addArgument("-y");
       ffmpeg.addArgument(target.getAbsolutePath());
       try {
           ffmpeg.execute();
       } catch (IOException e) {
           throw new EncoderException(e);
       }
       try {
           String lastWarning = null;
           long duration;
           long progress = 0;
           RBufferedReader reader = null;
           reader = new RBufferedReader(new InputStreamReader(ffmpeg
                   .getErrorStream()));
           MultimediaInfo info = parseMultimediaInfo(source, reader);
           if (durationAttribute != null) {
               duration = (long) Math
                       .round((durationAttribute.floatValue() * 1000L));
           } else {
               duration = info.getDuration();
               if (offsetAttribute != null) {
                   duration -= (long) Math
                           .round((offsetAttribute.floatValue() * 1000L));
               }
           }
           if (listener != null) {
               listener.sourceInfo(info);
           }
           int step = 0;
           String line;
           while ((line = reader.readLine()) != null) {
               if (step == 0) {
                   if (line.startsWith("WARNING: ")) {
                       if (listener != null) {
                           listener.message(line);
                       }
                   } else if (!line.startsWith("Output #0")) {
                       throw new EncoderException(line);
                   } else {
                       step++;
                   }
               } else if (step == 1) {
                   if (!line.startsWith("  ")) {
                       step++;
                   }
               }
               if (step == 2) {
                   if (!line.startsWith("Stream mapping:")) {
                       throw new EncoderException(line);
                   } else {
                       step++;
                   }
               } else if (step == 3) {
                   if (!line.startsWith("  ")) {
                       step++;
                   }
               }
               if (step == 4) {
                   line = line.trim();
                   if (line.length() > 0) {
                       Hashtable table = parseProgressInfoLine(line);
                       if (table == null) {
                           if (listener != null) {
                               listener.message(line);
                           }
                           lastWarning = line;
                       } else {
                           if (listener != null) {
                               String time = (String) table.get("time");
                               if (time != null) {
                                   int dot = time.indexOf('.');
                                   if (dot > 0 &amp;&amp; dot == time.length() - 2
                                           &amp;&amp; duration > 0) {
                                       String p1 = time.substring(0, dot);
                                       String p2 = time.substring(dot + 1);
                                       try {
                                           long i1 = Long.parseLong(p1);
                                           long i2 = Long.parseLong(p2);
                                           progress = (i1 * 1000L)
                                                   + (i2 * 100L);
                                           int perm = (int) Math
                                                   .round((double) (progress * 1000L)
                                                           / (double) duration);
                                           if (perm > 1000) {
                                               perm = 1000;kMDItemAudioEncodingApplication = "Lavf57.26.100"
                                           }
                                           listener.progress(perm);
                                       } catch (NumberFormatException e) {
                                           ;
                                       }
                                   }
                               }
                           }
                           lastWarning = null;
                       }
                   }
               }
           }
           if (lastWarning != null) {
               if (!SUCCESS_PATTERN.matcher(lastWarning).matches()) {
                   throw new EncoderException(lastWarning);
               }
           }
       } catch (IOException e) {
           throw new EncoderException(e);
       } finally {
           ffmpeg.destroy();
       }
    }

    }