Example #1
0
bool ACMStream::close(LPBYTE pOutputBuffer, DWORD *pOutputSize)
{

bool bResult = false;

	int nOutputSamples = 0;

    nOutputSamples = lame_encode_flush( gfp, pOutputBuffer, 0 );

	if ( nOutputSamples < 0 )
	{
		// BUFFER_TOO_SMALL
*pOutputSize = 0;
	}
	else
{
		*pOutputSize = nOutputSamples;

		bResult = true;
	}

	// lame will be closed in destructor
        //lame_close( gfp );

	return bResult;
}
Example #2
0
/* close connection to the peer         */
static void mp3streamout_disconnect(t_mp3streamout *x)
{

    int err = -1;
    if(x->x_lame >= 0)
    {
        /* ignore remaining bytes */
        if ( x->x_mp3size = lame_encode_flush( x->lgfp, x->x_mp3outbuf, 0) < 0 )
        {
            post( "mp3streamout~ : warning : remaining encoded bytes" );
        }
        lame_close( x->lgfp );
        x->x_lame = -1;
        post("mp3streamout~: encoder stream closed");
    }

    if(x->x_fd >= 0)            /* close socket */
    {
#ifdef _WIN32
        closesocket(x->x_fd);
#else
        close(x->x_fd);
#endif
        x->x_fd = -1;
        outlet_float( x->x_obj.ob_outlet, 0 );
        post("mp3streamout~: connection closed");
    }
}
Example #3
0
/*------------------------------------------------------------------------------
 *  Flush the data from the encoder
 *----------------------------------------------------------------------------*/
