The simplest ffmpeg-based audio encoder (PCM encoded as AAC) __ Encoding

Source: Internet
Author: User
Tags flush int size printf

This article describes one of the simplest audio encoders based on FFmpeg. The encoder realizes the PCM audio sampling data encoded as AAC compressed encoded data. The encoder code is very simple, but each line of code is important. By looking at the source code of this encoder, you can understand the FFmpeg audio coding process.

This program uses the latest version of the class library (compile time is 2014.5.6), the development platform for VC2010. All the configuration is done, just need to run it.


process (2014.9.29 update)

A flowchart with FFmpeg encoded audio is attached below. Using this process, not only can encode AAC audio, but also can encode mp3,mp2 and so on various ffmpeg support audio. The function of the blue background in the figure is the function of the actual output data. The light green function is the function of the audio encoding.


Briefly describe the meaning of each function in the process:

Av_register_all (): Registers ffmpeg all codecs.

AVFORMAT_ALLOC_OUTPUT_CONTEXT2 (): Initializes the avformatcontext of the output stream.

Avio_open (): Open the output file.

Av_new_stream (): Creates the avstream of the output stream.

Avcodec_find_encoder (): Find the encoder.

Avcodec_open2 (): Open the encoder.

Avformat_write_header (): Writes the file header (this function is not required for some encapsulation formats that do not have a file header.) such as Mpeg2ts).

Avcodec_encode_audio2 (): Encode audio. The Avframe (storage PCM sampled data) is encoded as avpacket (stream data in the form of Aac,mp3, etc.).

Av_write_frame (): Writes the encoded video stream to the file.

Av_write_trailer (): Writes the end of the file (this function is not required for some encapsulation formats that do not have a file header.) such as Mpeg2ts).
Code

