<div dir="ltr"><div><div>Hiii Gonzalo Garramuño,<br><br></div>I have modified the code but there is issue that i am not able to figure out.<br></div>No error while encoding, resampling , and writting the audio data. But output file only have the 1 sec audio. can you check the code and suggest some changes.<br><br>ref struct AudioWriterData<br>    {<br>        public:<br>            Ffmpeg::AVFormatContext*        FormatContext;<br>            <br>            Ffmpeg::AVStream*                AudioStream;<br>            Ffmpeg::AVFrame*                AudioFrame;<br>            Ffmpeg::AVCodec                *Audio_Codec;<br><br>            int AudioBitRate;<br>            int SampleRate;<br>            int Channels;<br>        <br>            int AudioReceived;<br>            int AudioWritten;<br><br>            int64_t next_pts;<br>            int samples_count;<br><br>            Ffmpeg::AVFrame *tmp_frame;<br><br>            float t, tincr, tincr2;<br>            struct Ffmpeg::SwsContext *sws_ctx;<br>            struct Ffmpeg::SwrContext *swr_ctx;<br><br>            double PreviousAudioDts;<br><br>            double EncodedAudioFrame;<br><br>            AudioWriterData()<br>            {<br>                FormatContext = NULL;<br>                <br>                AudioStream = NULL;<br><br>                Audio_Codec = NULL;<br><br>                AudioFrame = NULL;<br>            <br>                AudioReceived = 0;<br>                AudioWritten = 0;<br>                EncodedAudioFrame = 0;<br>            }<br>    };<br>    <br>    <br>    //Open the audio file with specified settings<br>    void AudioWriter::Open(String^ fileName, AudioCodec audioCodec, int audioBitrate, int sampleRate, int channels)<br>    {<br>        CheckIfDisposed();<br><br>        Close();<br><br>        data = gcnew AudioWriterData();<br>        bool success = false;<br><br>        if (((int)audioCodec < -1) || ((int)audioCodec >= AUDIO_CODECS_COUNT))<br>            throw gcnew ArgumentException("Invalid audio codec is specified.");<br><br>        m_acodec = audioCodec;<br>        m_audioBitrate = audioBitrate;<br>        m_sampleRate = sampleRate;<br>        m_channels = channels;<br><br>        data->AudioBitRate = audioBitrate;<br>        data->SampleRate = sampleRate;<br>        data->Channels = channels;<br><br>        char* nativeFileName = (char*)System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(fileName).ToPointer();<br><br>        try<br>        {<br>            Ffmpeg::AVOutputFormat* outputFormat = Ffmpeg::av_guess_format(NULL, nativeFileName, NULL);<br><br>            if (!outputFormat)<br>            {<br>                outputFormat = Ffmpeg::av_guess_format("mp3", NULL, NULL);<br><br>                if (!outputFormat)<br>                    throw gcnew Exception("Cannot find suitable output format.");<br>            }<br><br>            data->FormatContext = Ffmpeg::avformat_alloc_context();<br><br>            if (!data->FormatContext)<br>                throw gcnew Exception("Cannot allocate format context.");<br><br>            data->FormatContext->oformat = outputFormat;<br>            strcpy_s(data->FormatContext->filename, nativeFileName);<br><br>            Ffmpeg::AVCodecID avcodecid = (audioCodec == AudioCodec::Default) ? outputFormat->audio_codec : (Ffmpeg::AVCodecID) audio_codecs[(int)audioCodec];<br>            data->FormatContext->oformat->audio_codec = avcodecid;<br><br>            add_stream(data, data->FormatContext, data->Audio_Codec, avcodecid);<br><br>            open_audio(data->FormatContext, data->Audio_Codec, data);<br><br>            Ffmpeg::av_dump_format(data->FormatContext, 0, nativeFileName, 1);<br><br>            if (!(outputFormat->flags & AVFMT_NOFILE))<br>            {<br>                if (Ffmpeg::avio_open(&data->FormatContext->pb, nativeFileName, AVIO_FLAG_WRITE) < 0)<br>                    throw gcnew System::IO::IOException("Cannot open the audio file.");<br>            }<br><br>            Ffmpeg::avformat_write_header(data->FormatContext, NULL);<br><br>            success = true;<br>        }<br>        finally<br>        {<br>            nativeFileName = NULL;<br>            delete[] nativeFileName;<br><br>            if (!success)<br>                Close();<br>        }<br>    }<br>    <br>    static void add_stream(AudioWriterData^ ost, Ffmpeg::AVFormatContext *oc, Ffmpeg::AVCodec *codec, enum Ffmpeg::AVCodecID codec_id)<br>    {<br>        Ffmpeg::AVCodecContext *c;<br>        int i;<br><br>        codec = Ffmpeg::avcodec_find_encoder(codec_id);<br><br>        if (!(codec)) <br>            throw gcnew Exception("Invalid audio codec is specified.");<br><br>        ost->AudioStream = Ffmpeg::avformat_new_stream(oc, codec);<br><br>        if (!ost->AudioStream)<br>            throw gcnew Exception("Unable to add audio stream.");<br><br>        ost->AudioStream->id = oc->nb_streams - 1;<br>        c = ost->AudioStream->codec;<br>        c->sample_fmt = (codec)->sample_fmts ? (codec)->sample_fmts[0] : Ffmpeg::AV_SAMPLE_FMT_FLTP;<br>        c->bit_rate = ost->AudioBitRate;<br>        c->sample_rate = 44100;<br>        if ((codec)->supported_samplerates) <br>        {<br>            c->sample_rate = (codec)->supported_samplerates[0];<br>            for (i = 0; (codec)->supported_samplerates[i]; i++) <br>            {<br>                if ((codec)->supported_samplerates[i] == 44100)<br>                c->sample_rate = 44100;<br>            }<br>        }<br>        c->channels = Ffmpeg::av_get_channel_layout_nb_channels(c->channel_layout);<br>        c->channel_layout = AV_CH_LAYOUT_STEREO;<br>        if ((codec)->channel_layouts) <br>        {<br>            c->channel_layout = (codec)->channel_layouts[0];<br>            for (i = 0; (codec)->channel_layouts[i]; i++) <br>            {<br>                if ((codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO)<br>                    c->channel_layout = AV_CH_LAYOUT_STEREO;<br>            }<br>        }<br>        c->channels = Ffmpeg::av_get_channel_layout_nb_channels(c->channel_layout);<br>        ost->AudioStream->time_base.num = 1;<br>        ost->AudioStream->time_base.den = c->sample_rate;<br>        <br>        if (oc->oformat->flags & AVFMT_GLOBALHEADER)<br>            c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;<br>    }<br><br>    static Ffmpeg::AVFrame *alloc_audio_frame(enum Ffmpeg::AVSampleFormat sample_fmt,uint64_t channel_layout,int sample_rate, int nb_samples)<br>    {<br>        Ffmpeg::AVFrame *frame = Ffmpeg::av_frame_alloc();<br>        int ret;<br>        if (!frame) <br>            throw gcnew Exception("Unable to allocate frame.");<br>        <br>        frame->format = sample_fmt;<br>        frame->channel_layout = channel_layout;<br>        frame->sample_rate = sample_rate;<br>        frame->nb_samples = nb_samples;<br>        <br>        if (nb_samples) <br>        {<br>            ret = av_frame_get_buffer(frame, 0);<br>            if (ret < 0) <br>                throw gcnew Exception("Unable to buffer frame.");<br>        }<br>        <br>        return frame;<br>    }<br>    <br>    static void open_audio(Ffmpeg::AVFormatContext *oc, Ffmpeg::AVCodec *codec, AudioWriterData^ ost)<br>    {<br>        Ffmpeg::AVCodecContext *c;<br>        int nb_samples;<br>        int ret;<br>        c = ost->AudioStream->codec;<br><br>        ret = avcodec_open2(c, codec, NULL);<br>        if (ret < 0)<br>            throw gcnew Exception("Cannot open audio codec.");<br><br>        ost->t = 0;<br>        ost->tincr = 2 * M_PI * 110.0 / c->sample_rate;<br>        ost->tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;<br>        <br>        if (c->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)<br>            nb_samples = 10000;<br>        else<br>            nb_samples = c->frame_size;<br>        <br>        ost->AudioFrame = alloc_audio_frame(c->sample_fmt, c->channel_layout, c->sample_rate, nb_samples);<br>        ost->tmp_frame = alloc_audio_frame(Ffmpeg::AV_SAMPLE_FMT_S16, c->channel_layout, c->sample_rate, nb_samples);<br>                <br>        ost->swr_ctx = Ffmpeg::swr_alloc();<br>        if (!ost->swr_ctx)<br>            throw gcnew Exception("Could not allocate resampler context.");<br>                <br>        Ffmpeg::av_opt_set_int(ost->swr_ctx, "in_channel_count", c->channels, 0);<br>        Ffmpeg::av_opt_set_int(ost->swr_ctx, "in_sample_rate", c->sample_rate, 0);<br>        Ffmpeg::av_opt_set_sample_fmt(ost->swr_ctx, "in_sample_fmt", Ffmpeg::AV_SAMPLE_FMT_S16, 0);<br>        Ffmpeg::av_opt_set_int(ost->swr_ctx, "out_channel_count", c->channels, 0);<br>        Ffmpeg::av_opt_set_int(ost->swr_ctx, "out_sample_rate", c->sample_rate, 0);<br>        Ffmpeg::av_opt_set_sample_fmt(ost->swr_ctx, "out_sample_fmt", c->sample_fmt, 0);<br>                <br>        if ((ret = Ffmpeg::swr_init(ost->swr_ctx)) < 0)<br>            throw gcnew Exception("Failed to initialize the resampling context.");<br>    }<br>    <br>    void AudioWriter::WriteAudioChunk(IntPtr chunk, int lenght)<br>    {<br>        uint8_t *audioData = reinterpret_cast<uint8_t*>(static_cast<void*>(chunk));<br><br>        int buffer_size = Ffmpeg::av_samples_get_buffer_size(NULL, data->tmp_frame->channels, data->tmp_frame->nb_samples,<br>            data->AudioStream->codec->sample_fmt, 0);<br><br>        uint8_t *buf = reinterpret_cast<uint8_t*>(static_cast<void*>(chunk));<br>        int ret = Ffmpeg::avcodec_fill_audio_frame(data->tmp_frame, data->Channels, data->AudioStream->codec->sample_fmt, buf, buffer_size, 1);<br>        if (!ret)<br>            throw gcnew System::IO::IOException("A video file was not opened yet.");<br><br>        write_audio_frame(data->FormatContext, data, audioData);<br>    }<br>    <br>    static int write_audio_frame(Ffmpeg::AVFormatContext *oc, AudioWriterData^ ost, uint8_t *audioData)<br>    {<br>        Ffmpeg::AVCodecContext *c;<br>        Ffmpeg::AVPacket pkt = { 0 };<br>        int ret;<br>        int got_packet;<br>        int dst_nb_samples;<br><br>        Ffmpeg::av_init_packet(&pkt);<br>        c = ost->AudioStream->codec;<br>        <br>        Ffmpeg::AVFrame *frame = ost->tmp_frame;<br><br>        if (frame)<br>        {<br>            dst_nb_samples = Ffmpeg::av_rescale_rnd(swr_get_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples,<br>                c->sample_rate, c->sample_rate, Ffmpeg::AV_ROUND_UP);<br>            if (dst_nb_samples != frame->nb_samples)<br>                throw gcnew Exception("dst_nb_samples != frame->nb_samples");<br><br>            ret = Ffmpeg::av_frame_make_writable(ost->AudioFrame);<br>            if (ret < 0)<br>                throw gcnew Exception("Unable to make writable.");<br><br>            ret = swr_convert(ost->swr_ctx, ost->AudioFrame->data, dst_nb_samples, (const uint8_t **)frame->data, frame->nb_samples);<br>            if (ret < 0) <br>                throw gcnew Exception("Unable to convert to destination format.");<br>            <br>            frame = ost->AudioFrame;<br><br>            Ffmpeg::AVRational timebase = { 1, c->sample_rate };<br>            frame->pts = Ffmpeg::av_rescale_q(ost->samples_count, timebase, c->time_base);<br>            ost->samples_count += dst_nb_samples;<br>        }<br><br>        ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);<br>        if (ret < 0) <br>            throw gcnew Exception("Error encoding audio frame.");<br><br>        if (got_packet) <br>        {<br>            Console::WriteLine("Audio packet encode successfully.");<br>            ret = write_frame(oc, &c->time_base, ost->AudioStream, &pkt);<br>            if (ret < 0)<br>                Console::WriteLine("Audio is not written.");<br>        }<br>        else<br>            Console::WriteLine("Audio packet encode failed.");<br><br>        return (ost->AudioFrame || got_packet) ? 0 : 1;<br>    }<br><br>    static int write_frame(Ffmpeg::AVFormatContext *fmt_ctx, const Ffmpeg::AVRational *time_base, Ffmpeg::AVStream *st, Ffmpeg::AVPacket *pkt)<br>    {<br>        Ffmpeg::av_packet_rescale_ts(pkt, *time_base, st->time_base);<br>        pkt->stream_index = st->index;<br>        return Ffmpeg::av_interleaved_write_frame(fmt_ctx, pkt);<br>    }<br></div><div class="gmail_extra"><br><div class="gmail_quote">On 16 February 2017 at 03:13, Gonzalo Garramuño <span dir="ltr"><<a href="mailto:ggarra13@gmail.com" target="_blank">ggarra13@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
  
    
  
  <div bgcolor="#FFFFFF" text="#000000">
    <p><br>
    </p>
    <br>
    <div class="m_8816357505044468833moz-cite-prefix">El 15/02/17 a las 03:58, Prakash Rokade
      escribió:<br>
    </div><span class="">
    <blockquote type="cite">
      <div dir="ltr">
        <div>Thanks Gonzalo,</div>
        <div><br>
        </div>
        <div>According to your suggestion i have written the below code
          can you check ones, because audio is written but in output
          file no audio is present.</div>
        <div><span style="font-size:12.8px"></span><br style="font-size:12.8px">
        </div>
      </div>
    </blockquote></span>
    You are opening the stream with AV_SAMPLE_FMT_S16 and then using
    sample_fmt[0]. That's inconsistent to say the least.<br>
    You are not using swresample to take one audio format to another.<br>
    You have a swscale ptr which has nothing to do with audio.<br>
    You are using the new API but are not handling the AVERROR(EAGAIN)
    cases.  For this trial, use the old api which is more reliable for
    muxing.<br>
    Try to get the sample in doc/examples working and slowly modify it
    to fit your need.<span class="HOEnZb"><font color="#888888"><br>
    <pre class="m_8816357505044468833moz-signature" cols="72">-- 
Gonzalo Garramuño</pre>
  </font></span></div>

<br>______________________________<wbr>_________________<br>
Libav-user mailing list<br>
<a href="mailto:Libav-user@ffmpeg.org">Libav-user@ffmpeg.org</a><br>
<a href="http://ffmpeg.org/mailman/listinfo/libav-user" rel="noreferrer" target="_blank">http://ffmpeg.org/mailman/<wbr>listinfo/libav-user</a><br>
<br></blockquote></div><br></div>