void
LameLibEncoder :: flush ( void )
                                                            throw ( Exception )
{
    if ( !isOpen() ) {
        return;
    }

    // data chunk size estimate according to lame documentation
    unsigned int    mp3Size = 7200;
    unsigned char * mp3Buf  = new unsigned char[mp3Size];
    int             ret;

    ret = lame_encode_flush( lameGlobalFlags, mp3Buf, mp3Size );

    unsigned int    written = sink->write( mp3Buf, ret);
    delete[] mp3Buf;

    // just let go data that could not be written
    if ( written < (unsigned int) ret ) {
        reportEvent( 2,
                     "couldn't write all from encoder to underlying sink",
                     ret - written);
    }

    sink->flush();
}
Example #4
0
bool MP3Writer::end() {
  if(!is_setup) {
    RX_ERROR(MP3_WRERR_NOT_SETUP);
    return false;
  }

  if(!is_started) {
    RX_ERROR(MP3_WRERR_NOT_STARTED);
    return false;
  }
  
  int written = lame_encode_flush(lame_flags, (unsigned char*)mp3_buffer, MP3_WRITER_BUFFER_SIZE);
  if(written < 0) {
    RX_ERROR(MP3_WRERR_CANNOT_FLUSH);
  }
  else if(config.cb_data) {
    config.cb_data((const char*)mp3_buffer, written, config.user);
  }

  lame_close(lame_flags);
  
  config.cb_close(config.user);
  
  lame_flags = NULL;
  is_started = false;

  return true;
}
Example #5
0
void Java_com_iliayugai_zapp_utils_CommonUtils_encodeFile(JNIEnv *env,
		jobject jobj, jstring in_source_path, jstring in_target_path) {
	const char *source_path, *target_path;
	source_path = (*env)->GetStringUTFChars(env, in_source_path, NULL);
	target_path = (*env)->GetStringUTFChars(env, in_target_path, NULL);

	FILE *input_file, *output_file;
	input_file = fopen(source_path, "rb");
	output_file = fopen(target_path, "wb");

	short input[BUFFER_SIZE];
	char output[BUFFER_SIZE];
	int nb_read = 0;
	int nb_write = 0;
	int nb_total = 0;

	LOGD("Encoding started");
	while (nb_read = read_samples(input_file, input)) {
		nb_write = lame_encode_buffer(lame, input, input, nb_read, output,
				BUFFER_SIZE);
		fwrite(output, nb_write, 1, output_file);
		nb_total += nb_write;
	}
	LOGD("Encoded %d bytes", nb_total);

	nb_write = lame_encode_flush(lame, output, BUFFER_SIZE);
	fwrite(output, nb_write, 1, output_file);
	LOGD("Flushed %d bytes", nb_write);

	fclose(input_file);
	fclose(output_file);
}
Example #6
0
int doEncodeFinish(LameConf* conf, char* encodedBytes, int encodedArrayByteSize) {
	if (conf->gf==NULL) {
		//throwRuntimeException(env, "not initialized");
		return org_tritonus_lowlevel_lame_Lame_NOT_INITIALIZED;
	}
	return lame_encode_flush(conf->gf, encodedBytes, encodedArrayByteSize);
}
bool LameAudioWriter::close_private()
{
	if (m_bufferSize < 7200) {
		if (m_buffer) {
			delete [] m_buffer;
		}
		m_bufferSize = 7200;
		m_buffer = new char[m_bufferSize];
	}
	
	bool success = true;
	int size = lame_encode_flush(m_lameInfo->flags,
					(unsigned char*)m_buffer,
					m_bufferSize);
	if (size < 0) {
		PERROR("lame_encode_buffer_flush failed.");
		success = false;
	}
	if (size > 0 && fwrite(m_buffer, 1, size, m_fid) != (nframes_t)size) {
		PERROR("writing mp3 data failed.");
		success = false;
	}
	else {
		lame_mp3_tags_fid(m_lameInfo->flags, m_fid);
	}
	
	lame_close(m_lameInfo->flags);
	m_lameInfo->flags = 0;
	
	fclose(m_fid);
	m_fid = 0;
	
	return success;
}
Example #8
0
int main(int argc, char** argv)
{
	if(argc != 2)
	{
		printf("Usage: %s <wav file>\n", argv[0]);
		exit(0);
	}

	lame_global_flags *gfp;
	
	
	//set params
	gfp = lame_init();
	
	lame_set_num_channels(gfp,2);
	lame_set_in_samplerate(gfp,44100);
	lame_set_brate(gfp,128);
	lame_set_mode(gfp,1);
	lame_set_quality(gfp,2); 
	
	int ret_code = lame_init_params(gfp);
	if(ret_code < 0)
	{
		printf("ret_code < 0\n");
		exit(-1);
	}
	
	//read input file
	int read, write;
	FILE* pcm = fopen(argv[1], "rb");
	
	char* outPath;
	outPath = strdup(argv[1]);
	sprintf(outPath+strlen(argv[1])-3, "mp3");
	
	FILE* mp3 = fopen(outPath, "wb");
	

	
	short int pcm_buffer[PCM_SIZE * 2];
	unsigned char mp3_buffer[MP3_SIZE];
	
	do
	{
		read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
		if(read == 0)
			write = lame_encode_flush(gfp, mp3_buffer, MP3_SIZE);
		else
			write = lame_encode_buffer_interleaved(gfp, pcm_buffer, read, mp3_buffer, MP3_SIZE);
		fwrite(mp3_buffer, write, sizeof (unsigned char), mp3);
	}
	while (read != 0);
	
	lame_close(gfp);
	fclose(mp3);
	fclose(pcm);
	
	exit(0);
}
media_packet_ptr lame_encoder_impl_internal::encode(const audio_data * _AudioData)
{
    static const size_t mp3TimeBase = 14112000; // Least common multiple of 44100 and 32000
    const int predSamplesInLame = lame_get_mf_samples_to_encode( m_Lame.get() );
    // from lame:
    // The required mp3buf_size can be computed from num_samples,
    // samplerate and encoding rate, but here is a worst case estimate:
    // mp3buf_size in bytes = 1.25*num_samples + 7200
   
    const size_t samplesCount = (_AudioData) ?  _AudioData->get_samples_count() : 0;
    const size_t bufSize = static_cast<size_t>( 1.25 * samplesCount ) + 7200 ;
    uint8_t * buffer = m_Buffer.get_buffer( bufSize );
    int lameRet = 0;
    
    if (_AudioData)
    {
        const size_t channelsCount = _AudioData->get_channels_count();
        if (channelsCount == 1)
        {
            lameRet = lame_encode_buffer( 
                m_Lame.get(),
                (short*)_AudioData->get_raw_data(),
                (short*)_AudioData->get_raw_data(),
                _AudioData->get_samples_count(),
                buffer,
                bufSize);
        }
        else
        {
            lameRet = lame_encode_buffer_interleaved( 
                m_Lame.get(),
                (short*)_AudioData->get_raw_data(),
                _AudioData->get_samples_count(),
                buffer,
                bufSize);
        }
    }
    else
    {
        lameRet = lame_encode_flush(m_Lame.get(), buffer, bufSize) ;
    }

    const int samplesEncoded = predSamplesInLame +  samplesCount - lame_get_mf_samples_to_encode( m_Lame.get() );
    m_TotalSamplesEncoded += samplesEncoded;

    common_media_packet2_ptr mediaPacket = common_media_packet2_ptr( new common_media_packet2() );
    mediaPacket->setter()->set_data(buffer, lameRet, bufferAllocNew);
    mediaPacket->setter()->set_media_type(DT_AVMEDIA_TYPE_AUDIO);
    mediaPacket->setter()->set_time_base(dt_rational_t(1, mp3TimeBase));
    mediaPacket->setter()->set_duration( samplesEncoded * (mp3TimeBase / get_input_sample_rate()) );

    const dt_ts_t ts = m_TotalSamplesEncoded * (mp3TimeBase / get_input_sample_rate());
    mediaPacket->setter()->set_pts( ts );
    mediaPacket->setter()->set_dts( ts );

    return mediaPacket;
}
Example #10
0
/***********************************************************************
 * Work
 ***********************************************************************
 *
 **********************************************************************/
