unsigned char* AacEncoder::flush(int* resultSize) {
	*resultSize = -1;
	int enc_size = maxBytesOutput * 2;
	unsigned char* buffer = new unsigned char[enc_size];
	int buffer_pos = 0;

	if (faac_flush_buffer_size) {
		buffer_pos = faacEncEncode(faac, (int32_t *) faac_flush_buffer,
				faac_flush_buffer_size, buffer, enc_size);


		faac_flush_buffer_size = 0;
		if (buffer_pos) {
			if (logging) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,	"flush encode result = %D", buffer_pos);
		} else {
			if (logging) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,	"flush encode error");
		}
	}

	int enc_result = faacEncEncode(faac, NULL, 0, buffer + buffer_pos, enc_size - buffer_pos);
	if (enc_result >= 0) {
		if (enc_result) {
			buffer_pos += enc_result;
			*resultSize = buffer_pos;
			if (logging) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,	"flush result = %D", enc_result);
			return buffer;
		}
	} else {
		if (logging) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, "flush result = %D", enc_result);
		return NULL;
	}
}
Esempio n. 2
0
static int encode_faac(audio_encoder_t *encoder, uint8_t *dest, void *src, int len, int max_size)
{
	// len is divided by the number of bytes per sample
	enc_frame_size = faacEncEncode(faac,  (int32_t*) src,  len / divisor, dest, max_size);
	
	return enc_frame_size;
}
bool BleAudioEncoder_AAC::encode(const QByteArray &data, QByteArray &outputArray)
{
    if (data.size() != getFrameSize()) {
        log_error("aac data is too not equal to %d", getFrameSize());
        return false;
    }

    // A negative value to indicate a failure, the number of vaid bytes
    // in the output buffer otherwise. A return value of zero does not
    // indicate failure.
    int encodedBytes = faacEncEncode(m_faacHandle, (int32_t*)data.data(), m_samplesInputSize, m_outputBuffer, m_maxOutputSize);
    log_info("aac ori data %d , encode data %d", data.size(), encodedBytes);
    if (encodedBytes < 0) {
        log_error("faacEncEncode failed, aac ori data %d , encode data %d", data.size(), encodedBytes);
        return false;
    } else if (encodedBytes == 0) {
        log_trace("audio frame delayed in encoder.");
        return true;
    }

    static unsigned char af[2] = {0xaf, 0x01};

    outputArray.append((char *)af, 2);
    outputArray.append((char*)m_outputBuffer, encodedBytes);

    return true;
}
bool AudioEncoderFAAC::encodePacket(AVPacket* p, FLVTag& tag) {
  assert(encoder);
  // @todo in AudioEncoderFAAC we might want to check if the given packet contains enough bytes using the nsamples_needed member
  // assert(p->data.size() == nsamples_needed);
  
  int written = faacEncEncode(encoder, (int32_t*)&p->data.front(), nsamples_needed, faac_buffer, nbytes_out);
  
  if(written) {
    if(output_file.size() && ofs.is_open()) {
      ofs.write((char*)faac_buffer, written);
    }
  }

  if(written < 0) {
    STREAMER_ERROR("The faac encoder returned an error while encoding the input data: %d\n", written);
    ::exit(EXIT_FAILURE);
  }

  tag.bs.clear();
  tag.bs.putBytes((uint8_t*)faac_buffer, written);
  tag.setData(tag.bs.getPtr(), tag.bs.size());
  tag.makeAudioTag();
  tag.setAACPacketType(FLV_AAC_RAW_DATA);
  tag.setTimeStamp(p->timestamp);

  return true;
}
int AacEncoder::encode(short int* pcm, int length, unsigned char * output) {	
	memcpy(pcmBuf, faac_flush_buffer, sizeof(short) * faac_flush_buffer_size);
	int pcm_buf_pos = faac_flush_buffer_size;

	int enc_size = maxBytesOutput;
	int result = 0;
	int pcm_pos = 0;
	do {
		memcpy(pcmBuf + pcm_buf_pos, pcm + pcm_pos, sizeof(short) * (samplesInput - pcm_buf_pos));
		pcm_pos += samplesInput - pcm_buf_pos;
		
		int enc_result = faacEncEncode(faac, (int32_t *) pcmBuf, samplesInput, output + result, enc_size);
		if (enc_result >= 0) {
			result += enc_result;
		} else {
			result = enc_result;
		}

		pcm_buf_pos = 0;
	} while (result >= 0 && (length - pcm_pos >= samplesInput));

	if (result > 0) {
		faac_flush_buffer_size = length - pcm_pos;
		if (faac_flush_buffer_size > 0) {
			memcpy(faac_flush_buffer, pcm + pcm_pos, sizeof(short) * faac_flush_buffer_size);
		}
	}

	return result;
}
//______________________________________________
uint8_t	AVDMProcessAudio_Faac::getPacket(uint8_t *dest, uint32_t *len, 
					uint32_t *samples)
{				
uint8_t  *buf=dropBuffer;
uint32_t nbSample=0;
uint32_t rdall=0,asked,rd;
int wr;

	asked=_incoming_frame*2*_wavheader->channels;
	rd=_instream->read(asked,buf);
	
	if(rd==0)
		return 0;
	if(rd==MINUS_ONE)
		return 0;		
	    
  // Now encode
  	nbSample= rd/(2*_wavheader->channels);
	switch(_wavheader->channels)
	{
	case 1:
        	wr = faacEncEncode(_handle,
                      (int32_t *)buf,
                      nbSample, // Nb sample for all channels
                      dest,
                      FA_BUFFER_SIZE
		      );
		break;
	case 2:
		
		wr = faacEncEncode(_handle,
                      (int32_t *)buf,
                      nbSample*2, // Nb sample for all channels
                      dest,
                      FA_BUFFER_SIZE
		      );
		break;
	}
		     
	*len=wr;
	*samples=nbSample;
	//printf("Faac: asked :%lu got %lu out len:%d sample:%d\n",asked,rd,wr,nbSample);
	return 1;
}
Esempio n. 7
0
int FAACEncoder::Clean()
{
	if (m_hfaac!=NULL)
	{
		faacEncEncode(m_hfaac, NULL, 0, m_pfaacbuffer, 4096);
		faacEncClose(m_hfaac);
		m_hfaac=NULL;

	}
	return 0;
}
Esempio n. 8
0
int PcmToAac::Encode(int32_t * pbPCMBuffer, unsigned int nPCMBufferSize, unsigned char * pbAACBuffer, unsigned int nMaxOutputBytes)
{
	unsigned int nPCMBitSize = GetPCMBitSize();


	unsigned int nInputSamples = (nPCMBufferSize / (nPCMBitSize / 8));
	if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM faacEncEncode....\n",  __FUNCTION__, __LINE__);
	int nRet = faacEncEncode(hEncoder, (int*) pbPCMBuffer, nInputSamples, pbAACBuffer, nMaxOutputBytes);
	if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM faacEncEncode\n",  __FUNCTION__, __LINE__);

	return nRet;
}
int aacEncoder::aacEncoderProcess(uint8_t* pdata, int pSize, uint8_t* outputBuffer)
{
	if(interrupt)
	{
		faacEncClose(hEncoder);
		return 0;
	}
	unsigned int bytesWritten;
	unsigned int nBufferSize = pSize / (nPCMBitSize / 8);
	bytesWritten = faacEncEncode(hEncoder, (int32_t*)pdata, nBufferSize, outputBuffer, nMaxOutputBytes);
	return bytesWritten;
}
Esempio n. 10
0
static int encode_faac(audio_encoder_t *encoder, uint8_t *dest, void *src, int len, int max_size)
{
	if (encoder->params.channels >= 5)
		reorder_channel_nch(src, AF_CHANNEL_LAYOUT_MPLAYER_DEFAULT,
		                    AF_CHANNEL_LAYOUT_AAC_DEFAULT,
		                    encoder->params.channels,
		                    len / divisor, divisor);

	// len is divided by the number of bytes per sample
	enc_frame_size = faacEncEncode(faac,  (int32_t*) src,  len / divisor, dest, max_size);

	return enc_frame_size;
}
Esempio n. 11
0
/// ±àÂë
int32_t CAacEncoder::Encodec(const char* pSrcBuffer, uint32_t nSrcBuffSize,
                             char* pDestBuffer, uint32_t nDestBufferSize)
{
    // ²ÎÊý¼ì²é
    if(NULL == pSrcBuffer || 0 == nSrcBuffSize
            || NULL == pDestBuffer || nDestBufferSize < m_nMaxOutputBytes)
    {
        return 0;
    }

    return faacEncEncode(m_hHandleEncoder, (int32_t*)pSrcBuffer, m_nInputSamples,
                         (unsigned char*)pDestBuffer, nDestBufferSize);
}
Esempio n. 12
0
static int Faac_encode_frame(AVCodecContext *avctx,
                             unsigned char *frame, int buf_size, void *data)
{
    FaacAudioContext *s = avctx->priv_data;
    int bytes_written;

    bytes_written = faacEncEncode(s->faac_handle,
                                  data,
                                  avctx->frame_size * avctx->channels,
                                  frame,
                                  buf_size);

    return bytes_written;
}
Esempio n. 13
0
static int faac_encode(TCModuleInstance *self,
                       TCFrameAudio *in, TCFrameAudio *out)
{
    PrivateData *pd;
    uint8_t *inptr;
    int nsamples;

    TC_MODULE_SELF_CHECK(self, "encode");

    pd = self->userdata;

    if (in) {
        inptr = in->audio_buf;
        nsamples = in->audio_size / pd->bps;
    } else {
        inptr = NULL;
        nsamples = 0;
    }
    out->audio_len = 0;

    while (pd->audiobuf_len + nsamples >= pd->framesize) {
        int res;
        const int tocopy = (pd->framesize - pd->audiobuf_len) * pd->bps;
        ac_memcpy(pd->audiobuf + pd->audiobuf_len*pd->bps, inptr, tocopy);
        inptr += tocopy;
        nsamples -= tocopy / pd->bps;
        pd->audiobuf_len = 0;
        res = faacEncEncode(pd->handle, (int32_t *)pd->audiobuf, pd->framesize,
                            out->audio_buf + out->audio_len,
                            out->audio_size - out->audio_len);
        if (res > out->audio_size - out->audio_len) {
            tc_log_error(MOD_NAME,
                         "Output buffer overflow!  Try a lower bitrate.");
            return TC_ERROR;
        }
        out->audio_len += res;
    }

    if (nsamples > 0) {
        ac_memcpy(pd->audiobuf + pd->audiobuf_len*pd->bps, inptr,
                  nsamples*pd->bps);
        pd->audiobuf_len += nsamples;
    }
    pd->need_flush = TC_TRUE;
    return TC_OK;
}
Esempio n. 14
0
void ZAAC::AACEncode(BYTE *indata, int inlen)
{
	if (!IsPlay)
	{
		return;
	}
	int nRet = faacEncEncode(hEncoder, (__int32*)indata, nInputSamples, pbAACBuffer, nMaxOutputBytes);
	if(nRet>0)
	{
		if(m_flv)
			m_flv->GetAACData(pbAACBuffer,nRet,clock());
		if(m_mp4)
			m_mp4->GetAACData(pbAACBuffer,nRet,clock());
	//	if (m_rtmp)
	//		m_rtmp->GetAACData(pbAACBuffer,nRet,clock());
	}
}
Esempio n. 15
0
//this function is called by PortAudio when new audio data arrived
int snd_callback(const void *input,
                 void *output,
                 unsigned long frameCount,
                 const PaStreamCallbackTimeInfo* timeInfo,
                 PaStreamCallbackFlags statusFlags,
                 void *userData)
{
		printf("%d: framecount: %ld\n", total_samples, frameCount);
	
    int nRet = faacEncEncode(
        hEncoder, (int*) input, frameCount * channel, pbAACBuffer, nMaxOutputBytes);

    fwrite(pbAACBuffer, 1, nRet, fp_out);
    
    total_samples++;

    return 0;
}
Esempio n. 16
0
unsigned char* FAACEncoder::Encoder(unsigned char*indata,int inlen,int &outlen)
{
	if(m_hfaac!=NULL)
	{
		int nInputSamples = inlen/2;
		outlen = faacEncEncode(m_hfaac, (int32_t*)indata, nInputSamples, m_pfaacbuffer, 4096);
	}else
	{
		outlen=-1;
	}
	if (outlen>0)
	{
		return m_pfaacbuffer;
	}else
	{
		return NULL;
	}
	return NULL;
}
Esempio n. 17
0
int local_write_doublebuffer(unsigned long id, double *dbuff, unsigned long scount, int bytesencoded, int framesize)
{
	unsigned int   i;

	if(pestreams[id].fb_size <= scount * sizeof(float) || !pestreams[id].floatbuffer)
	{
		pestreams[id].fb_size = scount * sizeof(float);
		pestreams[id].floatbuffer = (float*) sys_mem_realloc(pestreams[id].floatbuffer, pestreams[id].fb_size);
	}


	for(i=0; i<scount; i++)
		pestreams[id].floatbuffer[i] = (float)(dbuff[i] * 32767.0);


	bytesencoded = faacEncEncode(pestreams[id].enchandle,
								(int32_t *)pestreams[id].floatbuffer,
								scount,
								pestreams[id].obuffer,
								pestreams[id].maxbytesout);

	if(pestreams[id].ismp4)
	{
		if(bytesencoded)
		{
			unsigned int samples_left = pestreams[id].totalsamples - pestreams[id].encodedsamples + framesize;
			MP4Duration dur           = samples_left > framesize ? framesize : samples_left;
			MP4Duration ofs           = pestreams[id].encodedsamples > 0 ? 0 : framesize;


			MP4WriteSample(pestreams[id].mp4file, pestreams[id].mp4track, pestreams[id].obuffer, bytesencoded, dur, ofs, 1);

			pestreams[id].encodedsamples += (unsigned int)dur;
		}

	}else{
		if(bytesencoded)
			sys_file_write(pestreams[id].fhandle, pestreams[id].obuffer, bytesencoded);
	}
}
Esempio n. 18
0
/***********************************************************************
 * Encode
 ***********************************************************************
 *
 **********************************************************************/