/** * Simplest FFmpeg-based audio encoder *simplest FFmpeg Audio Encoder * * Lei Huawei Lei Xiaohua *leixiaohua1020@126.com * Communication University/Digital TV technology *c Ommunication University of China/digital TV Technology *http://blog.csdn.net/leixiaohua1020 * * This program realizes the audio PCM sampling data encoded as a compressed code stream
 (MP3,WMA,AAC, etc.).
 * Is the simplest ffmpeg audio coding aspect of the tutorial.
 * Learn This example to learn about the FFmpeg coding process.
 *this software encode PCM data to AAC bitstream. 
 *it ' s The simplest audio encoding software based on FFmpeg. *suitable for Beginner of FFmpeg * * #include <stdio.h> #define __stdc_constant_macros #ifdef _WIN32//windows E
Xtern "C" {#include "libavcodec/avcodec.h" #include "libavformat/avformat.h"}; #else//linux #ifdef __cplusplus extern "C" {#endif #include <libavcodec/avcodec.h> #include <libavformat/av
Format.h> #ifdef __cplusplus};
	#endif #endif int Flush_encoder (avformatcontext *fmt_ctx,unsigned int stream_index) {int ret;
	int got_frame;
	Avpacket enc_pkt; if (! (
		Fmt_ctx->streams[stream_index]->codec->codec->capabilities &Codec_cap_delay)) return 0;
		while (1) {enc_pkt.data = NULL;
		enc_pkt.size = 0;
		Av_init_packet (&AMP;ENC_PKT);
		ret = Avcodec_encode_audio2 (Fmt_ctx->streams[stream_index]->codec, &enc_pkt, NULL, &got_frame);
		Av_frame_free (NULL);
		if (Ret < 0) break;
			if (!got_frame) {ret=0;
		Break
		} printf ("Flush encoder:succeed to encode 1 frame!\tsize:%5d\n", enc_pkt.size);
		/* MUX Encoded frame */ret = Av_write_frame (Fmt_ctx, &AMP;ENC_PKT);
	if (Ret < 0) break;
} return ret;
	} int main (int argc, char* argv[]) {avformatcontext* pformatctx;
	Avoutputformat* FMT;
	avstream* Audio_st;
	avcodeccontext* Pcodecctx;

	avcodec* Pcodec;
	uint8_t* Frame_buf;
	Avframe* pframe;

	Avpacket PKT;
	int got_frame=0;
	int ret=0;

	int size=0;	                        FILE *in_file=null;                          Raw PCM data int framenum=1000;          Audio Frame Number const char* Out_file = "TDJM.AAC";

	Output URL int i; in_file= fopen ("TDJM.PCM"," RB ");

	Av_register_all ();
	Method 1.
	Pformatctx = Avformat_alloc_context ();
	FMT = Av_guess_format (null, out_file, NULL);


	Pformatctx->oformat = FMT;
	Method 2.
	AVFORMAT_ALLOC_OUTPUT_CONTEXT2 (&AMP;PFORMATCTX, NULL, NULL, out_file);

	FMT = pformatctx->oformat; Open output URL if (Avio_open (&pformatctx->pb,out_file, Avio_flag_read_write) < 0) {printf ("Failed to open
		Output file!\n ");
	return-1;
	} Audio_st = Avformat_new_stream (pformatctx, 0);
	if (audio_st==null) {return-1;
	} Pcodecctx = audio_st->codec;
	pcodecctx->codec_id = fmt->audio_codec;
	Pcodecctx->codec_type = Avmedia_type_audio;
	PCODECCTX-&GT;SAMPLE_FMT = AV_SAMPLE_FMT_S16;
	Pcodecctx->sample_rate= 44100;
	pcodecctx->channel_layout=av_ch_layout_stereo;
	Pcodecctx->channels = Av_get_channel_layout_nb_channels (pcodecctx->channel_layout);  

	Pcodecctx->bit_rate = 64000;

	Show Some information Av_dump_format (pformatctx, 0, Out_file, 1); Pcodec = avCodec_find_encoder (pcodecctx->codec_id);
		if (!pcodec) {printf ("Can not find encoder!\n");
	return-1;
		} if (Avcodec_open2 (Pcodecctx, Pcodec,null) < 0) {printf ("Failed to open encoder!\n");
	return-1;
	} pframe = Av_frame_alloc ();
	pframe->nb_samples= pcodecctx->frame_size;
	
	pframe->format= pcodecctx->sample_fmt; Size = Av_samples_get_buffer_size (NULL, PCODECCTX-&GT;CHANNELS,PCODECCTX-&GT;FRAME_SIZE,PCODECCTX-&GT;SAMPLE_FMT,
	1);
	Frame_buf = (uint8_t *) av_malloc (size); Avcodec_fill_audio_frame (Pframe, Pcodecctx->channels, PCODECCTX-&GT;SAMPLE_FMT, (const uint8_t*) frame_buf, size,
	
	1);

	Write Header Avformat_write_header (pformatctx,null);

	Av_new_packet (&pkt,size); for (i=0; i<framenum; i++) {//read PCM if (fread (FRAME_BUF, 1, size, in_file) <= 0) {printf ("Failed to Read R AW data!
			\ n ");
		return-1;
		}else if (feof (In_file)) {break;  } pframe->data[0] = Frame_buf;
		PCM Data pframe->pts=i*100;
		got_frame=0; //Encode ret = Avcodec_encode_audio2 (Pcodecctx, &pkt,pframe, &got_frame);
			if (Ret < 0) {printf ("Failed to encode!\n");
		return-1; } if (got_frame==1) {printf ("Succeed to encode 1 frame!
			\tsize:%5d\n ", pkt.size);
			Pkt.stream_index = audio_st->index;
			ret = Av_write_frame (Pformatctx, &AMP;PKT);
		Av_free_packet (&AMP;PKT);
	}}//flush Encoder ret = Flush_encoder (pformatctx,0);
		if (Ret < 0) {printf ("Flushing encoder failed\n");
	return-1;

	}//write Trailer Av_write_trailer (PFORMATCTX);
		Clean if (audio_st) {avcodec_close (AUDIO_ST-&GT;CODEC);
		Av_free (pframe);
	Av_free (FRAME_BUF);
	} avio_close (PFORMATCTX-&GT;PB);

	Avformat_free_context (PFORMATCTX);

	Fclose (In_file);
return 0;

 }


Results

When the program finishes running, a PCM sampling data file (*.PCM) is encoded as an AAC stream file (*.AAC).


Download

Simplest FFmpeg Audio encoder


Project Home

sourceforge:https://sourceforge.net/projects/simplestffmpegaudioencoder/

Github:https://github.com/leixiaohua1020/simplest_ffmpeg_audio_encoder

Open source China: Http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_audio_encoder


CSDN Project Download Address:

http://download.csdn.net/detail/leixiaohua1020/7324091

PUDN Project Download Address:

Http://www.pudn.com/downloads644/sourcecode/multimedia/detail2605236.html


update -1.1 (2015.2.13) =========================================

This time, considering the cross-platform requirements, the source code has been adjusted. After this adjustment, the source code can be compiled on the following platform:

VC + +: Open the SLn file to compile without configuration.

Cl.exe: Open Compile_cl.bat can be compiled using cl.exe at the command line, note that you may need to follow the VC installation path to adjust the parameters inside the script. The compile command is as follows.

:: VS2010 Environment call
"D:\Program Files\Microsoft Visual Studio 10.0\vc\vcvarsall.bat"
:: Include
@ Set include=include;%i Nclude%
:: Lib
@set lib=lib;%lib%
:: Compile and link
cl simplest_ffmpeg_audio_encoder.cpp/link Avcodec.lib avformat.lib avutil.lib ^
avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib/opt:noref

The MINGW:MINGW command line runs compile_mingw.sh to compile using MinGW's g++. The compile command is as follows.

g++ simplest_ffmpeg_audio_encoder.cpp-g-o simplest_ffmpeg_audio_encoder.exe \
-i/usr/local/include-l/usr/ Local/lib-lavformat-lavcodec-lavutil

Gcc:linux or MacOS command line run compile_gcc.sh can be compiled using GCC. The compile command is as follows.

GCC simplest_ffmpeg_audio_encoder.cpp-g-o simplest_ffmpeg_audio_encoder.out \
-i/usr/local/include-l/usr/ Local/lib-lavformat-lavcodec-lavutil

PS: The related compilation commands have been saved in the project folder


CSDN Download Address: http://download.csdn.net/detail/leixiaohua1020/8445209

The SourceForge has been updated.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.