int enclameWork( hb_work_object_t * w, hb_buffer_t ** buf_in,
                 hb_buffer_t ** buf_out )
{
    hb_work_private_t * pv = w->private_data;
    hb_audio_t * audio = w->audio;
    hb_buffer_t * in = *buf_in;
    hb_buffer_t * buf;

    if ( (*buf_in)->size <= 0 )
    {
        /* EOF on input - send it downstream & say we're done */

        buf = hb_buffer_init( pv->output_bytes );
        buf->size = lame_encode_flush( pv->lame, buf->data, LAME_MAXMP3BUFFER );
        buf->s.start = pv->pts;
        buf->s.stop  = buf->s.start + 90000 * 1152 / audio->config.out.samplerate;

        buf->s.type = AUDIO_BUF;
        buf->s.frametype = HB_FRAME_AUDIO;

        if( buf->size <= 0 )
        {
            hb_buffer_close( &buf );
        }

        // Add the flushed data
        *buf_out = buf;

        // Add the eof
        if ( buf )
        {
            buf->next = in;
        }
        else
        {
            *buf_out = in;
        }

        *buf_in = NULL;
        return HB_WORK_DONE;
    }

    hb_list_add( pv->list, *buf_in );
    *buf_in = NULL;

    *buf_out = buf = Encode( w );

    while( buf )
    {
        buf->next = Encode( w );
        buf       = buf->next;
    }

    return HB_WORK_OK;
}
JNIEXPORT jint JNICALL Java_org_proof_recorder_service_jni_SimpleLame_flush(
		JNIEnv *env, jclass cls, jbyteArray mp3buf) {
	const jsize mp3buf_size = (*env)->GetArrayLength(env, mp3buf);
	jbyte* j_mp3buf = (*env)->GetByteArrayElements(env, mp3buf, NULL);

	int result = lame_encode_flush(glf, j_mp3buf, mp3buf_size);

	(*env)->ReleaseByteArrayElements(env, mp3buf, j_mp3buf, 0);

	return result;
}
void AudioReader::exportAudioDataToMP3(const char* data)
{
    QSettings settings;
    emit TCMessage("Exporting MP3...");
    int read, write;
    FILE *pcm = fopen("TCTemp.wav", "wb");
    fwrite(data,1,format.chunkSize,pcm);
    fflush(pcm);
    pcm = fopen("TCTemp.wav", "rb");
    f = fopen(this->outfile.toLocal8Bit().constData(), "wb");

    const int PCM_SIZE = 8192;
    const int MP3_SIZE = 8192*2;

    short int pcm_buffer[PCM_SIZE*2];
    unsigned char mp3_buffer[MP3_SIZE];

    lame_t lame = lame_init();
    lame_set_in_samplerate(lame, format.SampleRate);
    lame_set_VBR(lame, (vbr_mode)settings.value("vbr",0).toInt());

    if(lame_get_VBR(lame)) {
        lame_set_VBR_min_bitrate_kbps(lame,settings.value("min",128).toInt());
        lame_set_VBR_max_bitrate_kbps(lame,settings.value("max",192).toInt());

    }
    else
    {
        lame_set_brate(lame,settings.value("min",128).toInt());
    }
    lame_set_num_channels(lame,(int)format.Channels);
    lame_set_quality(lame,0);
    if(format.Channels==1)lame_set_mode(lame,MONO);
    else                  lame_set_mode(lame,STEREO);

    lame_init_params(lame);
    do {
        if(!knock->running)break;
        read = fread(pcm_buffer, 2*byte_size, PCM_SIZE, pcm);
        fflush(f);
        if (read == 0)
            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
        else
            write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
        fwrite(mp3_buffer, write, 1, f);
        fflush(f);
    } while (read != 0);
    lame_close(lame);
    fclose(pcm);
    if(unlink("TCTemp.wav")!=0) {
        emit TCColor("color: red;");
        emit TCMessage(QString("Error while removing TCTemp.wav"));
    }
}
jint Java_ice_caster_android_shout_Lame_flush(
		JNIEnv *env, jclass cls, jbyteArray mp3buf) {
	const jsize mp3buf_size = (*env)->GetArrayLength(env, mp3buf);
	jbyte* j_mp3buf = (*env)->GetByteArrayElements(env, mp3buf, NULL);

	int result = lame_encode_flush(glf, j_mp3buf, mp3buf_size);

	(*env)->ReleaseByteArrayElements(env, mp3buf, j_mp3buf, 0);

	return result;
}
JNIEXPORT jint JNICALL Java_cn_net_xyd_videoaudiodemo_mp3lame_SimpleLame_flush(
        JNIEnv *env, jclass cls, jbyteArray mp3buf) {
  const jsize mp3buf_size = (*env)->GetArrayLength(env, mp3buf);
  jbyte* j_mp3buf = (*env)->GetByteArrayElements(env, mp3buf, NULL);

  int result = lame_encode_flush(glf, j_mp3buf, mp3buf_size);

  (*env)->ReleaseByteArrayElements(env, mp3buf, j_mp3buf, 0);

  return result;
}
JNIEXPORT jint JNICALL Java_com_xiong_richard_greyparrot_SimpleLame_flush(
		JNIEnv *env, jclass cls, jbyteArray mp3buf) {
	const jsize mp3buf_size = (*env)->GetArrayLength(env, mp3buf);
	jbyte* j_mp3buf = (*env)->GetByteArrayElements(env, mp3buf, NULL);

	int result = lame_encode_flush(glf, j_mp3buf, mp3buf_size);

	(*env)->ReleaseByteArrayElements(env, mp3buf, j_mp3buf, 0);

	return result;
}
Example #16
0
EmErrorCode LameEncoder::FlushRest()
{
    int ret = lame_encode_flush(m_gfp, m_Buffer.data(), m_Buffer.size());
    if (ret >= 0) {
        if ((int)::fwrite(m_Buffer.data(), 1, ret, m_OutputFile) == ret) {
            ::lame_mp3_tags_fid(m_gfp, m_OutputFile);
            return ErrorCode::Ok;
        }
    }
    return ErrorCode::EncoderFailedToFlush;
}
JNIEXPORT jint JNICALL Java_com_anhuioss_crowdroid_util_RecordVoiceToMp3Lame_flush(
		JNIEnv *env, jclass cls, jbyteArray mp3buf) {
	const jsize mp3buf_size = (*env)->GetArrayLength(env, mp3buf);
	jbyte* j_mp3buf = (*env)->GetByteArrayElements(env, mp3buf, NULL);

	int result = lame_encode_flush(glf, j_mp3buf, mp3buf_size);

	(*env)->ReleaseByteArrayElements(env, mp3buf, j_mp3buf, 0);

	return result;
}
Example #18
0
JNIEXPORT jint JNICALL Java_com_czt_mp3recorder_util_LameUtil_flush(
		JNIEnv *env, jclass cls, jbyteArray mp3buf) {
	const jsize mp3buf_size = (*env)->GetArrayLength(env, mp3buf);
	jbyte* j_mp3buf = (*env)->GetByteArrayElements(env, mp3buf, NULL);

	int result = lame_encode_flush(lame, j_mp3buf, mp3buf_size);

	(*env)->ReleaseByteArrayElements(env, mp3buf, j_mp3buf, 0);

	return result;
}
Example #19
0
int WMp3Encoder::EncodeSamples(void *pSamples, unsigned int nNumberOfSamples)
{
	ASSERT_W(c_nBitBerSample == 16);
	
	if(c_fReady == 0)
	{
		err(ENCODER_NOT_READY);
		return 0;
	}

	int nOutputBytes;

	short *samples = (short*) pSamples;
	unsigned int nHaveSamples = nNumberOfSamples;

	if(nNumberOfSamples == 0)
	{
		nOutputBytes = lame_encode_flush(gfp, c_pWorkingBuffer, c_nSamplesBufferSizeInBytes);
		if(nOutputBytes > 0)
			c_write_callback(c_pWorkingBuffer, nOutputBytes, c_user_data); // 	Chunk ID
			
		return 1;

	}

	while(nHaveSamples)
	{
		unsigned int nFill = c_NumberOfInputSamples;
		if(nFill > nHaveSamples)
			nFill = nHaveSamples;

		

		if ( 1 == lame_get_num_channels( gfp ) )
		{
			nOutputBytes = lame_encode_buffer(gfp, samples, samples, nFill, c_pWorkingBuffer, 0);
			samples = &samples[nFill];
		}
		else
		{
			nOutputBytes = lame_encode_buffer_interleaved(gfp, samples, nFill, c_pWorkingBuffer, 0);
			samples = &samples[nFill * 2];
		}

		nHaveSamples -= nFill;

		if(nOutputBytes > 0)
			c_write_callback(c_pWorkingBuffer, nOutputBytes, c_user_data); // 	Chunk ID

	}

	return 1;
}
jint simple_lame_lib_flush(
		JNIEnv* env, lame_global_flags* glf, 
		jbyteArray mp3buf) {
	const jsize mp3buf_size = (*env)->GetArrayLength(env, mp3buf);
	jbyte* j_mp3buf = (*env)->GetByteArrayElements(env, mp3buf, NULL);

	int result = lame_encode_flush(glf, j_mp3buf, mp3buf_size);

	(*env)->ReleaseByteArrayElements(env, mp3buf, j_mp3buf, 0);

	return result;
}
/**
    \fn encode
    \brief Get an encoded mp3 packet
    @param dest [in] Where to write datas
    @param len  [out] Length of encoded datas in bytes
    @param samples [out] Number of samples
    @return true on success, false on error

*/
bool AUDMEncoder_Lame::encode(uint8_t *dest, uint32_t *len, uint32_t *samples)
{

  int32_t nbout;

  *samples = BLOCK_SIZE;	//FIXME
  *len = 0;
  if(AudioEncoderStopped==_state)
        return false;

    refillBuffer (_chunk);
    if(AudioEncoderNoInput==_state)
    {
        int left=tmptail-tmphead;
        if (left < _chunk)
        {
            if(left)
            {
                nbout=send(left,dest);
                tmphead=tmptail;
                ADM_info("[lame]Sending last packet\n");
                goto cont;
            }
              // Flush
              _state=AudioEncoderStopped;
              nbout=lame_encode_flush(MYFLAGS,dest,16*1024);
              if(nbout<0) 
              {
                    ADM_warning("Error while flushing lame\n");
                    return false;   
              }
                    
              *len=nbout;
              *samples=BLOCK_SIZE;  
              ADM_info("[Lame] Flushing, last block is %d bytes\n",nbout);
              return true;
    }
  }
  nbout=send(_chunk,dest);
  tmphead += _chunk;
cont:
  if (nbout < 0)
    {
      printf ("[Lame] Error !!! : %"PRIi32"\n", nbout);
      return false;
    }
  *len = nbout;
  if (!*len)
    *samples = 0;
  else
    *samples=BLOCK_SIZE;
  return true;
}
Example #22
0
//
// Finsh - flush the buffered samples
//
HRESULT CEncoder::Finish()
{
    CAutoLock l(&m_lock);

    if (!pgf || !m_outFrameBuf || (m_outOffset >= OUT_BUFFER_MAX))
        return E_FAIL;

    m_outOffset += lame_encode_flush(pgf, m_outFrameBuf + m_outOffset, OUT_BUFFER_SIZE - m_outOffset);

    m_bFinished = TRUE;

    return S_OK;
}
Example #23
0
void mp3_close(int64_t handle){
    mp3_file* ptr = (mp3_file *) handle;
    if(ptr->err != -1){
        int n = lame_encode_flush(ptr->gfp, (unsigned char *) ptr->frame, ptr->length);
        if(n > 0 && ptr->file){
            n = fwrite(ptr->frame, n, 1, ptr->file);
        }
    }
    
    if(ptr->file){
        fclose(ptr->file);
    }
    lame_close(ptr->gfp);
    ptr->dec->~CSpeexDecoder();
    free(ptr);
}
Example #24
0
void Encoder(char* src, char* dst){
 
           //printf("Inside Encoder : %s \n",src);
           //printf("Inside Encoder : %s \n",dst);
           if(src == NULL || dst == NULL)
              return;

           int read, write;
           FILE* wav;
           FILE* mp3;
           wav = fopen(src, "rb");
           if(wav == NULL){
              printf(" Unable to open the file %s \n", src);
              return;
            }
           mp3 = fopen(dst, "wb");
           if(mp3 == NULL){
              printf(" Unable to open the file %s \n", dst);
              return;
           } 
           const int PCM_SIZE = 8192;
           const int MP3_SIZE = 8192;
           
           short int PCM_BUFFER[2*PCM_SIZE];
           char MP3_BUFFER[MP3_SIZE];

           lame_t lame = lame_init();
           lame_set_in_samplerate(lame, 44100);
           lame_set_VBR(lame, vbr_default);
           lame_init_params(lame);
           do {
                read = fread(PCM_BUFFER, 2*sizeof(short int), PCM_SIZE, wav);
                if (read == 0)
                write = lame_encode_flush(lame, MP3_BUFFER, MP3_SIZE);
                else
                write = lame_encode_buffer_interleaved(lame, PCM_BUFFER, read, MP3_BUFFER, MP3_SIZE);
                fwrite(MP3_BUFFER, write, 1, mp3);
                } while (read != 0);

           lame_close(lame);
           fclose(wav);
           fclose(mp3);
  
            }