static hb_buffer_t * Encode( hb_work_object_t * w )
{
    hb_work_private_t * pv = w->private_data;

    if( hb_list_bytes( pv->list ) < pv->input_samples * sizeof( float ) )
    {
        /* Need more data */
        return NULL;
    }

    uint64_t pts, pos;
    hb_list_getbytes( pv->list, pv->buf, pv->input_samples * sizeof( float ),
                      &pts, &pos );

    int i;
    float *fltBuf = (float*)pv->buf;
    for ( i = 0; i < pv->input_samples; i++ )
        fltBuf[i] *= 32768.0;
        
    int size = faacEncEncode( pv->faac, (int32_t *)pv->buf, pv->input_samples,
                              pv->obuf, pv->output_bytes );

    // AAC needs four frames before it can start encoding so we'll get nothing
    // on the first three calls to the encoder.
    if ( size > 0 )
    {
        hb_buffer_t * buf = hb_buffer_init( size );
        memcpy( buf->data, pv->obuf, size );
        buf->size        = size;
        buf->s.start     = pv->pts;
        buf->s.duration  = pv->framedur;
        buf->s.stop      = buf->s.start + buf->s.duration;
        buf->s.type      = AUDIO_BUF;
        buf->s.frametype = HB_FRAME_AUDIO;
        pv->pts += pv->framedur;
        return buf;
    }
    return NULL;
}
Esempio n. 19
0
static int Faac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
                             const AVFrame *frame, int *got_packet_ptr)
{
    FaacAudioContext *s = avctx->priv_data;
    int bytes_written, ret;
    int num_samples  = frame ? frame->nb_samples : 0;
    void *samples    = frame ? frame->data[0]    : NULL;

    if ((ret = ff_alloc_packet(avpkt, (7 + 768) * avctx->channels))) {
        av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
        return ret;
    }

    bytes_written = faacEncEncode(s->faac_handle, samples,
                                  num_samples * avctx->channels,
                                  avpkt->data, avpkt->size);
    if (bytes_written < 0) {
        av_log(avctx, AV_LOG_ERROR, "faacEncEncode() error\n");
        return bytes_written;
    }

    /* add current frame to the queue */
    if (frame) {
        if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
            return ret;
    }

    if (!bytes_written)
        return 0;

    /* Get the next frame pts/duration */
    ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
                       &avpkt->duration);

    avpkt->size = bytes_written;
    *got_packet_ptr = 1;
    return 0;
}
Esempio n. 20
0
byte* CAACEncoderManager::Encoder(byte *indata,int inlen,int &outlen)
{

	EnterCriticalSection(&m_hcritical_section);
	if(m_hAACEncoder!=NULL)
	{
		int nInputSamples = inlen/(16/8);
		outlen = faacEncEncode(m_hAACEncoder, (int32_t*)indata, nInputSamples, m_paacbuffer, 2048);
	}else
	{
		outlen=-1;
	}
	LeaveCriticalSection(&m_hcritical_section);
	
	if (outlen>0)
	{
		return m_paacbuffer;
	}else
	{
		return NULL;
	}
	return NULL;
}
Esempio n. 21
0
VOID CSoundRecDlg::ProcessHeader(WAVEHDR * pHdr)
{
	MMRESULT mRes=0;

	TRACE("%d",pHdr->dwUser);
	if(WHDR_DONE==(WHDR_DONE &pHdr->dwFlags))
	{
		ShowDebug(_T("CSoundRecDlg::ProcessHeader, pHdr->dwBytesRecorded=%d"), pHdr->dwBytesRecorded);

		unsigned long nInputSamples = pHdr->dwBytesRecorded / (m_stWFEX.wBitsPerSample / 8);
		ShowDebug(_T("CSoundRecDlg::ProcessHeader faacEncEncode nInputSamples=%d"), nInputSamples);

		long nLeftSamples = nInputSamples;
		BYTE* pData = (BYTE*)pHdr->lpData;
		while (nLeftSamples > 0)
		{
			int nBytesEncoded = faacEncEncode(m_hAACEncoder, (int*)pData, m_nMaxInputSamples, m_pbAACBuffer, m_nMaxOutputBytes);

			ShowDebug(_T("CSoundRecDlg::ProcessHeader faacEncEncode nBytesEncoded=%d"), nBytesEncoded);

			int nBytesWritten = fwrite(m_pbAACBuffer, 1, nBytesEncoded, m_fpAACOutput);

			ShowDebug(_T("CSoundRecDlg::ProcessHeader fwrite nBytesWritten=%d"), nBytesWritten);

			nLeftSamples -= m_nMaxInputSamples;
			pData += m_nMaxInputSamples;
		}
		

		mmioWrite(m_hOPFile,pHdr->lpData,pHdr->dwBytesRecorded);
		mRes=waveInAddBuffer(m_hWaveIn,pHdr,sizeof(WAVEHDR));
		if(mRes!=0)
			StoreError(mRes,TRUE,"File: %s ,Line Number:%d",__FILE__,__LINE__);

		
	}
}
//______________________________________________
uint8_t	AUDMEncoder_Faac::getPacket(uint8_t *dest, uint32_t *len, uint32_t *samples)
{
  uint32_t count=0;
_again:
        *samples = _chunk/_wavheader->channels;
        *len = 0;

        if(!refillBuffer(_chunk ))
        {
          return 0; 
        }
        ADM_assert(tmptail>=tmphead);
        reorderChannels(&(tmpbuffer[tmphead]),*samples);
        *len = faacEncEncode(_handle, (int32_t *)&(tmpbuffer[tmphead]), _chunk, dest, FA_BUFFER_SIZE);
        if(!*len) 
        {
          count++;
          if(count<20)
            goto _again;
          *samples=0;
        }
        tmphead+=_chunk;
        return 1;
}
Esempio n. 23
0
main(int argc, char **argv) {

	int quality = atol(argv[1]);
	int type = atol(argv[2]);

	long samplerate = 16000;
	long channels = 1;
	long samples_input;
	long max_bytes_output;
	faacEncHandle hEncoder;
	faacEncConfigurationPtr mformat;

	hEncoder = faacEncOpen(samplerate, channels, &samples_input, &max_bytes_output);

	printf("Samples input: %ld max_bytes: %ld\n", samples_input, max_bytes_output);


	uint16_t big_input[4096];

	uint16_t input[samples_input];
	char output[max_bytes_output];


	mformat = faacEncGetCurrentConfiguration(hEncoder);


	printf("aacObjectType %d, bitRate %ld, inputFormat %d, outputFormat %d, quantqual %ld, useTns %d, bandWidth %d\n", mformat->aacObjectType, mformat->bitRate, mformat->inputFormat, mformat->outputFormat, mformat->quantqual, mformat->useTns, mformat->bandWidth);

	mformat->inputFormat = 	FAAC_INPUT_16BIT;
	mformat->outputFormat = 1; // ADTP format
	mformat->quantqual = quality;
	mformat->aacObjectType = type;

	if (! faacEncSetConfiguration(hEncoder, mformat)) {
		puts("Don't accept");
		exit(1);
	}

	printf("aacObjectType %d, bitRate %ld, inputFormat %d, outputFormat %d, quantqual %ld, useTns %d, bandWidth %d\n", mformat->aacObjectType, mformat->bitRate, mformat->inputFormat, mformat->outputFormat, mformat->quantqual, mformat->useTns, mformat->bandWidth);


	int written, r, file;

	int ofile = creat("out.aac", 00600);

	while( (r = read(0, input, samples_input * sizeof(uint16_t))) > 0   ) {
		written = faacEncEncode(hEncoder, (short *) input, r/sizeof(uint16_t), output, max_bytes_output);
		if (written > 0) {
			write(ofile, output, written);
		}
	}

	// Save last frames
	while ((written = faacEncEncode(hEncoder, (short *) input, 0, output, max_bytes_output)) > 0) {
			write(ofile, output, written);
	}

	faacEncClose(hEncoder);
	close(ofile);

}
Esempio n. 24
0
void AACStream::SendData(uint8_t *buf, uint32_t size, struct timeval *ts)
{

  int16_t *pcmInPt=(int16_t *)buf;
  uint32_t i,pcmLen= size>>1;

#ifdef AACSTREAM_DEBUG
  DEBUG("data size %d", size);
  //Write to MICIn.pcm file
  fwrite(pcmInPt, sizeof(int16_t), pcmLen, pfOutputMIC);
#endif

  for(i=0;i<pcmLen;i++){
    if((uint16_t)*pcmInPt == 0x8000)
	*pcmInPt=0x8001;
    *pcmAACbufPt++=*pcmInPt++;
    aac_in_count++;
    if(aac_in_count == samplesInput){
      pcmAACbufPt= pcmAACbuf;
#ifdef AACSTREAM_DEBUG
      DEBUG("aac_in_count=%d...!!\n",aac_in_count);
#endif
      aac_in_count=0;

      /* call the actual encoding routine */
      bytesWritten = faacEncEncode(hEncoder,(int32_t *)pcmAACbuf, samplesInput, bitbuf, maxBytesOutput);
#ifdef AACSTREAM_DEBUG
      DEBUG("AAC bytesWritten=%d...!!\n",bytesWritten);
#endif
      if (bytesWritten > 0){
#ifdef AACSTREAM_DEBUG
        DEBUG("AAC bytesWritten=%d...!!\n",bytesWritten);
        /* write bitstream to aac file */
        fwrite(bitbuf, 1, bytesWritten, pfOutputAAC);
#endif
        buf= bitbuf;
        size= bytesWritten;

        ats += aacDuration;
        LinkedListNode<BaseOutStream *> *pTemp = _pOutStreams;
        while (pTemp != NULL) {
          switch(pTemp->info->GetType()){
            case ST_OUT_NET_RTMP_4_RTMP:
              _dataBuffer.ReadFromBuffer(RTMPAACRawHeader, sizeof(RTMPAACRawHeader));
              _dataBuffer.ReadFromBuffer(buf, size);
              if(!pTemp->info->FeedData(GETIBPOINTER(_dataBuffer), GETAVAILABLEBYTESCOUNT(_dataBuffer), 0, GETAVAILABLEBYTESCOUNT(_dataBuffer), ats, true)){
                FATAL("Unable to feed OS: %p", pTemp->info);
              }
              _dataBuffer.IgnoreAll();
              break;
            default:
              if (!pTemp->info->FeedData(buf, size, 0, 0, ats, true)) {
                FATAL("Unable to feed OS: %p", pTemp->info);
              }
              break;
          }
          pTemp = pTemp->pPrev;
        }



      } else if (bytesWritten < 0) {
        FATAL("faacEncEncode fail...!!\n");
        exit(1);
      }
    }

  }

}
Esempio n. 25
0
int main(int argc, char* argv[])
{
    unsigned long nSampleRate = 11025;  // 采样率
    unsigned int nChannels = 1;         // 声道数
    unsigned int nPCMBitSize = 16;      // 单样本位数
    unsigned long nInputSamples = 0;
    unsigned long nMaxOutputBytes = 0;
    int nRet;
    faacEncHandle hEncoder;
    faacEncConfigurationPtr pConfiguration; 

    int nBytesRead;
    int nPCMBufferSize;
    unsigned char* pbPCMBuffer;
    unsigned char* pbAACBuffer;

    FILE* fpIn; // WAV file for input
    FILE* fpOut; // AAC file for output

    fpIn = fopen("in.wav", "rb");
    fpOut = fopen("out.aac", "wb");

    // (1) Open FAAC engine
    hEncoder = faacEncOpen(nSampleRate, nChannels, &nInputSamples, &nMaxOutputBytes);
    if(hEncoder == NULL) {
        printf("[ERROR] Failed to call faacEncOpen()\n");
        return -1;
    }

    nPCMBufferSize = nInputSamples * nPCMBitSize / 8;
    pbPCMBuffer = new unsigned char [nPCMBufferSize];
    pbAACBuffer = new unsigned char [nMaxOutputBytes];

    // (2.1) Get current encoding configuration
    pConfiguration = faacEncGetCurrentConfiguration(hEncoder);
    pConfiguration->inputFormat = FAAC_INPUT_16BIT;

    // (2.2) Set encoding configuration
    nRet = faacEncSetConfiguration(hEncoder, pConfiguration);

    for(int i = 0; 1; i++) {
        // 读入的实际字节数,最大不会超过nPCMBufferSize,一般只有读到文件尾时才不是这个值
        nBytesRead = fread(pbPCMBuffer, 1, nPCMBufferSize, fpIn);

        // 输入样本数,用实际读入字节数计算,一般只有读到文件尾时才不是nPCMBufferSize/(nPCMBitSize/8);
        nInputSamples = nBytesRead / (nPCMBitSize / 8);

        // (3) Encode
        nRet = faacEncEncode(
        hEncoder, (int*) pbPCMBuffer, nInputSamples, pbAACBuffer, nMaxOutputBytes);

        fwrite(pbAACBuffer, 1, nRet, fpOut);

        printf("%d: faacEncEncode returns %d\n", i, nRet);

        if(nBytesRead <= 0) {
            break;
        }
    }

    // (4) Close FAAC engine
    nRet = faacEncClose(hEncoder);

    delete[] pbPCMBuffer;
    delete[] pbAACBuffer;
    fclose(fpIn);
    fclose(fpOut);

    //getchar();

    return 0;
}
Esempio n. 26
0
/*------------------------------------------------------------------------------
 *  Write data to the encoder
 *----------------------------------------------------------------------------*/
