shithub: aacenc

Download patch

ref: d9455dcc8c34a4bb31248c6b9970384e532649ea
parent: 1bed72165486ab1775fe0428a8426c5b90629331
author: lenox <lenox>
date: Fri Feb 18 04:21:05 EST 2000

new interface functions

--- a/aacenc.h
+++ b/aacenc.h
@@ -1,3 +1,5 @@
+#include <stdio.h>
+#include <sndfile.h>
 
 typedef struct RCBufStruct RCBuf;	/* buffer handle */
 
@@ -6,6 +8,7 @@
 
 #define FNO_ERROR 0
 #define FERROR 1
+#define F_FINISH 2
 
 #define NO_HEADER	0
 #define ADIF_HEADER     1
@@ -19,12 +22,13 @@
 	char HomePage[255];
 } faacVersion;
 
-// This structure is for internal use of the encoder only.
+// This structure is for AAC stream object
 typedef struct {
 	long total_bits;
 	long frames;
 	long cur_frame;
 	int is_first_frame;
+	int is_last_frames;
 	int channels;
 	int out_sampling_rate;
 	int in_sampling_rate;
@@ -40,110 +44,36 @@
 	double **inputBuffer;
 	RCBuf *rc_buf;
 	int rc_needed;
-	int samplesToRead;
 	int savedSize;
 	float saved[2048];
 	int cut_off;
 	int bit_rate;
-	char out_dir[255];
-	int out_dir_set;
 	int raw_audio;
+        SNDFILE *in_file;
+        FILE *out_file;
+        unsigned char *bitBuffer;
+        int bitBufferSize;
+        short *sampleBuffer;
+	int samplesToRead;
 } faacAACStream;
 
 #ifndef FAAC_DLL
 
+int faac_EncodeInit(faacAACStream *as, char *in_file, char *out_file);
+int faac_EncodeFrame(faacAACStream *as);
+void faac_EncodeFree(faacAACStream *as);
+void faac_EncodeFinish(faacAACStream *as);
+faacVersion *faac_Version(void);
+void faac_InitParams(faacAACStream *as);
 
-//
-// The main() function in encoder.c gives an example of how to use these functions
-//
-
-// faacAACStream* faacEncodeInit(faacAACConfig *ac, int *samplesToRead, int *bitBufferSize,
-//  int *headerSize);
-//
-// Purpose:
-//  Initializes the DLL.
-// Parameters:
-//  Input:
-//   ac: Completely filled faacAACConfig structure
-//  Output:
-//   samplesToRead: Number of samples that should be read before every call to faacEncodeFrame()
-//   bitBufferSize: Size of the buffer in bytes that should be initialized for writing
-//   headerSize: Size of the buffer in bytes that should be initialized for writing the header
-//               This number of bytes should be skipped in the file before writing any frames.
-//               Later, after calling faacAACFree() the headerBuf should be written to this space in the AAC file.
-// Return value:
-//  faacAACStream structure that should be used in calls to other functions
-typedef int (*FAACENCODEINIT) (faacAACStream *as, int *samplesToRead, int *bitBufferSize, int *headerSize);
-
-
-// int faacEncodeFrame(faacAACStream *as, short *Buffer, int Samples, unsigned char *bitBuffer,
-//  int *bitBufSize);
-//
-// Purpose:
-//  Encodes a chunk of samples.
-// Parameters:
-//  Input:
-//   as: faacAACStream returned by faacEncodeInit()
-//   Buffer: Sample data from audio file
-//   Samples: Number of samples in buffer
-//  Output:
-//   bitBuffer: Output data that should be written to the AAC file.
-//   bitBufSize: Size of bitBuffer in bytes
-// Return value:
-//  FERROR or FNO_ERROR
-typedef int (*FAACENCODEFRAME) (faacAACStream *as, short *Buffer, int Samples, unsigned char *bitBuffer, int *bitBufSize);
-
-
-// int faacEncodeFinish(faacAACStream *as, unsigned char *bitBuffer, int *bitBufSize);
-//
-// Purpose:
-//  Flushes the last pieces of data.
-// Parameters:
-//  Input:
-//   as: faacAACStream returned by faacEncodeInit()
-//  Output:
-//   bitBuffer: Output data that should be written to the AAC file.
-//   bitBufSize: Size of bitBuffer in bytes
-// Return value:
-//  FERROR or FNO_ERROR
-typedef int (*FAACENCODEFINISH) (faacAACStream *as, unsigned char *bitBuffer, int *bitBufSize);
-
-// int faacEncodeFree(faacAACStream *as, unsigned char *headerBuf);
-//
-// Purpose:
-//  Frees encoder memory and fills in headerBuf.
-// Parameters:
-//  Input:
-//   as: faacAACStream returned by faacEncodeInit()
-//  Output:
-//   headerBuf: Header data that should be written to the AAC file, size of 
-//         the data is headerSize returned by faacEncodeInit().
-// Return value:
-//  FERROR or FNO_ERROR
-typedef int (*FAACENCODEFREE) (faacAACStream *as, unsigned char *headerBuf);
-
-
-// int faacEncodeVersion(void);
-//
-// Purpose:
-//  Gives version information from the DLL.
-// Return value:
-//  Filled in faacVersion structure
-typedef faacVersion* (*FAACENCODEVERSION) (void);
-
-#define TEXT_FAACENCODEINIT    "faacEncodeInit"
-#define TEXT_FAACENCODEFRAME   "faacEncodeFrame"
-#define TEXT_FAACENCODEFINISH  "faacEncodeFinish"
-#define TEXT_FAACENCODEFREE    "faacEncodeFree"
-#define TEXT_FAACENCODEVERSION "faacEncodeVersion"
-
 #else
 