Example #25
0
int32_t mp3_stream_final(int64_t handle, char** ppch){
    assert(ppch);
    mp3_file* ptr = (mp3_file *) handle;

    if(ptr->err != -1){
        int n = lame_encode_flush(ptr->gfp, (unsigned char *) ptr->frame, ptr->length);
        if(n > 0 && ptr->file){
            n = fwrite(ptr->frame, n, 1, ptr->file);
        }
        ptr->err = n;
    }
    *ppch = ptr->frame;
    
    int n = ptr->err;
    if(ptr->err != -1){
        ptr->err = -1;
    }
    return n;
}
Example #26
0
static int MP3_close(FILE* fp, struct amci_file_desc_t* fmt_desc, int options, long h_codec,
				    struct amci_codec_t *codec)
{
    int final_samples;

    unsigned char  mp3buffer[7200];    
    DBG("MP3: close. \n");
    if(options == AMCI_WRONLY) {
      if (!h_codec || !((mp3_coder_state*)h_codec)->gfp) {
	ERROR("no valid codec handle!\n");
	return -1;
      }

      if ((final_samples = lame_encode_flush(((mp3_coder_state*)h_codec)->gfp,mp3buffer, 7200))) {
	    fwrite(mp3buffer, 1, final_samples, fp);
	    DBG("MP3: flushing %d bytes from MP3 encoder.\n", final_samples);
	}
	lame_mp3_tags_fid(((mp3_coder_state*)h_codec)->gfp,fp);
    }
    return 0;
}
Example #27
0
int encode_to_file(lame_global_flags *gfp, const FMT_DATA *hdr, const short *leftPcm, const short *rightPcm,
	const int iDataSize, const char *filename)
{
	int numSamples = iDataSize / hdr->wBlockAlign;

	int mp3BufferSize = numSamples * 5 / 4 + 7200; // worst case estimate
	unsigned char *mp3Buffer = new unsigned char[mp3BufferSize];

	// call to lame_encode_buffer
	int mp3size = lame_encode_buffer(gfp, (short*)leftPcm, (short*)rightPcm, numSamples, mp3Buffer, mp3BufferSize);
	if (!(mp3size > 0)) {
		delete[] mp3Buffer;
		cerr << "No data was encoded by lame_encode_buffer. Return code: " << mp3size << endl;
		return EXIT_FAILURE;
	}

	// write to file
	FILE *out = fopen(filename, "wb+");
	fwrite((void*)mp3Buffer, sizeof(unsigned char), mp3size, out);

	// call to lame_encode_flush
	int flushSize = lame_encode_flush(gfp, mp3Buffer, mp3BufferSize);

	// write flushed buffers to file
	fwrite((void*)mp3Buffer, sizeof(unsigned char), flushSize, out);

	// call to lame_mp3_tags_fid (might be omitted)
	lame_mp3_tags_fid(gfp, out);

	fclose(out);
	delete[] mp3Buffer;

#ifdef __VERBOSE_
	cout << "Wrote " << mp3size + flushSize << " bytes." << endl;
#endif
	return EXIT_SUCCESS;
}
Example #28
0
    /* stop recording */