unsigned int
FaacEncoder :: write (  const void    * buf,
                        unsigned int    len )           throw ( Exception )
{
    if ( !isOpen() || len == 0 ) {
        return 0;
    }

    unsigned int    channels         = getInChannel();
    unsigned int    bitsPerSample    = getInBitsPerSample();
    unsigned int    sampleSize       = (bitsPerSample / 8) * channels;
    unsigned char * b                = (unsigned char*) buf;
    unsigned int    processed        = len - (len % sampleSize);
    unsigned int    nSamples         = processed / sampleSize;
    unsigned char * faacBuf          = new unsigned char[maxOutputBytes];
    int             samples          = (int) nSamples * channels;
    int             processedSamples = 0;



    if ( converter ) {
        unsigned int         converted;
#ifdef HAVE_SRC_LIB
        src_short_to_float_array ((short *) b, (float *) converterData.data_in, samples);
        converterData.input_frames   = nSamples;
        converterData.data_out = resampledOffset + (resampledOffsetSize * channels);
        int srcError = src_process (converter, &converterData);
        if (srcError)
             throw Exception (__FILE__, __LINE__, "libsamplerate error: ", src_strerror (srcError));
        converted = converterData.output_frames_gen;
#else
        int         inCount  = nSamples;
        short int     * shortBuffer  = new short int[samples];
        int         outCount = (int) (inCount * resampleRatio);
        Util::conv( bitsPerSample, b, processed, shortBuffer, isInBigEndian());
        converted = converter->resample( inCount,
                                         outCount+1,
                                         shortBuffer,
                                         &resampledOffset[resampledOffsetSize*channels]);
        delete[] shortBuffer;
#endif
        resampledOffsetSize += converted;

        // encode samples (if enough)
        while(resampledOffsetSize - processedSamples >= inputSamples/channels) {
            int outputBytes;
#ifdef HAVE_SRC_LIB
            short *shortData = new short[inputSamples];
            src_float_to_short_array(resampledOffset + (processedSamples * channels),
                                     shortData, inputSamples) ;
            outputBytes = faacEncEncode(encoderHandle,
                                       (int32_t*) shortData,
                                        inputSamples,
                                        faacBuf,
                                        maxOutputBytes);
            delete [] shortData;
#else
            outputBytes = faacEncEncode(encoderHandle,
                                       (int32_t*) &resampledOffset[processedSamples*channels],
                                        inputSamples,
                                        faacBuf,
                                        maxOutputBytes);
#endif
            getSink()->write(faacBuf, outputBytes);
            processedSamples+=inputSamples/channels;
        }

        if (processedSamples && (int) resampledOffsetSize >= processedSamples) {
            resampledOffsetSize -= processedSamples;
            //move least part of resampled data to beginning
            if(resampledOffsetSize)
#ifdef HAVE_SRC_LIB
                resampledOffset = (float *) memmove(resampledOffset, &resampledOffset[processedSamples*channels],
                                                    resampledOffsetSize*channels*sizeof(float));
#else
                resampledOffset = (short *) memmove(resampledOffset, &resampledOffset[processedSamples*channels],
                                                    resampledOffsetSize*sampleSize);
#endif
        }
    } else {
        while (processedSamples < samples) {
            int     outputBytes;
            int     inSamples = samples - processedSamples < (int) inputSamples
                              ? samples - processedSamples
                              : inputSamples;

            outputBytes = faacEncEncode(encoderHandle,
                                       (int32_t*) (b + processedSamples/sampleSize),
                                        inSamples,
                                        faacBuf,
                                        maxOutputBytes);
            getSink()->write(faacBuf, outputBytes);

            processedSamples += inSamples;
        }
    }

    delete[] faacBuf;

    return samples * sampleSize;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
    int frames, currentFrame;
    faacEncHandle hEncoder;
    pcmfile_t *infile = NULL;

    unsigned long samplesInput, maxBytesOutput, totalBytesWritten=0;

    faacEncConfigurationPtr myFormat;
    unsigned int mpegVersion = MPEG2;
    unsigned int objectType = LOW;
    unsigned int useMidSide = 1;
    static unsigned int useTns = DEFAULT_TNS;
    enum container_format container = NO_CONTAINER;
    int optimizeFlag = 0;
    enum stream_format stream = ADTS_STREAM;
    int cutOff = -1;
    int bitRate = 0;
    unsigned long quantqual = 0;
    int chanC = 3;
    int chanLF = 4;

    char *audioFileName = NULL;
    char *aacFileName = NULL;
    char *aacFileExt = NULL;
    int aacFileNameGiven = 0;

    float *pcmbuf;
    int *chanmap = NULL;

    unsigned char *bitbuf;
    int samplesRead = 0;
    const char *dieMessage = NULL;

    int rawChans = 0; // disabled by default
    int rawBits = 16;
    int rawRate = 44100;
    int rawEndian = 1;

    int shortctl = SHORTCTL_NORMAL;

    FILE *outfile = NULL;

#ifdef HAVE_LIBMP4V2
    MP4FileHandle MP4hFile = MP4_INVALID_FILE_HANDLE;
    MP4TrackId MP4track = 0;
    unsigned int ntracks = 0, trackno = 0;
    unsigned int ndiscs = 0, discno = 0;
    u_int8_t compilation = 0;
    const char *artist = NULL, *title = NULL, *album = NULL, *year = NULL,
      *genre = NULL, *comment = NULL, *writer = NULL;
    u_int8_t *art = NULL;
    u_int64_t artSize = 0;
    u_int64_t total_samples = 0;
    u_int64_t encoded_samples = 0;
    unsigned int delay_samples;
    unsigned int frameSize;
#endif
    char *faac_id_string;
    char *faac_copyright_string;

#ifndef _WIN32
    // install signal handler
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
#endif

    // get faac version
    if (faacEncGetVersion(&faac_id_string, &faac_copyright_string) == FAAC_CFG_VERSION)
    {
        fprintf(stderr, "Freeware Advanced Audio Coder\nFAAC %s\n\n", faac_id_string);
    }
    else
    {
        fprintf(stderr, __FILE__ "(%d): wrong libfaac version\n", __LINE__);
        return 1;
    }

    /* begin process command line */
    progName = argv[0];
    while (1) {
        static struct option long_options[] = {
            { "help", 0, 0, 'h'},
            { "long-help", 0, 0, 'H'},
            { "raw", 0, 0, 'r'},
            { "no-midside", 0, 0, NO_MIDSIDE_FLAG},
            { "cutoff", 1, 0, 'c'},
            { "quality", 1, 0, 'q'},
            { "pcmraw", 0, 0, 'P'},
            { "pcmsamplerate", 1, 0, 'R'},
            { "pcmsamplebits", 1, 0, 'B'},
            { "pcmchannels", 1, 0, 'C'},
            { "shortctl", 1, 0, SHORTCTL_FLAG},
            { "tns", 0, 0, TNS_FLAG},
            { "no-tns", 0, 0, NO_TNS_FLAG},
            { "mpeg-version", 1, 0, MPEGVERS_FLAG},
            { "obj-type", 1, 0, OBJTYPE_FLAG},
            { "license", 0, 0, 'L'},
#ifdef HAVE_LIBMP4V2
            { "createmp4", 0, 0, 'w'},
            { "optimize", 0, 0, 's'},
            { "artist", 1, 0, ARTIST_FLAG},
            { "title", 1, 0, TITLE_FLAG},
            { "album", 1, 0, ALBUM_FLAG},
            { "track", 1, 0, TRACK_FLAG},
            { "disc", 1, 0, DISC_FLAG},
            { "genre", 1, 0, GENRE_FLAG},
            { "year", 1, 0, YEAR_FLAG},
            { "cover-art", 1, 0, COVER_ART_FLAG},
            { "comment", 1, 0, COMMENT_FLAG},
        { "writer", 1, 0, WRITER_FLAG},
        { "compilation", 0, 0, COMPILATION_FLAG},
#endif
        { "pcmswapbytes", 0, 0, 'X'},
            { 0, 0, 0, 0}
        };
        int c = -1;
        int option_index = 0;

        c = getopt_long(argc, argv, "Hhb:m:o:rnc:q:PR:B:C:I:X"
#ifdef HAVE_LIBMP4V2
                        "ws"
#endif
            ,long_options, &option_index);

        if (c == -1)
            break;

        if (!c)
        {
          dieMessage = usage;
          break;
        }

        switch (c) {
    case 'o':
        {
            int l = strlen(optarg);
        aacFileName = malloc(l+1);
        memcpy(aacFileName, optarg, l);
        aacFileName[l] = '\0';
        aacFileNameGiven = 1;
        }
        break;
        case 'r': {
            stream = RAW_STREAM;
            break;
        }
        case NO_MIDSIDE_FLAG: {
            useMidSide = 0;
            break;
        }
        case 'c': {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0) {
                cutOff = i;
            }
            break;
        }
        case 'b': {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                bitRate = 1000 * i;
            }
            break;
        }
        case 'q':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                if (i > 0 && i < 1000)
                    quantqual = i;
            }
            break;
        }
        case 'I':
            sscanf(optarg, "%d,%d", &chanC, &chanLF);
            break;
        case 'P':
            rawChans = 2; // enable raw input
            break;
        case 'R':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                rawRate = i;
                rawChans = (rawChans > 0) ? rawChans : 2;
            }
            break;
        }
        case 'B':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
            {
                if (i > 32)
                    i = 32;
                if (i < 8)
                    i = 8;
                rawBits = i;
                rawChans = (rawChans > 0) ? rawChans : 2;
            }
            break;
        }
        case 'C':
        {
            unsigned int i;
            if (sscanf(optarg, "%u", &i) > 0)
                rawChans = i;
            break;
        }