-__declspec(dllexport) int faacEncodeInit(faacAACStream *as, int *samplesToRead, int *bitBufferSize, int *headerSize);
-__declspec(dllexport) int faacEncodeFrame(faacAACStream *as, short *Buffer, int Samples, unsigned char *bitBuffer, int *bitBufSize);
-__declspec(dllexport) int faacEncodeFree(faacAACStream *as, unsigned char *headerBuf);
-__declspec(dllexport) int faacEncodeFinish(faacAACStream *as, unsigned char *bitBuffer, int *bitBufSize);
-__declspec(dllexport) faacVersion *faacEncodeVersion(void);
+__declspec(dllexport) int faac_EncodeInit(faacAACStream *as, char *in_file, char *out_file);
+__declspec(dllexport) int faac_EncodeFrame(faacAACStream *as);
+__declspec(dllexport) void faac_EncodeFree(faacAACStream *as);
+__declspec(dllexport) void faac_EncodeFinish(faacAACStream *as);
+__declspec(dllexport) faacVersion *faac_Version(void);
+__declspec(dllexport) void faac_InitParams(faacAACStream *as);
 
 #endif
 
--- a/enc.h
+++ b/enc.h
@@ -1,7 +1,7 @@
 /**********************************************************************
 Header file: enc.h
 
-$Id: enc.h,v 1.4 2000/02/15 07:01:21 lenox Exp $
+$Id: enc.h,v 1.5 2000/02/18 09:21:05 lenox Exp $
 
 Authors:
 HP    Heiko Purnhagen, Uni Hannover <purnhage@tnt.uni-hannover.de>
@@ -37,7 +37,7 @@
 /* EncTfInit() */
 /* Init t/f-based encoder core. */
 
-void EncTfInit (faacAACStream *as, int VBR_setting);
+void EncTfInit (faacAACStream *as);
 
 
 
--- a/enc_tf.c
+++ b/enc_tf.c
@@ -112,7 +112,7 @@
  ***
  ****************************************************************************************/
 