static void mp3write_stop(t_mp3write *x)
{
    int err = -1;

    if ( x->x_fd < 0 ) {
       post("mp3write~: stop received but no file has been set ... ignored.");
       return;
    }
 
    if ( x->x_recflag == 0 ) {
       post("mp3write~: stop received but recording is stopped ... ignored.");
       return;
    }
        /* first stop recording / buffering and so on, than do the rest */
    x->x_recflag = 0;

    /* flushing remaining frames and tag */
    x->x_mp3size = lame_encode_flush( x->lgfp, x->x_mp3outbuf, MY_MP3_MALLOC_OUT_SIZE ); 
    
    mp3write_writeframes(x);   /* write mp3 to file */

    x->x_recflag = 0;
    post("mp3write~: stop recording, flushed %d bytes", x->x_mp3size);
}
Example #29
0
static inline void free_context(shout_context_t *context)
{
	int ret;

	if (context) {
		switch_mutex_lock(context->audio_mutex);
		context->err++;
		switch_mutex_unlock(context->audio_mutex);

		if (context->stream_url) {
			int sanity = 0;

			while (context->thread_running) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Waiting for stream to terminate: %s\n", context->stream_url);
				switch_yield(500000);
				if (++sanity > 10) {
					switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Giving up waiting for stream to terminate: %s\n", context->stream_url);
					break;
				}
			}
		}

		switch_thread_rwlock_wrlock(context->rwlock);

		if (context->mh) {
			mpg123_close(context->mh);
			mpg123_delete(context->mh);
		}

		if (context->fp) {
			unsigned char mp3buffer[8192];
			int len;
			int16_t blank[2048] = { 0 }, *r = NULL;


			if (context->channels == 2) {
				r = blank;
			}

			len = lame_encode_buffer(context->gfp, blank, r, sizeof(blank) / 2, mp3buffer, sizeof(mp3buffer));

			if (len) {
				ret = fwrite(mp3buffer, 1, len, context->fp);
			}

			while ((len = lame_encode_flush(context->gfp, mp3buffer, sizeof(mp3buffer))) > 0) {
				ret = fwrite(mp3buffer, 1, len, context->fp);
				if (ret < 0) {
					break;
				}
			}

			lame_mp3_tags_fid(context->gfp, context->fp);

			fclose(context->fp);
			context->fp = NULL;
		}

		if (context->shout) {
			shout_close(context->shout);
			context->shout = NULL;
		}

		if (context->gfp) {
			lame_close(context->gfp);
			context->gfp = NULL;
		}

		if (context->audio_buffer) {
			switch_buffer_destroy(&context->audio_buffer);
		}

		switch_mutex_destroy(context->audio_mutex);

		switch_thread_rwlock_unlock(context->rwlock);
		switch_thread_rwlock_destroy(context->rwlock);
	}
}
Example #30
0
void do_broadcast(switch_stream_handle_t *stream)
{
	char *path_info = switch_event_get_header(stream->param_event, "http-path-info");
	char *file;
	lame_global_flags *gfp = NULL;
	switch_file_handle_t fh = { 0 };
	unsigned char mp3buf[TC_BUFFER_SIZE] = "";
	uint8_t buf[1024];
	int rlen;
	int is_local = 0;
	uint32_t interval = 20000;

	if (strstr(path_info + 7, "://")) {
		file = strdup(path_info + 7);
		is_local++;
	} else {
		file = switch_mprintf("%s/streamfiles/%s", SWITCH_GLOBAL_dirs.base_dir, path_info + 7);
	}
	assert(file);

	if (switch_core_file_open(&fh, file, 0, 0, SWITCH_FILE_FLAG_READ | SWITCH_FILE_DATA_SHORT, NULL) != SWITCH_STATUS_SUCCESS) {
		memset(&fh, 0, sizeof(fh));
		stream->write_function(stream, "Content-type: text/html\r\n\r\n<h2>File not found</h2>\n");
		goto end;
	}

	if (switch_test_flag((&fh), SWITCH_FILE_NATIVE)) {
		stream->write_function(stream, "Content-type: text/html\r\n\r\n<h2>File format not supported</h2>\n");
		goto end;
	}

	if (!(gfp = lame_init())) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate lame\n");
		goto end;
	}

	lame_set_num_channels(gfp, fh.channels);
	lame_set_in_samplerate(gfp, fh.samplerate);
	lame_set_brate(gfp, 16 * (fh.samplerate / 8000) * fh.channels);
	lame_set_mode(gfp, 3);
	lame_set_quality(gfp, 2);
	lame_set_errorf(gfp, log_error);
	lame_set_debugf(gfp, log_debug);
	lame_set_msgf(gfp, log_msg);
	lame_set_bWriteVbrTag(gfp, 0);
	lame_mp3_tags_fid(gfp, NULL);
	lame_init_params(gfp);
	lame_print_config(gfp);

	stream->write_function(stream, "Content-type: audio/mpeg\r\n" "Content-Disposition: inline; filename=\"%s.mp3\"\r\n\r\n", path_info + 7);

	if (fh.interval) {
		interval = fh.interval * 1000;
	}

	for (;;) {
		switch_size_t samples = sizeof(buf) / 2;

		switch_core_file_read(&fh, buf, &samples);

		if (is_local) {
			switch_yield(interval);
		}

		if (!samples) {
			break;
		}

		if ((rlen = lame_encode_buffer(gfp, (void *) buf, NULL, samples, mp3buf, sizeof(mp3buf))) < 0) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "MP3 encode error %d!\n", rlen);
			goto end;
		}

		if (rlen) {
			if (stream->raw_write_function(stream, mp3buf, rlen)) {
				switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Disconnected\n");
				goto end;
			}
		}
	}

	while ((rlen = lame_encode_flush(gfp, mp3buf, sizeof(mp3buf))) > 0) {
		if (stream->raw_write_function(stream, mp3buf, rlen)) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Disconnected\n");
			goto end;
		}
	}

  end:

	if (fh.channels) {
		switch_core_file_close(&fh);
	}

	switch_safe_free(file);

	if (gfp) {
		lame_close(gfp);
		gfp = NULL;
	}
}