#ifdef HAVE_LIBMP4V2
        case 'w':
        container = MP4_CONTAINER;
            break;
        case 's':
        optimizeFlag = 1;
            break;
    case ARTIST_FLAG:
        artist = optarg;
        break;
    case WRITER_FLAG:
        writer = optarg;
        break;
    case TITLE_FLAG:
        title = optarg;
        break;
    case ALBUM_FLAG:
        album = optarg;
        break;
    case TRACK_FLAG:
        sscanf(optarg, "%d/%d", &trackno, &ntracks);
        break;
    case DISC_FLAG:
        sscanf(optarg, "%d/%d", &discno, &ndiscs);
        break;
    case COMPILATION_FLAG:
        compilation = 0x1;
        break;
    case GENRE_FLAG:
        genre = optarg;
        break;
    case YEAR_FLAG:
        year = optarg;
        break;
    case COMMENT_FLAG:
        comment = optarg;
        break;
    case COVER_ART_FLAG: {
        FILE *artFile = fopen(optarg, "rb");

        if(artFile) {
            u_int64_t r;

            fseek(artFile, 0, SEEK_END);
        artSize = ftell(artFile);

        art = malloc(artSize);

            fseek(artFile, 0, SEEK_SET);
        clearerr(artFile);

        r = fread(art, artSize, 1, artFile);

        if (r != 1) {
            dieMessage = "Error reading cover art file!\n";
            free(art);
            art = NULL;
        } else if (artSize < 12 || !check_image_header(art)) {
            /* the above expression checks the image signature */
            dieMessage = "Unsupported cover image file format!\n";
            free(art);
            art = NULL;
        }

        fclose(artFile);
        } else {
            dieMessage = "Error opening cover art file!\n";
        }

        break;
    }