-void EncTfInit (faacAACStream *as, int VBR_setting)
+void EncTfInit (faacAACStream *as)
 {
 	int chanNum, i;
 	int SampleRates[] = {
--- a/encoder.c
+++ b/encoder.c
@@ -1,71 +1,154 @@
-
-/* Encoder DLL interface module.*/
-
-#ifdef FAAC_DLL
+#ifdef WIN32
 #include <windows.h>
 #endif
 #include <memory.h>
 #include <string.h>
 #include <stdlib.h>
-
 #include "aacenc.h"
 #include "bitstream.h"	/* bit stream module */
 #include "rateconv.h"
 
-#include "enc.h"	/* encoder cores */
-
-#define BITHEADERBUFSIZE (65536)
+#include "enc.h"	/* encoder core */
+////////////////////////////////////////////////////////////////////////////////
+int write_ADIF_header(faacAACStream *as)
+{
+	BsBitStream *bitHeader;
+        unsigned char headerBuf[20];
+	float seconds;
+	int i, bits, bytes;
+	static int SampleRates[] = {96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,0};
 
-/* ---------- functions ---------- */
+	seconds = (float)as->out_sampling_rate/(float)1024;
+	seconds = (float)as->cur_frame/seconds;
 
+	as->total_bits += 17 * 8;
+	bitHeader = BsOpenWrite(200);
 
-int faacEncodeInit(faacAACStream *as, int *samplesToRead, int *bitBufferSize, int *headerSize)
+	for (i = 0; ; i++)
+	{
+		if (SampleRates[i] == as->out_sampling_rate)
+			break;
+		else if (SampleRates[i] == 0)
+		{
+			return FERROR;
+		}
+	}
+
+	// ADIF_Header
+	BsPutBit(bitHeader,'A',8);
+	BsPutBit(bitHeader,'D',8);
+	BsPutBit(bitHeader,'I',8);
+	BsPutBit(bitHeader,'F',8);
+	BsPutBit(bitHeader,0,1);   // Copyright present
+	BsPutBit(bitHeader,0,1);   // Original
+	BsPutBit(bitHeader,0,1);   // Home
+	BsPutBit(bitHeader,0,1);   // Bitstream type
+	BsPutBit(bitHeader,(int)(as->total_bits/seconds),23);  // Bitrate
+	BsPutBit(bitHeader, 0, 4);   // num program config elements
+
+	// ADIF_buffer_fulness
+	BsPutBit(bitHeader, 0, 20);
+
+	// program_config_element
+	BsPutBit(bitHeader,0,4);
+	BsPutBit(bitHeader,as->profile,2);
+	BsPutBit(bitHeader,i,4);
+	BsPutBit(bitHeader,1,4);
+	BsPutBit(bitHeader,0,4);
+	BsPutBit(bitHeader,0,4);
+	BsPutBit(bitHeader,0,2);
+	BsPutBit(bitHeader,0,3);
+	BsPutBit(bitHeader,0,4);
+	BsPutBit(bitHeader,0,1);
+	BsPutBit(bitHeader,0,1);
+	BsPutBit(bitHeader,0,1);
+	// element_list
+	BsPutBit(bitHeader,(as->channels == 2),1);
+	BsPutBit(bitHeader,0,4);
+
+	ByteAlign(bitHeader, 1);
+        // Comment
+	BsPutBit(bitHeader,0,8);
+
+	bits = BsBufferNumBit(bitHeader);
+
+	// Copy bitBuf into bitBuffer here
+	bytes = (int)((bits+7)/8);
+	for (i = 0; i < bytes; i++)
+		headerBuf[i] = bitHeader->data[i];
+	BsClose(bitHeader);
+        // Write header to a file
+	fseek(as->out_file, 0, SEEK_SET);
+	fwrite(headerBuf, 1, 17, as->out_file);
+	return FNO_ERROR;
+}
+////////////////////////////////////////////////////////////////////////////////
+int faac_EncodeInit(faacAACStream *as, char *in_file, char *out_file)
 {
 	int frameNumSample,delayNumSample;
-	int ch;
+	int ch, frames, startupNumFrame;
+	SF_INFO sf_info;
 
-	int startupNumFrame;
+	if (as->raw_audio) {
+		sf_info.format =  SF_FORMAT_RAW;
+		sf_info.format |= SF_FORMAT_PCM_BE;
+		sf_info.channels = 2;
+		sf_info.pcmbitwidth = 16;
+		sf_info.samplerate = 44100;
+		}
 
-	if ((as->inputBuffer = (double**)malloc( as->channels*sizeof(double*)))==NULL)
+	as->in_file = sf_open_read(in_file, &sf_info);
+	if (as->in_file==NULL)
 		return -1;
+
+	as->out_file = fopen(out_file, "wb");
+	if (as->out_file==NULL)
+		return -2;
+
+	frames = (int)(sf_info.samples/1024+0.5);
+
+	as->channels = sf_info.channels;
+	as->in_sampling_rate = sf_info.samplerate;
+	as->out_sampling_rate = (as->out_sampling_rate) ? (as->out_sampling_rate) : sf_info.samplerate;
+	as->cut_off = (as->cut_off) ? (as->cut_off) : ((as->out_sampling_rate)>>1);
+
+	if ((as->inputBuffer = (double**)malloc( as->channels*sizeof(double*)))==NULL)
+		return -3;
 	for (ch=0; ch < as->channels; ch++)
 	{
 		if ((as->inputBuffer[ch]=(double*)malloc( 1024*sizeof(double)))==NULL)
-			return -1;
+			return -4;
 	}
 
-	if((as->bit_rate % 1000)||(as->bit_rate < 16000)) {
-		return -1;
+        as->bit_rate*=1000;
+        if((as->bit_rate % 1000)||(as->bit_rate < 16000)) {
+		return -5;
 	}
 	if (as->channels != 2)
-		return -1;
+		return -6;
 	if ((as->profile != MAIN_PROFILE)&&(as->profile != LOW_PROFILE))
-		return -1;
+		return -7;
 
 	as->total_bits = 0;
 	as->frames = 0;
 	as->cur_frame = 0;
 	as->is_first_frame = 1;
+        as->is_last_frames = 0;
 
 	if (as->in_sampling_rate != as->out_sampling_rate)
 		as->rc_needed = 1;
 	else
 		as->rc_needed = 0;
-	if (as->header_type==ADIF_HEADER) {
-		*headerSize = 17;
-	} else {
-		*headerSize = 0;
-	}
 
-	EncTfInit(as, 0);
+	EncTfInit(as);
 
 	frameNumSample = 1024;
 	delayNumSample = 2*frameNumSample;
 
-	*samplesToRead = frameNumSample * as->channels;
+	as->samplesToRead = frameNumSample * as->channels;
 
 	as->frame_bits = (int)(as->bit_rate*frameNumSample/as->out_sampling_rate+0.5);
-	*bitBufferSize = (int)(((as->frame_bits * 5) + 7)/8);
+	as->bitBufferSize = (int)(((as->frame_bits * 5) + 7)/8);
 
 
 	/* num frames to start up encoder due to delay compensation */
@@ -83,42 +166,60 @@
 			-1,			/* in: alpha for Kaiser window */
 			-1,			/* in: 6dB cutoff freq / input bandwidth */
 			-1,			/* in: 100dB cutoff freq / input bandwidth */
-			samplesToRead);		/* out: num input samples / frame */
-		as->samplesToRead = *samplesToRead;
+			&as->samplesToRead);        /* out: num input samples / frame */
 	} else {
-		*samplesToRead = 1024*as->channels;
-		as->samplesToRead = *samplesToRead;
+		as->samplesToRead = 1024*as->channels;
 	}
 
 	as->savedSize = 0;
 
-	return 0;
+       	if (as->header_type == ADIF_HEADER) {
+                char tmp[17];
+		memset(tmp, 0, 17*sizeof(char));
+		fwrite(tmp, 1, 17, as->out_file);
+	}
+	as->sampleBuffer = (short*) malloc(as->samplesToRead*sizeof(short));
+	as->bitBuffer = (unsigned char*) malloc((as->bitBufferSize+100)*sizeof(char));
+
+	return frames;
 }
