[Libav-user] Troubles with encoding in AAC

Bakhtiyarov Dmitriy bakhtiyarov.dima at gmail.com
Fri Nov 15 21:20:20 CET 2013

Good day for all!

I'm developing a GUI application, which encode video and audio stream from camera and microphone. And I have some problem with the audio stream.

I receive raw samples from microphone using QAudioProbe from Qt library and I give samples in format AV_SAMPLE_FMT_S32, but AAC encoder support only AV_SAMPLE_FMT_S16. I'm resampling raw stream using swr_convert(...) from libswresample.
I don't have any errors or warning messages in this process, but when I call avcodec_encode_audio2(...) again and again I'm only one time can see gotPacket variable set to 1 :( 
The size of this successfully encoded buffer = 33 bytes. 
What is the mistake, that I made?

I use following code for encoding audio stream:

AVCodecContext* m_context;
AVFrame* m_inData;
AVPacket m_outPacket;

//Initialization of resample context
SwrContext* m_resampleContext = swr_alloc();

av_opt_set_int(m_resampleContext, "in_channel_layout", AV_CH_LAYOUT_STEREO, 0);
av_opt_set_int(m_resampleContext, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
av_opt_set_int(m_resampleContext, "in_sample_rate", sampleRate, 0);
av_opt_set_int(m_resampleContext, "out_sample_rate", sampleRate, 0);
av_opt_set_int(m_resampleContext, "in_sample_fmt", inFormat, 0);
av_opt_set_int(m_resampleContext, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);

if (swr_init(m_resampleContext) < 0)
    qDebug() << "AACEncoder: init of resample context failed!";
    return false;

        if (swr_convert(m_resampleContext, &m_inData->data[0], m_inData->nb_samples, (const u_int8_t**)&buf,
         		m_inData->nb_samples) < 0)
        	qFatal("Failed to resample audio stream!");

        QAudioFormat f = buffer.format();
	m_inData->channels = f.channelCount();
	m_inData->channel_layout = AV_CH_LAYOUT_STEREO;
	m_inData->format = AV_SAMPLE_FMT_S16;

	int gotPacket;
	if ( avcodec_encode_audio2(m_context, &m_outPacket, m_inData, &gotPacket) < 0 )
		//error processing

	if (gotPacket)
		qDebug() << "AACEncoder: size of encoded frame " << m_outPacket.size;
		std::copy(m_outPacket.data, m_outPacket.data + m_outPacket.size, std::back_inserter(result));
		audio_dump.write((const char*)m_outPacket.data, m_outPacket.size);

With best regards,
Dmitriy Bakhtiyarov.

More information about the Libav-user mailing list