#endif
        case SHORTCTL_FLAG:
            shortctl = atoi(optarg);
            break;
        case TNS_FLAG:
            useTns = 1;
            break;
        case NO_TNS_FLAG:
            useTns = 0;
            break;
    case MPEGVERS_FLAG:
            mpegVersion = atoi(optarg);
            switch(mpegVersion)
            {
            case 2:
                mpegVersion = MPEG2;
                break;
            case 4:
                mpegVersion = MPEG4;
                break;
            default:
            dieMessage = "Unrecognised MPEG version!\n";
            }
            break;
#if 0
    case OBJTYPE_FLAG:
        if (!strcasecmp(optarg, "LC"))
                objectType = LOW;
        else if (!strcasecmp(optarg, "Main"))
            objectType = MAIN;
        else if (!strcasecmp(optarg, "LTP")) {
            mpegVersion = MPEG4;
        objectType = LTP;
        } else
            dieMessage = "Unrecognised object type!\n";
        break;
#endif
        case 'L':
        fprintf(stderr, faac_copyright_string);
        dieMessage = license;
        break;
    case 'X':
      rawEndian = 0;
      break;
    case 'H':
      dieMessage = long_help;
      break;
    case 'h':
          dieMessage = short_help;
      break;
    case '?':
        default:
      dieMessage = usage;
          break;
        }
    }

    /* check that we have at least one non-option arguments */
    if (!dieMessage && (argc - optind) > 1 && aacFileNameGiven)
        dieMessage = "Cannot encode several input files to one output file.\n";

    if (argc - optind < 1 || dieMessage)
    {
        fprintf(stderr, dieMessage ? dieMessage : usage,
           progName, progName, progName, progName);
        return 1;
    }

    while (argc - optind > 0) {

    /* get the input file name */
    audioFileName = argv[optind++];

    /* generate the output file name, if necessary */
    if (!aacFileNameGiven) {
        char *t = strrchr(audioFileName, '.');
    int l = t ? strlen(audioFileName) - strlen(t) : strlen(audioFileName);

#ifdef HAVE_LIBMP4V2
    aacFileExt = container == MP4_CONTAINER ? ".m4a" : ".aac";
#else
    aacFileExt = ".aac";
#endif

    aacFileName = malloc(l+1+4);
    memcpy(aacFileName, audioFileName, l);
    memcpy(aacFileName + l, aacFileExt, 4);
    aacFileName[l+4] = '\0';
    } else {
        aacFileExt = strrchr(aacFileName, '.');

        if (aacFileExt && (!strcmp(".m4a", aacFileExt) || !strcmp(".m4b", aacFileExt) || !strcmp(".mp4", aacFileExt)))
#ifndef HAVE_LIBMP4V2
        fprintf(stderr, "WARNING: MP4 support unavailable!\n");
#else
        container = MP4_CONTAINER;
#endif
    }

    /* open the audio input file */
    if (rawChans > 0) // use raw input
    {
        infile = wav_open_read(audioFileName, 1);
    if (infile)
    {
        infile->bigendian = rawEndian;
        infile->channels = rawChans;
        infile->samplebytes = rawBits / 8;
        infile->samplerate = rawRate;
        infile->samples /= (infile->channels * infile->samplebytes);
    }
    }
    else // header input
        infile = wav_open_read(audioFileName, 0);

    if (infile == NULL)
    {
        fprintf(stderr, "Couldn't open input file %s\n", audioFileName);
    return 1;
    }


    /* open the encoder library */
    hEncoder = faacEncOpen(infile->samplerate, infile->channels,
        &samplesInput, &maxBytesOutput);

#ifdef HAVE_LIBMP4V2
    if (container != MP4_CONTAINER && (ntracks || trackno || artist ||
                       title ||  album || year || art ||
                       genre || comment || discno || ndiscs ||
                       writer || compilation))
    {
        fprintf(stderr, "Metadata requires MP4 output!\n");
    return 1;
    }

    if (container == MP4_CONTAINER)
    {
        mpegVersion = MPEG4;
    stream = RAW_STREAM;
    }

    frameSize = samplesInput/infile->channels;
    delay_samples = frameSize; // encoder delay 1024 samples
#endif
    pcmbuf = (float *)malloc(samplesInput*sizeof(float));
    bitbuf = (unsigned char*)malloc(maxBytesOutput*sizeof(unsigned char));
    chanmap = mkChanMap(infile->channels, chanC, chanLF);
    if (chanmap)
    {
        fprintf(stderr, "Remapping input channels: Center=%d, LFE=%d\n",
            chanC, chanLF);
    }

    if (cutOff <= 0)
    {
        if (cutOff < 0) // default
            cutOff = 0;
        else // disabled
            cutOff = infile->samplerate / 2;
    }
    if (cutOff > (infile->samplerate / 2))
        cutOff = infile->samplerate / 2;

    /* put the options in the configuration struct */
    myFormat = faacEncGetCurrentConfiguration(hEncoder);
    myFormat->aacObjectType = objectType;
    myFormat->mpegVersion = mpegVersion;
    myFormat->useTns = useTns;
    switch (shortctl)
    {
    case SHORTCTL_NOSHORT:
      fprintf(stderr, "disabling short blocks\n");
      myFormat->shortctl = shortctl;
      break;
    case SHORTCTL_NOLONG:
      fprintf(stderr, "disabling long blocks\n");
      myFormat->shortctl = shortctl;
      break;
    }
    if (infile->channels >= 6)
        myFormat->useLfe = 1;
    myFormat->allowMidside = useMidSide;
    if (bitRate)
        myFormat->bitRate = bitRate / infile->channels;
    myFormat->bandWidth = cutOff;
    if (quantqual > 0)
        myFormat->quantqual = quantqual;
    myFormat->outputFormat = stream;
    myFormat->inputFormat = FAAC_INPUT_FLOAT;
    if (!faacEncSetConfiguration(hEncoder, myFormat)) {
        fprintf(stderr, "Unsupported output format!\n");
#ifdef HAVE_LIBMP4V2
        if (container == MP4_CONTAINER) MP4Close(MP4hFile);
#endif
        return 1;
    }

#ifdef HAVE_LIBMP4V2
    /* initialize MP4 creation */
    if (container == MP4_CONTAINER) {
        unsigned char *ASC = 0;
        unsigned long ASCLength = 0;
    char *version_string;

#ifdef MP4_CREATE_EXTENSIBLE_FORMAT
    /* hack to compile against libmp4v2 >= 1.0RC3
     * why is there no version identifier in mp4.h? */
        MP4hFile = MP4Create(aacFileName, MP4_DETAILS_ERROR, 0);
#else
    MP4hFile = MP4Create(aacFileName, MP4_DETAILS_ERROR, 0, 0);
#endif
        if (!MP4_IS_VALID_FILE_HANDLE(MP4hFile)) {
            fprintf(stderr, "Couldn't create output file %s\n", aacFileName);
            return 1;
        }

        MP4SetTimeScale(MP4hFile, 90000);
        MP4track = MP4AddAudioTrack(MP4hFile, infile->samplerate, MP4_INVALID_DURATION, MP4_MPEG4_AUDIO_TYPE);
        MP4SetAudioProfileLevel(MP4hFile, 0x0F);
        faacEncGetDecoderSpecificInfo(hEncoder, &ASC, &ASCLength);
        MP4SetTrackESConfiguration(MP4hFile, MP4track, ASC, ASCLength);
    free(ASC);

    /* set metadata */
    version_string = malloc(strlen(faac_id_string) + 6);
    strcpy(version_string, "FAAC ");
    strcpy(version_string + 5, faac_id_string);
    MP4SetMetadataTool(MP4hFile, version_string);
    free(version_string);

    if (artist) MP4SetMetadataArtist(MP4hFile, artist);
    if (writer) MP4SetMetadataWriter(MP4hFile, writer);
    if (title) MP4SetMetadataName(MP4hFile, title);
    if (album) MP4SetMetadataAlbum(MP4hFile, album);
    if (trackno > 0) MP4SetMetadataTrack(MP4hFile, trackno, ntracks);
    if (discno > 0) MP4SetMetadataDisk(MP4hFile, discno, ndiscs);
    if (compilation) MP4SetMetadataCompilation(MP4hFile, compilation);
    if (year) MP4SetMetadataYear(MP4hFile, year);
    if (genre) MP4SetMetadataGenre(MP4hFile, genre);
    if (comment) MP4SetMetadataComment(MP4hFile, comment);
        if (artSize) {
        MP4SetMetadataCoverArt(MP4hFile, art, artSize);
        free(art);
    }
    }
    else
    {
#endif
        /* open the aac output file */
        if (!strcmp(aacFileName, "-"))
        {
            outfile = stdout;
        }
        else
        {
            outfile = fopen(aacFileName, "wb");
        }
        if (!outfile)
        {
            fprintf(stderr, "Couldn't create output file %s\n", aacFileName);
            return 1;
        }
#ifdef HAVE_LIBMP4V2
    }
#endif

    cutOff = myFormat->bandWidth;
    quantqual = myFormat->quantqual;
    bitRate = myFormat->bitRate;
    if (bitRate)
      fprintf(stderr, "Average bitrate: %d kbps\n",
          (bitRate + 500)/1000*infile->channels);
    fprintf(stderr, "Quantization quality: %ld\n", quantqual);
    fprintf(stderr, "Bandwidth: %d Hz\n", cutOff);
    fprintf(stderr, "Object type: ");
    switch(objectType)
    {
    case LOW:
        fprintf(stderr, "Low Complexity");
        break;
    case MAIN:
        fprintf(stderr, "Main");
        break;
    case LTP:
        fprintf(stderr, "LTP");
        break;
    }
    fprintf(stderr, "(MPEG-%d)", (mpegVersion == MPEG4) ? 4 : 2);
    if (myFormat->useTns)
        fprintf(stderr, " + TNS");
    if (myFormat->allowMidside)
        fprintf(stderr, " + M/S");
    fprintf(stderr, "\n");

    fprintf(stderr, "Container format: ");
    switch(container)
    {
    case NO_CONTAINER:
      switch(stream)
    {
    case RAW_STREAM:
      fprintf(stderr, "Headerless AAC (RAW)\n");
      break;
    case ADTS_STREAM:
      fprintf(stderr, "Transport Stream (ADTS)\n");
      break;
    }
        break;
#ifdef HAVE_LIBMP4V2
    case MP4_CONTAINER:
        fprintf(stderr, "MPEG-4 File Format (MP4)\n");
        break;
#endif
    }

    if (outfile
#ifdef HAVE_LIBMP4V2
        || MP4hFile != MP4_INVALID_FILE_HANDLE
#endif
       )
    {
        int showcnt = 0;
#ifdef _WIN32
        long begin = GetTickCount();
#endif
        if (infile->samples)
            frames = ((infile->samples + 1023) / 1024) + 1;
        else
            frames = 0;
        currentFrame = 0;

        fprintf(stderr, "Encoding %s to %s\n", audioFileName, aacFileName);
        if (frames != 0)
            fprintf(stderr, "   frame          | bitrate | elapsed/estim | "
            "play/CPU | ETA\n");
        else
            fprintf(stderr, " frame | elapsed | play/CPU\n");

        /* encoding loop */
#ifdef _WIN32
    for (;;)
#else
        while (running)
#endif
        {
            int bytesWritten;

            samplesRead = wav_read_float32(infile, pcmbuf, samplesInput, chanmap);

#ifdef HAVE_LIBMP4V2
            total_samples += samplesRead / infile->channels;
#endif

            /* call the actual encoding routine */
            bytesWritten = faacEncEncode(hEncoder,
                (int32_t *)pcmbuf,
                samplesRead,
                bitbuf,
                maxBytesOutput);

            if (bytesWritten)
            {
                currentFrame++;
                showcnt--;
        totalBytesWritten += bytesWritten;
            }

            if ((showcnt <= 0) || !bytesWritten)
            {
                double timeused;
#ifdef __unix__
                struct rusage usage;
#endif
#ifdef _WIN32
                char percent[MAX_PATH + 20];
                timeused = (GetTickCount() - begin) * 1e-3;
#else
#ifdef __unix__
                if (getrusage(RUSAGE_SELF, &usage) == 0) {
                    timeused = (double)usage.ru_utime.tv_sec +
                        (double)usage.ru_utime.tv_usec * 1e-6;
                }
                else
                    timeused = 0;
#else
                timeused = (double)clock() * (1.0 / CLOCKS_PER_SEC);
#endif
#endif
                if (currentFrame && (timeused > 0.1))
                {
                    showcnt += 50;

                    if (frames != 0)
                        fprintf(stderr,
                            "\r%5d/%-5d (%3d%%)|  %5.1f  | %6.1f/%-6.1f | %7.2fx | %.1f ",
                            currentFrame, frames, currentFrame*100/frames,
                ((double)totalBytesWritten * 8.0 / 1000.0) /
                ((double)infile->samples / infile->samplerate * currentFrame / frames),
                            timeused,
                            timeused * frames / currentFrame,
                            (1024.0 * currentFrame / infile->samplerate) / timeused,
                            timeused  * (frames - currentFrame) / currentFrame);
                    else
                        fprintf(stderr,
                            "\r %5d |  %6.1f | %7.2fx ",
                            currentFrame,
                            timeused,
                            (1024.0 * currentFrame / infile->samplerate) / timeused);

                    fflush(stderr);
#ifdef _WIN32
                    if (frames != 0)
                    {
                        sprintf(percent, "%.2f%% encoding %s",
                            100.0 * currentFrame / frames, audioFileName);
                        SetConsoleTitle(percent);
                    }
#endif
                }
            }

            /* all done, bail out */
            if (!samplesRead && !bytesWritten)
                break ;

            if (bytesWritten < 0)
            {
                fprintf(stderr, "faacEncEncode() failed\n");
                break ;
            }

            if (bytesWritten > 0)
            {
#ifdef HAVE_LIBMP4V2
                u_int64_t samples_left = total_samples - encoded_samples + delay_samples;
                MP4Duration dur = samples_left > frameSize ? frameSize : samples_left;
                MP4Duration ofs = encoded_samples > 0 ? 0 : delay_samples;

                if (container == MP4_CONTAINER)
                {
                    /* write bitstream to mp4 file */
                    MP4WriteSample(MP4hFile, MP4track, bitbuf, bytesWritten, dur, ofs, 1);
                }
                else
                {
#endif
                    /* write bitstream to aac file */
                    fwrite(bitbuf, 1, bytesWritten, outfile);
#ifdef HAVE_LIBMP4V2
                }

                encoded_samples += dur;
#endif
            }
        }

#ifdef HAVE_LIBMP4V2
        /* clean up */
        if (container == MP4_CONTAINER)
        {
            MP4Close(MP4hFile);
            if (optimizeFlag == 1)
            {
                fprintf(stderr, "\n\nMP4 format optimization... ");
                MP4Optimize(aacFileName, NULL, 0);
                fprintf(stderr, "Done!");
            }
        } else
#endif
            fclose(outfile);

        fprintf(stderr, "\n\n");
    }

    faacEncClose(hEncoder);

    wav_close(infile);

    if (pcmbuf) free(pcmbuf);
    if (bitbuf) free(bitbuf);
    if (aacFileNameGiven) free(aacFileName);

    }

    return 0;
}
Esempio n. 28
0
int g7712aac::aac_encode_g711(unsigned char* inbuf, unsigned int inlen, unsigned char* outbuf, unsigned int* outlen , int type)
{
	audio_buffer_->write_data(inbuf, inlen);
	int buffer_len = 0;
	*outlen = 0;
	while ((buffer_len = audio_buffer_->get_data(pbG711ABuffer, /*164*/G711_ONE_LEN)) > 0)
	{
		if (buffer_len <= 0)
		{
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM  no G711 data !\n", __FUNCTION__, __LINE__);
			//Sleep(100);
			return -1;
		}

		nStatus = 0;        
		memset(pbPCMTmpBuffer, 0, PCMSize);
		if ((nPCMRead = g711_decode(pbPCMTmpBuffer, &PCMSize, pbG711ABuffer+/*4*/G711_ONE_OFFSET, buffer_len-/*4*/G711_ONE_OFFSET , type)) < 0) // TODO: skip 4 byte?
		{
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM  failed buffer_len = %d !\n", __FUNCTION__, __LINE__, buffer_len);            
			return -1;
		}
		//if(AAC_DEBUG) printf("nPCMRead = %d, PCMSize = %d\n", nPCMRead, PCMSize);

		if ((nPCMBufferSize - nCount) < nPCMRead)
		{
			//if(AAC_DEBUG) printf("nPCMBufferSize = %d, nCount = %d, nPCMRead = %d\n", nPCMBufferSize, nCount, nPCMRead);
			nStatus = 1;
			memset(pbAACBuffer, 0, nMaxOutputBytes);
			memcpy(pbPCMBuffer + nCount, pbPCMTmpBuffer, (nPCMBufferSize - nCount));
			nInputSamples = (nPCMBufferSize / (nPCMBitSize / 8));
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM faacEncEncode....\n",  __FUNCTION__, __LINE__);
			nRet = faacEncEncode(hEncoder, (int*) pbPCMBuffer, nInputSamples, pbAACBuffer, nMaxOutputBytes);
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM faacEncEncode\n",  __FUNCTION__, __LINE__);
			memcpy(outbuf + *outlen, pbAACBuffer, nRet);
			*outlen += nRet;

			nTmp = nPCMRead - (nPCMBufferSize - nCount);
			memset(pbPCMBuffer, 0, nPCMBufferSize);
			memcpy(pbPCMBuffer, pbPCMTmpBuffer + (nPCMBufferSize - nCount), nTmp);
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM (nPCMBufferSize - nCount) < nPCMRead\n",  __FUNCTION__, __LINE__);
			nCount = 0;
			nCount += nTmp;
		}

		if (nStatus == 0)
		{
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM nStatus = 0...\n",  __FUNCTION__, __LINE__);
			memcpy(pbPCMBuffer + nCount, pbPCMTmpBuffer, nPCMRead);
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM nStatus = 0\n",  __FUNCTION__, __LINE__);
			nCount += nPCMRead;
		}

		if (nPCMRead < /*320*/CON_PCM_SIZE)
		{
			if(AAC_DEBUG) printf("nPCMRead = %d\n", nPCMRead);
			nInputSamples = (nCount / (nPCMBitSize / 8));
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM faacEncEncode....\n",  __FUNCTION__, __LINE__);
			nRet = faacEncEncode(hEncoder, (int*) pbPCMBuffer, nInputSamples, pbAACBuffer, nMaxOutputBytes);
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM faacEncEncode\n",  __FUNCTION__, __LINE__);
			memcpy(outbuf + *outlen, pbAACBuffer, nRet);
			*outlen += nRet;
			if(AAC_DEBUG) printf("%s:[%d] G711A -> PCM nPCMRead < 320\n",  __FUNCTION__, __LINE__);
		}
	}
	return *outlen;
}