-
-int faacEncodeFrame(faacAACStream *as, short *Buffer, int Samples, unsigned char *bitBuffer, int *bitBufSize)
+////////////////////////////////////////////////////////////////////////////////
+int faac_EncodeFrame(faacAACStream *as)
 {
 	int i, j, error;
 	int usedNumBit, usedBytes;
-	int samplesOut, curSample = 0;
+	int samplesOut, curSample = 0, Samples;
 	BsBitStream *bitBuf;
 	float *dataOut;
 	float *data = NULL;
 	int totalBytes = 0;
 
+        if (!as->is_last_frames){
+               	Samples = sf_read_short(as->in_file, as->sampleBuffer, as->samplesToRead);
+                if (Samples < as->samplesToRead) as->is_last_frames = 1;
+                }
+            else {
+                 Samples = 0;
+                 if(as->sampleBuffer){
+                         free(as->sampleBuffer);
+                         as->sampleBuffer = NULL;
+                         }
+                 }
+
 	// Is this the last (incomplete) frame
 	if ((Samples < as->samplesToRead)&&(Samples > 0)) {
 		// Padd with zeros
-		memset(Buffer + Samples, 0, (as->samplesToRead-Samples)*sizeof(short));
+		memset(as->sampleBuffer + Samples, 0, (as->samplesToRead-Samples)*sizeof(short));
 	}
 
 	if (as->rc_needed && (Samples > 0)) {
 		samplesOut = as->savedSize + RateConv (
 			as->rc_buf,			/* in: buffer (handle) */
-			Buffer,		/* in: input data[] */
+			as->sampleBuffer,		/* in: input data[] */
 			as->samplesToRead,		/* in: number of input samples */
 			&dataOut);
 
-		data = malloc((samplesOut)*sizeof(float));
+		data = (float*) malloc((samplesOut)*sizeof(float));
 		for (i = 0; i < as->savedSize; i++)
 			data[i] = as->saved[i];
 		for (j = 0; i < samplesOut; i++, j++)
@@ -125,9 +226,9 @@
 			data[i] = dataOut[j];
 	} else if (Samples > 0) {
 		samplesOut = 1024*as->channels;
-		data = malloc((samplesOut)*sizeof(float));
+		data = (float*) malloc((samplesOut)*sizeof(float));
 		for (i = 0; i < samplesOut; i++)
-			data[i] = Buffer[i];
+			data[i] = as->sampleBuffer[i];
 	} else
 		samplesOut = 1024*as->channels;
 
@@ -135,7 +236,7 @@
 	{
 
 		// Process Buffer
-		if (Buffer) {
+		if (as->sampleBuffer) {
 			if (as->channels == 2)
 			{
 				if (Samples > 0)
@@ -163,7 +264,7 @@
 			as->is_first_frame = 0;
 			as->cur_frame++;
 
-			*bitBufSize = 0;
+			as->bitBufferSize = 0;
 
 			samplesOut -= (as->channels*1024);
 			curSample  += (as->channels*1024);
@@ -194,7 +295,7 @@
 		// Copy bitBuf into bitBuffer here
 		usedBytes = (int)((usedNumBit+7)/8);
 		for (i = 0; i < usedBytes; i++)
-			bitBuffer[i+totalBytes] = bitBuf->data[i];
+			as->bitBuffer[i+totalBytes] = bitBuf->data[i];
 		totalBytes += usedBytes;
 		BsClose(bitBuf);
 
@@ -208,7 +309,7 @@
 
 	}
 
-	*bitBufSize = totalBytes;
+	as->bitBufferSize = totalBytes;
 
 	as->savedSize = samplesOut;
 	for (i = 0; i < samplesOut; i++)
@@ -215,95 +316,19 @@
 		as->saved[i] = data[curSample+i];
 	if (data) free(data);
 
-	return FNO_ERROR;
+       	fwrite(as->bitBuffer, 1, as->bitBufferSize, as->out_file);
+        if (Samples < as->samplesToRead) return F_FINISH;
+                else	return FNO_ERROR;
 }
-
-int faacEncodeFinish(faacAACStream *as, unsigned char *bitBuffer, int *bitBufSize)
+////////////////////////////////////////////////////////////////////////////////
+void faac_EncodeFinish(faacAACStream *as)
 {
-	unsigned char tmpBitBuffer[2048];
-	int tmpBitBufSize, i;
-	faacEncodeFrame(as, NULL, 0, tmpBitBuffer, &tmpBitBufSize);
-	for (i = 0; i < tmpBitBufSize; i++)
-		bitBuffer[i] = tmpBitBuffer[i];
-	faacEncodeFrame(as, NULL, 0, tmpBitBuffer, bitBufSize);
-	for (i = 0; i < *bitBufSize; i++)
-		bitBuffer[i+tmpBitBufSize] = tmpBitBuffer[i];
-	*bitBufSize += tmpBitBufSize;
-
-	return FNO_ERROR;
+	faac_EncodeFrame(as);
+	faac_EncodeFrame(as);
 }
-
-int make_ADIF_header(faacAACStream *as, unsigned char *headerBuf)
+////////////////////////////////////////////////////////////////////////////////
+void faac_EncodeFree(faacAACStream *as)
 {
-	BsBitStream *bitHeader;
-	float seconds;
-	int i, bits, bytes;
-	static int SampleRates[] = {96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,0};
-
-	seconds = (float)as->out_sampling_rate/(float)1024;
-	seconds = (float)as->cur_frame/seconds;
-
-	as->total_bits += 17 * 8;
-	bitHeader = BsOpenWrite(BITHEADERBUFSIZE);
-
-	for (i = 0; ; i++)
-	{
-		if (SampleRates[i] == as->out_sampling_rate)
-			break;
-		else if (SampleRates[i] == 0)
-		{
-			return FERROR;
-		}
-	}
-
-	// ADIF_Header
-	BsPutBit(bitHeader,'A',8);
-	BsPutBit(bitHeader,'D',8);
-	BsPutBit(bitHeader,'I',8);
-	BsPutBit(bitHeader,'F',8);
-	BsPutBit(bitHeader,0,1);   // Copyright present
-	BsPutBit(bitHeader,0,1);   // Original
-	BsPutBit(bitHeader,0,1);   // Home
-	BsPutBit(bitHeader,0,1);   // Bitstream type
-	BsPutBit(bitHeader,(int)(as->total_bits/seconds),23);  // Bitrate
-	BsPutBit(bitHeader, 0, 4);   // num program config elements
-
-	// ADIF_buffer_fulness
-	BsPutBit(bitHeader, 0, 20);
-
-	// program_config_element
-	BsPutBit(bitHeader,0,4);
-	BsPutBit(bitHeader,as->profile,2);
-	BsPutBit(bitHeader,i,4);
-	BsPutBit(bitHeader,1,4);
-	BsPutBit(bitHeader,0,4);
-	BsPutBit(bitHeader,0,4);
-	BsPutBit(bitHeader,0,2);
-	BsPutBit(bitHeader,0,3);
-	BsPutBit(bitHeader,0,4);
-	BsPutBit(bitHeader,0,1);
-	BsPutBit(bitHeader,0,1);
-	BsPutBit(bitHeader,0,1);
-	// element_list
-	BsPutBit(bitHeader,(as->channels == 2),1);
-	BsPutBit(bitHeader,0,4);
-
-	ByteAlign(bitHeader, 1);
-        // Comment
-	BsPutBit(bitHeader,0,8);
-
-	bits = BsBufferNumBit(bitHeader);
-
-	// Copy bitBuf into bitBuffer here
-	bytes = (int)((bits+7)/8);
-	for (i = 0; i < bytes; i++)
-		headerBuf[i] = bitHeader->data[i];
-	BsClose(bitHeader);
-	return FNO_ERROR;
-}
-
-void faacEncodeFree(faacAACStream *as)
-{
 	int ch;
 
 	/* free encoder memory */
@@ -311,12 +336,20 @@
 	if (as->rc_needed)
 		RateConvFree (as->rc_buf);
 
-	for (ch=0; ch < as->channels; ch++)
+	for(ch=0; ch < as->channels; ch++)
 		if(as->inputBuffer[ch]) free(as->inputBuffer[ch]);
 	if(as->inputBuffer) free(as->inputBuffer);
+
+        if (as->header_type==ADIF_HEADER)
+             write_ADIF_header(as);
+
+        sf_close(as->in_file);
+        fclose(as->out_file);
+
+	if (as->bitBuffer)  free(as->bitBuffer);
 }
-
-faacVersion *faacEncodeVersion(void)
+////////////////////////////////////////////////////////////////////////////////
+faacVersion *faac_Version(void)
 {
 	faacVersion *faacv = malloc(sizeof(faacVersion));
 
@@ -323,22 +356,37 @@
 	faacv->DLLMajorVersion = 2;
 	faacv->DLLMinorVersion = 30;
 	faacv->MajorVersion = 0;
-	faacv->MinorVersion = 65;
+	faacv->MinorVersion = 70;
 	strcpy(faacv->HomePage, "http://www.slimline.net/aac/");
 
 	return faacv;
 }
-
+////////////////////////////////////////////////////////////////////////////////
+void faac_InitParams(faacAACStream *as)
+{
+as->profile = MAIN_PROFILE;
+as->header_type = ADTS_HEADER;
+as->use_IS = 0;
+as->use_MS = 0;
+as->use_TNS = 0;
+as->use_LTP = 1;
+as->use_PNS = 0;
+as->cut_off = 0;
+as->bit_rate = 128;
+as->out_sampling_rate = 0;
+as->raw_audio = 0;
+}
+////////////////////////////////////////////////////////////////////////////////
 #ifdef FAAC_DLL
 
 BOOL APIENTRY DllMain(HANDLE hModule,
-                      DWORD  ul_reason_for_call, 
+                      DWORD  ul_reason_for_call,
                       LPVOID lpReserved)
 {
     return TRUE;
 }
 
-#else
+#else  // Not dll
 
 /* You can download libsndfile from http://www.zip.com.au/~erikd/libsndfile/ */
 #ifdef WIN32
@@ -347,8 +395,6 @@
 #include <time.h>
 #endif
 
-#include <sndfile.h>
-
 char *get_filename(char *pPath)
 {
     char *pT;
@@ -403,20 +449,12 @@
 	return;
 }
 
-int parse_arg(int argc, char *argv[],faacAACStream *as, char *FileNames[200], int *FileCount)
+int parse_arg(int argc, char *argv[],faacAACStream *as, char *InFileNames[100], char *OutFileNames[100])
 {
-int i;
-char *argp;
+int i, out_dir_set=0, FileCount=0;
+char *argp, *fnp, out_dir[255];
 
-as->profile = MAIN_PROFILE;
-as->header_type = ADTS_HEADER;
-as->use_IS = 0, as->use_MS = 0, as->use_TNS = 0, as->use_LTP = 1, as->use_PNS = 0;
-as->cut_off = 0;
-as->bit_rate = 128;
-as->out_sampling_rate = 0;
-as->out_dir_set = 0;
-as->raw_audio = 0;
-
+faac_InitParams(as);
 	if (argc == 1) {
 		usage();
 		return -1;
@@ -431,9 +469,10 @@
 
 			if (!strchr(argp, '*') && !strchr(argp, '?'))
 			{
-				FileNames[*FileCount] = malloc((strlen(argv[i])+1)*sizeof(char));
-				strcpy(FileNames[*FileCount], argv[i]);
-				(*FileCount)++;
+				InFileNames[FileCount] = (char*) malloc((strlen(argv[i])+1)*sizeof(char));
+				OutFileNames[FileCount] = (char*) malloc((strlen(argv[i])+1)*sizeof(char));
+				strcpy(InFileNames[FileCount], argv[i]);
+				FileCount++;
 			} else {
 #ifdef WIN32
 				HANDLE hFindFile;
@@ -458,10 +497,10 @@
 				{
 					do
 					{
-						FileNames[*FileCount] = malloc((strlen(fd.cFileName)
+						InFileNames[FileCount] = (char*) malloc((strlen(fd.cFileName)
 							+ strlen(path) + 2)*sizeof(char));
-						strcat(strcpy(FileNames[*FileCount], path), fd.cFileName);
-						(*FileCount)++;
+						strcat(strcpy(InFileNames[FileCount], path), fd.cFileName);
+						FileCount++;
 					} while (FindNextFile(hFindFile, &fd));
 					FindClose(hFindFile);
 				}
@@ -515,8 +554,8 @@
 				as->cut_off = atoi(&argv[i][2]);
 				break;
 			case 'o': case 'O':
-				as->out_dir_set = 1;
-				strcpy(as->out_dir, &argv[i][2]);
+				out_dir_set = 1;
+				strcpy(out_dir, &argv[i][2]);
 				break;
 			case '?':
 				usage();
@@ -524,187 +563,128 @@
 			}
 		}
 	}
-        if ((*FileCount) == 0) {
+        if (FileCount == 0) {
 		return -1;
-	}
-        as->bit_rate*=1000;
-return 0;
-}
+        	}
+            else{
+                for (i = 0; i < FileCount; i++){
+        		if (out_dir_set)
+        			combine_path(OutFileNames[i], out_dir, InFileNames[i]);
+        		else
+        			strcpy(OutFileNames[i], InFileNames[i]);
+        		fnp = strrchr(OutFileNames[i],'.');
+        		fnp[0] = '\0';
+        		strcat(OutFileNames[i],".aac");
+                }
+            }
+return FileCount;
+}
 
-int main(int argc, char *argv[])
+void printVersion(void)
 {
-	int readNumSample;
+faacVersion *faacv;
+faacv = faac_Version();
+printf("FAAC cl (Freeware AAC Encoder)\n");
+printf("FAAC homepage: %s\n", faacv->HomePage);
+printf("Encoder engine version: %d.%d\n\n",
+	faacv->MajorVersion, faacv->MinorVersion);
+if (faacv) free(faacv);
+}
 
-	short *sampleBuffer;
-	unsigned char *bitBuffer;
-	FILE *aacfile;
-	SNDFILE *sndfile;
-	SF_INFO sf_info;
-	int noSamples;
-	int error;
-	int bitBufSize;
-	int curBitBufSize;
-	int headerSize;
-	int i, frames, cfr;
-	char *FileNames[200];
-	int FileCount = 0;
+void printConf(faacAACStream *as)
+{
+printf("AAC configuration:\n");
+printf("----------------------------------------------\n");
+printf("AAC profile: %s.\n", (as->profile==MAIN_PROFILE)?"MAIN":"LOW");
+printf("Bitrate: %dkbps.\n", as->bit_rate);
+printf("Mid/Side (MS) stereo coding: %s.\n",
+	(as->use_MS==1)?"Full":((as->use_MS==0)?"Switching":"Off"));
+printf("Intensity stereo (IS) coding: %s.\n", as->use_IS?"On":"Off");
+printf("Temporal Noise Shaping: %s.\n", as->use_TNS?"On":"Off");
+printf("Long Term Prediction: %s.\n", as->use_LTP?"On":"Off");
+printf("Perceptual Noise Substitution: %s.\n", as->use_PNS?"On":"Off");
+if (as->out_sampling_rate)
+	printf("Output sampling rate: %dHz.\n", as->out_sampling_rate);
+if (as->cut_off)
+	printf("Cut-off frequency: %dHz.\n", as->cut_off);
+if (as->header_type == ADIF_HEADER)
+	printf("Header info: ADIF header (seeking disabled)\n");
+    else if (as->header_type == ADTS_HEADER)
+	printf("Header info: ADTS headers (seeking enabled)\n");
+    else
+	printf("Header info: no headers (seeking disabled)\n");
+printf("----------------------------------------------\n");
+}
 
-	faacAACStream as;
-	faacVersion *faacv;
+int main(int argc, char *argv[])
+{
+	int i, frames, currentFrame, result, FileCount;
+	char *InFileNames[100];
+	char *OutFileNames[100];
 
+	faacAACStream *as;
+
+        /* timing vars */
 	long begin, end;
 	int nTotSecs, nSecs;
 	int nMins;
 
-	faacv = faacEncodeVersion();
-	printf("FAAC cl (Freeware AAC Encoder)\n");
-	printf("FAAC homepage: %s\n", faacv->HomePage);
-	printf("Encoder engine version: %d.%d\n\n",
-		faacv->MajorVersion, faacv->MinorVersion);
-	if (faacv) free(faacv);
+        /* create main aacstream object */
+        as =(faacAACStream *) malloc(sizeof(faacAACStream));
 
+        /* Print version of FAAC */
+        printVersion();
+
 	/* Process command line params */
-        if (parse_arg(argc, argv, &as, FileNames, &FileCount)) return 0;
+        if ((FileCount=parse_arg(argc, argv, as, InFileNames, OutFileNames))<0) return 0;
 
-	printf("AAC profile: %s.\n", (as.profile==MAIN_PROFILE)?"MAIN":"LOW");
-	printf("Bitrate: %dkbps.\n", as.bit_rate/1000);
-	printf("Mid/Side (MS) stereo coding: %s.\n",
-		(as.use_MS==1)?"Full":((as.use_MS==0)?"Switching":"Off"));
-	printf("Intensity stereo (IS) coding: %s.\n", as.use_IS?"On":"Off");
-	printf("Temporal Noise Shaping: %s.\n", as.use_TNS?"On":"Off");
-	printf("Long Term Prediction: %s.\n", as.use_LTP?"On":"Off");
-	printf("Perceptual Noise Substitution: %s.\n", as.use_PNS?"On":"Off");
-//	printf("ADIF header: %s.\n", no_header?"Off":"On");
-	if (as.out_dir_set)
-		printf("Output directory: %s.\n", as.out_dir);
-	if (as.out_sampling_rate)
-		printf("Output sampling rate: %dHz.\n", as.out_sampling_rate);
-	if (as.cut_off)
-		printf("Cut-off frequency: %dHz.\n", as.cut_off);
-	printf("\n");
+        /* Print configuration */
+        printConf(as);
 
+        /* Process input files */
 	for (i = 0; i < FileCount; i++) {
-		char aac_fn[255];
-		char *fnp;
-
-		printf("0%\tBusy encoding %s.\r", FileNames[i]);
-
+		printf("0%\tBusy encoding %s.\r", InFileNames[i]);
 #ifdef WIN32
 		begin = GetTickCount();
 #else
 		begin = clock();
 #endif
-
-		if (as.raw_audio) {
-			sf_info.format =  SF_FORMAT_RAW;
-			sf_info.format |= SF_FORMAT_PCM_BE;
-			sf_info.channels = 2;
-			sf_info.pcmbitwidth = 16;
-			sf_info.samplerate = 44100;
-		}
-
-		sndfile = sf_open_read(FileNames[i], &sf_info);
-		if (sndfile==NULL) {
-			printf("Error while encoding %s.\n", FileNames[i]);
+                /* Init encoder core and retrieve number of frames */
+                if ((frames=faac_EncodeInit(as, InFileNames[i], OutFileNames[i])) < 0) {
+			printf("Error %d while encoding %s.\n",-frames,InFileNames[i]);
 			continue;
 		}
-
-		frames = (int)(sf_info.samples/1024+0.5);
-
-		if (as.out_dir_set)
-			combine_path(aac_fn, as.out_dir, FileNames[i]);
-		else
-			strcpy(aac_fn, FileNames[i]);
-		fnp = strrchr(aac_fn,'.');
-		fnp[0] = '\0';
-		strcat(aac_fn,".aac");
-
-		aacfile = fopen(aac_fn, "wb");
-		if (aacfile==NULL) {
-			printf("Error while encoding %s.\n", FileNames[i]);
-			continue;
-		}
-
-		as.channels = sf_info.channels;
-		as.in_sampling_rate = sf_info.samplerate;
-		as.out_sampling_rate = as.out_sampling_rate ? as.out_sampling_rate : sf_info.samplerate;
-		as.cut_off = as.cut_off ? as.cut_off : (as.out_sampling_rate>>1);
-
-		if (faacEncodeInit(&as, &readNumSample, &bitBufSize, &headerSize) == -1) {
-			printf("Error while encoding %s.\n", FileNames[i]);
-			continue;
-		}
-		sampleBuffer = malloc(readNumSample*sizeof(short));
-
-		bitBuffer = malloc((bitBufSize+100)*sizeof(char));
-
-		if (headerSize > 0) {
-			memset(bitBuffer, 0, headerSize*sizeof(char));
-			// Skip headerSize bytes for ADIF header
-			// They should be written after calling faacEncodeFree
-			fwrite(bitBuffer, 1, headerSize, aacfile);
-		}
-
-		cfr = 0;
-
+                currentFrame = 0;
 		// Keep encoding frames until the end of the audio file
 		do {
-			cfr++;
-
-			noSamples = sf_read_short(sndfile, sampleBuffer, readNumSample);
-
-			error = faacEncodeFrame(&as, sampleBuffer, noSamples, bitBuffer, &curBitBufSize);
-			if (error == FERROR) {
-				printf("Error while encoding %s.\n", FileNames[i]);
+			currentFrame++;
+			result = faac_EncodeFrame(as);
+			if (result == FERROR) {
+				printf("Error while encoding %s.\n", InFileNames[i]);
 				break;
 			}
+			printf("%.2f%%\tBusy encoding %s.\r", min(((double)currentFrame/(double)frames)*100,100),InFileNames[i]);
 
-			fwrite(bitBuffer, 1, curBitBufSize, aacfile);
+		} while (result != F_FINISH);
 
-			printf("%.2f%%\tBusy encoding %s.\r", min(((double)cfr/(double)frames)*100,100),FileNames[i]);
-
-		} while (noSamples == readNumSample);
-
-		if (error == FERROR) {
-			continue;
-		}
-
-		error = faacEncodeFinish(&as, bitBuffer, &curBitBufSize);
-		if (error == FERROR) {
-			printf("Error while encoding %s.\n", FileNames[i]);
-			continue;
-		}
-
-		fwrite(bitBuffer, 1, curBitBufSize, aacfile);
-
-                if (as.header_type==ADIF_HEADER){
-                        make_ADIF_header(&as,bitBuffer);
-			fseek(aacfile, 0, SEEK_SET);
-			fwrite(bitBuffer, 1, headerSize, aacfile);
-                        }
-
-		sf_close(sndfile);
-
-		faacEncodeFree(&as);
-
-		fclose(aacfile);
-
-		if (bitBuffer)  free(bitBuffer);
-		if (sampleBuffer)  free(sampleBuffer);
+                /* finishing last frames and destroying internal data */
+		faac_EncodeFinish(as);
+                faac_EncodeFree(as);
 #ifdef WIN32
 		end = GetTickCount();
 #else
 		end = clock();
 #endif
-
 		nTotSecs = (end-begin)/1000;
 		nMins = nTotSecs / 60;
 		nSecs = nTotSecs - (60*nMins);
-		printf("Encoding %s took:\t%d:%.2d\t\n", FileNames[i], nMins, nSecs);
+		printf("Encoding %s took:\t%d:%.2d\t\n", InFileNames[i], nMins, nSecs);
+                if(InFileNames[i]) free(InFileNames[i]);
+                if(OutFileNames[i]) free(OutFileNames[i]);
 	}
+        if (as) free (as);
 	return FNO_ERROR;
 }
 
-
-#endif
+#endif // end of #ifndef FAAC_DLL