MP3Encoder(UINT bitRate) { curBitRate = bitRate; lgf = lame_init(); if(!lgf) CrashError(TEXT("Unable to open mp3 encoder")); lame_set_in_samplerate(lgf, App->GetSampleRateHz()); lame_set_out_samplerate(lgf, App->GetSampleRateHz()); lame_set_num_channels(lgf, 2); lame_set_mode(lgf, STEREO); lame_set_disable_reservoir(lgf, TRUE); //bit reservoir has to be disabled for seamless streaming lame_set_VBR(lgf, vbr_off); lame_set_brate(lgf, bitRate); lame_init_params(lgf); outputFrameSize = lame_get_framesize(lgf); //1152 usually dwMP3MaxSize = DWORD(1.25*double(outputFrameSize*audioBlockSize) + 7200.0); MP3OutputBuffer.SetSize(dwMP3MaxSize+1); MP3OutputBuffer[0] = 0x2f; bFirstPacket = true; Log(TEXT("------------------------------------------")); Log(TEXT("%s"), GetInfoString().Array()); }
int lame_enc_init(lame_enc *lame) { int rc; char info_buf[256]; lame->gfp = lame_init(); lame_set_num_channels(lame->gfp, lame->channel); lame_set_in_samplerate(lame->gfp, lame->samplerate_in); lame_set_out_samplerate(lame->gfp, lame->samplerate_out); lame_set_brate(lame->gfp, lame->bitrate); if((rc = lame_init_params(lame->gfp)) < 0) { printf("bitrate: %d\n", lame->bitrate); snprintf(info_buf, sizeof(info_buf), "unable to init lame params %d", rc); print_info(info_buf, 1); return 1; } lame->state = LAME_READY; return 0; }
int enclameInit( hb_work_object_t * w, hb_job_t * job ) { hb_work_private_t * pv = calloc( 1, sizeof( hb_work_private_t ) ); hb_audio_t * audio = w->audio; w->private_data = pv; pv->job = job; hb_log( "enclame: opening libmp3lame" ); pv->lame = lame_init(); // use ABR lame_set_scale( pv->lame, 32768.0 ); if( audio->config.out.compression_level >= 0 ) { lame_set_quality( pv->lame, audio->config.out.compression_level ); } if( audio->config.out.bitrate > 0 ) { lame_set_VBR( pv->lame, vbr_abr ); lame_set_VBR_mean_bitrate_kbps( pv->lame, audio->config.out.bitrate ); } else if( audio->config.out.quality >= 0 ) { lame_set_brate( pv->lame, 0 ); lame_set_VBR( pv->lame, vbr_default ); lame_set_VBR_quality( pv->lame, audio->config.out.quality ); } lame_set_in_samplerate( pv->lame, audio->config.out.samplerate ); lame_set_out_samplerate( pv->lame, audio->config.out.samplerate ); pv->out_discrete_channels = hb_mixdown_get_discrete_channel_count( audio->config.out.mixdown ); // Lame's default encoding mode is JOINT_STEREO. This subtracts signal // that is "common" to left and right (within some threshold) and encodes // it separately. This improves quality at low bitrates, but hurts // imaging (channel separation) at higher bitrates. So if the bitrate // is suffeciently high, use regular STEREO mode. if ( pv->out_discrete_channels == 1 ) { lame_set_mode( pv->lame, MONO ); lame_set_num_channels( pv->lame, 1 ); } else if ( audio->config.out.bitrate >= 128 ) { lame_set_mode( pv->lame, STEREO ); } lame_init_params( pv->lame ); pv->input_samples = 1152 * pv->out_discrete_channels; pv->output_bytes = LAME_MAXMP3BUFFER; pv->buf = malloc( pv->input_samples * sizeof( float ) ); audio->config.out.samples_per_frame = 1152; pv->list = hb_list_init(); pv->pts = -1; return 0; }
bool LameAudioWriter::open_private() { m_fid = fopen(m_fileName.toUtf8().data(), "w+"); if (!m_fid) { return false; } m_lameInfo->flags = lame_init(); if (m_lameInfo->flags == 0) { PERROR("lame_init failed."); return false; } if (m_channels == 1) { lame_set_mode(m_lameInfo->flags, MONO); } lame_set_num_channels(m_lameInfo->flags, m_channels); lame_set_in_samplerate(m_lameInfo->flags, m_rate); lame_set_out_samplerate(m_lameInfo->flags, m_rate); if(m_method == 0) { // Constant Bitrate lame_set_VBR(m_lameInfo->flags, vbr_off); lame_set_brate(m_lameInfo->flags, m_maxBitrate); } else if (m_method == 1) { // Average Bitrate lame_set_VBR(m_lameInfo->flags, vbr_abr); lame_set_VBR_mean_bitrate_kbps(m_lameInfo->flags, m_maxBitrate); } else if (m_method == 2) { // Variable Bitrate (old) lame_set_VBR(m_lameInfo->flags, vbr_default); lame_set_VBR_min_bitrate_kbps(m_lameInfo->flags, m_minBitrate); lame_set_VBR_max_bitrate_kbps(m_lameInfo->flags, m_maxBitrate); } else if (m_method == 3) { // Variable Bitrate (new) lame_set_VBR(m_lameInfo->flags, vbr_default); lame_set_VBR_min_bitrate_kbps(m_lameInfo->flags, m_minBitrate); lame_set_VBR_max_bitrate_kbps(m_lameInfo->flags, m_maxBitrate); } lame_set_quality(m_lameInfo->flags, m_quality); // // file options // lame_set_copyright(m_lameInfo->flags, false); lame_set_original(m_lameInfo->flags, true); lame_set_strict_ISO(m_lameInfo->flags, false); lame_set_error_protection(m_lameInfo->flags, false); return (lame_init_params(m_lameInfo->flags ) != -1); }
static bool lame_encoder_setup(struct lame_encoder *encoder, GError **error) { if (encoder->quality >= -1.0) { /* a quality was configured (VBR) */ if (0 != lame_set_VBR(encoder->gfp, vbr_rh)) { g_set_error(error, lame_encoder_quark(), 0, "error setting lame VBR mode"); return false; } if (0 != lame_set_VBR_q(encoder->gfp, encoder->quality)) { g_set_error(error, lame_encoder_quark(), 0, "error setting lame VBR quality"); return false; } } else { /* a bit rate was configured */ if (0 != lame_set_brate(encoder->gfp, encoder->bitrate)) { g_set_error(error, lame_encoder_quark(), 0, "error setting lame bitrate"); return false; } } if (0 != lame_set_num_channels(encoder->gfp, encoder->audio_format.channels)) { g_set_error(error, lame_encoder_quark(), 0, "error setting lame num channels"); return false; } if (0 != lame_set_in_samplerate(encoder->gfp, encoder->audio_format.sample_rate)) { g_set_error(error, lame_encoder_quark(), 0, "error setting lame sample rate"); return false; } if (0 != lame_set_out_samplerate(encoder->gfp, encoder->audio_format.sample_rate)) { g_set_error(error, lame_encoder_quark(), 0, "error setting lame out sample rate"); return false; } if (0 > lame_init_params(encoder->gfp)) { g_set_error(error, lame_encoder_quark(), 0, "error initializing lame params"); return false; } return true; }
/* initialize the lame library */ static void mp3streamout_tilde_lame_init(t_mp3streamout *x) { int ret; x->lgfp = lame_init(); /* set default parameters for now */ #ifdef _WIN32 /* load lame_enc.dll library */ HINSTANCE dll; dll=LoadLibrary("lame_enc.dll"); if(dll==NULL) { error("mp3streamout~: error loading lame_enc.dll"); closesocket(x->x_fd); x->x_fd = -1; outlet_float(x->x_obj.ob_outlet, 0); post("mp3streamout~: connection closed"); return; } #endif { const char *lameVersion = get_lame_version(); logpost(NULL, 4, "mp3streamout~ : using lame version : %s", lameVersion ); } /* setting lame parameters */ lame_set_num_channels( x->lgfp, 2); lame_set_in_samplerate( x->lgfp, sys_getsr() ); lame_set_out_samplerate( x->lgfp, x->x_samplerate ); lame_set_brate( x->lgfp, x->x_bitrate ); lame_set_mode( x->lgfp, x->x_mp3mode ); lame_set_quality( x->lgfp, x->x_mp3quality ); lame_set_emphasis( x->lgfp, 1 ); lame_set_original( x->lgfp, 1 ); lame_set_copyright( x->lgfp, 1 ); /* viva free music societies !!! */ lame_set_disable_reservoir( x->lgfp, 0 ); //lame_set_padding_type( x->lgfp, PAD_NO ); /* deprecated in LAME */ ret = lame_init_params( x->lgfp ); if ( ret<0 ) { post( "mp3streamout~ : error : lame params initialization returned : %d", ret ); } else { x->x_lame=1; /* magic formula copied from windows dll for MPEG-I */ x->x_lamechunk = 2*1152; post( "mp3streamout~ : lame initialization done. (%d)", x->x_lame ); } lame_init_bitstream( x->lgfp ); }
JNIEXPORT void JNICALL Java_com_czt_mp3recorder_util_LameUtil_init( JNIEnv *env, jclass cls, jint inSamplerate, jint inChannel, jint outSamplerate, jint outBitrate, jint quality) { if (lame != NULL) { lame_close(lame); lame = NULL; } lame = lame_init(); lame_set_in_samplerate(lame, inSamplerate); lame_set_num_channels(lame, inChannel);//输入流的声道 lame_set_out_samplerate(lame, outSamplerate); lame_set_brate(lame, outBitrate); lame_set_quality(lame, quality); lame_init_params(lame); }
void Java_ice_caster_android_shout_Lame_init( JNIEnv *env, jclass cls, jint inSamplerate, jint outChannel, jint outSamplerate, jint outBitrate, jint quality) { if (glf != NULL) { lame_close(glf); glf = NULL; } glf = lame_init(); lame_set_in_samplerate(glf, inSamplerate); lame_set_num_channels(glf, outChannel); lame_set_out_samplerate(glf, outSamplerate); lame_set_brate(glf, outBitrate); lame_set_quality(glf, quality); lame_init_params(glf); }
JNIEXPORT void JNICALL Java_com_anhuioss_crowdroid_util_RecordVoiceToMp3Lame_init( JNIEnv *env, jclass cls, jint inSamplerate, jint outChannel, jint outSamplerate, jint outBitrate, jint quality) { if (glf != NULL) { lame_close(glf); glf = NULL; } glf = lame_init(); lame_set_in_samplerate(glf, inSamplerate); lame_set_num_channels(glf, outChannel); lame_set_out_samplerate(glf, outSamplerate); lame_set_brate(glf, outBitrate); lame_set_quality(glf, quality); lame_init_params(glf); }
JNIEXPORT void JNICALL Java_cn_net_xyd_videoaudiodemo_mp3lame_SimpleLame_init( JNIEnv *env, jclass cls, jint inSamplerate, jint outChannel, jint outSamplerate, jint outBitrate, jint quality) { if (glf != NULL) { lame_close(glf); glf = NULL; } glf = lame_init(); lame_set_in_samplerate(glf, inSamplerate); lame_set_num_channels(glf, outChannel); lame_set_out_samplerate(glf, outSamplerate); lame_set_brate(glf, outBitrate); lame_set_quality(glf, quality); lame_init_params(glf); }
JNIEXPORT void JNICALL Java_org_proof_recorder_service_jni_SimpleLame_init( JNIEnv *env, jclass cls, jint inSamplerate, jint outChannel, jint outSamplerate, jint outBitrate, jint quality) { if (glf != NULL) { lame_close(glf); glf = NULL; } glf = lame_init(); lame_set_in_samplerate(glf, inSamplerate); lame_set_num_channels(glf, outChannel); lame_set_out_samplerate(glf, outSamplerate); lame_set_brate(glf, outBitrate); lame_set_quality(glf, quality); lame_init_params(glf); }
JNIEXPORT void JNICALL Java_com_xiong_richard_greyparrot_SimpleLame_init( JNIEnv *env, jclass cls, jint inSamplerate, jint outChannel, jint outSamplerate, jint outBitrate, jint quality) { if (glf != NULL) { lame_close(glf); glf = NULL; } glf = lame_init(); lame_set_in_samplerate(glf, inSamplerate); lame_set_num_channels(glf, outChannel); lame_set_out_samplerate(glf, outSamplerate); lame_set_brate(glf, outBitrate); lame_set_quality(glf, quality); lame_init_params(glf); }
bool Mp3Writer::open(const QString &fn, long sr, bool s) { bool b = AudioFileWriter::open(fn + ".mp3", sr, s); if (!b) return false; lame = lame_init(); if (!lame) return false; bitRate = preferences.get(Pref::OutputFormatMp3Bitrate).toInt(); lame_set_in_samplerate(lame, sampleRate); lame_set_num_channels(lame, stereo ? 2 : 1); lame_set_out_samplerate(lame, sampleRate); // TODO: do we need this? lame_set_bWriteVbrTag(lame, 0); lame_set_mode(lame, stereo ? STEREO : MONO); lame_set_brate(lame, bitRate); if (lame_init_params(lame) == -1) return false; return true; }
int main (int argc, char **argv) { char *url; int brate = 32; int c; while ((c = getopt(argc, argv, "u:b:")) != -1) switch (c) { case 'u': url = strdup(optarg); break; case 'b': brate = atoi(optarg); break; default: abort(); } // libev loop = ev_default_loop(0); ev_signal_init(&sigint_sig, sigint_cb, SIGINT); ev_signal_start (loop, &sigint_sig); ev_async_init(&async, send_cb); ev_async_start(loop, &async); // jack jack_status_t status; ringbuf = jack_ringbuffer_create(buffer_size); framebuf = malloc(buffer_samples * sizeof(jack_default_audio_sample_t)); client = jack_client_open("jack2rtmp", JackNullOption, &status); if (client == NULL) { fprintf(stderr, "jack server not running?\n"); return EXIT_FAILURE; } jack_on_shutdown(client, jack_shutdown, NULL); jack_set_process_callback(client, jack_callback, NULL); //jack_set_latency_callback(client, jack_latency_callback, NULL); output_port = jack_port_register(client, "1", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); //jack_port_register(client, "2", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); if (jack_activate(client)) { fprintf(stderr, "cannot activate client"); } // lame mp3 = lame_init(); lame_set_num_channels(mp3, 1); lame_set_mode(mp3, MONO); lame_set_in_samplerate(mp3, 48000); lame_set_out_samplerate(mp3, 44100); lame_set_quality(mp3, 2); // 0=best (very slow), 9=worst. lame_set_brate(mp3, brate); lame_init_params(mp3); // rtmp rtmp_o = RTMP_Alloc(); if (rtmp_o == NULL) { fprintf(stderr, "RTMP_Alloc\n"); return EXIT_FAILURE; } RTMP_Init(rtmp_o); RTMP_SetupURL(rtmp_o, url); RTMP_EnableWrite(rtmp_o); if (!RTMP_Connect(rtmp_o, NULL) || !RTMP_ConnectStream(rtmp_o, 0)) { RTMP_Free(rtmp_o); fprintf(stderr, "Can not connect.\n"); return EXIT_FAILURE; } else { fprintf(stderr, "Connected.\n"); } /* char *rtmp_buffer = malloc(4096); char *rtmp_top = rtmp_buffer + RTMP_MAX_HEADER_SIZE; char *outend = rtmp_buffer + 4096; *rtmp_top = (uint8_t) AMF_STRING; rtmp_top++; rtmp_top = put_amf_string(rtmp_top, "@setDataFrame"); *rtmp_top = (uint8_t) AMF_STRING; rtmp_top++; rtmp_top = put_amf_string(rtmp_top, "onMetaData"); // описание объекта *rtmp_top = (uint8_t) 8; rtmp_top++; rtmp_top = AMF_EncodeInt32(rtmp_top, outend, 8); // содержимое объекта rtmp_top = put_amf_string(rtmp_top, "duration"); rtmp_top = AMF_EncodeNumber(rtmp_top, outend, 0); rtmp_top = put_amf_string(rtmp_top, "audiodatarate"); rtmp_top = AMF_EncodeNumber(rtmp_top, outend, brate); rtmp_top = put_amf_string(rtmp_top, "audiosamplerate"); rtmp_top = AMF_EncodeNumber(rtmp_top, outend, 44100); rtmp_top = put_amf_string(rtmp_top, "audiosamplesize"); rtmp_top = AMF_EncodeNumber(rtmp_top, outend, 16); rtmp_top = put_amf_string(rtmp_top, "stereo"); rtmp_top = AMF_EncodeBoolean(rtmp_top, outend, FALSE); rtmp_top = put_amf_string(rtmp_top, "audiocodecid"); rtmp_top = AMF_EncodeNumber(rtmp_top, outend, 2); rtmp_top = put_amf_string(rtmp_top, "encoder"); *rtmp_top = (uint8_t) AMF_STRING; rtmp_top++; rtmp_top = put_amf_string(rtmp_top, "Lavf53.21.1"); rtmp_top = put_amf_string(rtmp_top, "filesize"); rtmp_top = AMF_EncodeNumber(rtmp_top, outend, 0); // конец объекта rtmp_top = put_amf_string(rtmp_top, ""); *rtmp_top = (uint8_t) AMF_OBJECT_END; rtmp_top++; rtmp_w.m_headerType = RTMP_PACKET_SIZE_LARGE; rtmp_w.m_nChannel = 0x04; // source channel rtmp_w.m_nBodySize = rtmp_top - rtmp_buffer - RTMP_MAX_HEADER_SIZE; rtmp_w.m_packetType = RTMP_PACKET_TYPE_INFO; rtmp_w.m_nInfoField2 = rtmp_o->m_stream_id; rtmp_w.m_body = rtmp_buffer + RTMP_MAX_HEADER_SIZE; if ( !RTMP_SendPacket(rtmp_o, &rtmp_w, TRUE) ) { fprintf(stderr, "RTMP_SendPacket error\n"); } free(rtmp_buffer); */ int off = 0; setsockopt(RTMP_Socket(rtmp_o), SOL_TCP, TCP_NODELAY, &off, sizeof(off)); rtmp_i = TRUE; ev_loop(loop, 0); jack_ringbuffer_free(ringbuf); //jack_client_close(client); return EXIT_SUCCESS; }
/*------------------------------------------------------------------------------ * Open an encoding session *----------------------------------------------------------------------------*/ bool LameLibEncoder :: open ( void ) throw ( Exception ) { if ( isOpen() ) { close(); } lameGlobalFlags = lame_init(); // ugly lame returns -1 in a pointer on allocation errors if ( !lameGlobalFlags || ((int)lameGlobalFlags) == -1 ) { throw Exception( __FILE__, __LINE__, "lame lib init error", (int) lameGlobalFlags); } if ( 0 > lame_set_num_channels( lameGlobalFlags, getInChannel()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting channels error", getInChannel() ); } if ( 0 > lame_set_mode( lameGlobalFlags, getInChannel() == 1 ? MONO : JOINT_STEREO) ) { throw Exception( __FILE__, __LINE__, "lame lib setting mode error", JOINT_STEREO ); } reportEvent( 5, "set lame mode", lame_get_mode( lameGlobalFlags)); reportEvent( 5, "set lame channels", lame_get_num_channels( lameGlobalFlags)); if ( 0 > lame_set_in_samplerate( lameGlobalFlags, getInSampleRate()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting input sample rate error", getInSampleRate() ); } reportEvent( 5, "set lame in sample rate", lame_get_in_samplerate( lameGlobalFlags)); if ( 0 > lame_set_out_samplerate( lameGlobalFlags, getOutSampleRate()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting output sample rate error", getOutSampleRate() ); } reportEvent( 5, "set lame out sample rate", lame_get_out_samplerate( lameGlobalFlags)); if ( 0 > lame_set_brate( lameGlobalFlags, getOutBitrate()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting output bit rate error", getOutBitrate() ); } reportEvent( 5, "set lame bit rate", lame_get_brate( lameGlobalFlags)); if ( lowpass ) { if ( 0 > lame_set_lowpassfreq( lameGlobalFlags, lowpass) ) { throw Exception( __FILE__, __LINE__, "lame lib setting lowpass frequency error", lowpass ); } reportEvent( 5, "set lame lowpass frequency", lame_get_lowpassfreq( lameGlobalFlags)); } if ( highpass ) { if ( 0 > lame_set_highpassfreq( lameGlobalFlags, highpass) ) { throw Exception( __FILE__, __LINE__, "lame lib setting highpass frequency error", lowpass ); } reportEvent( 5, "set lame highpass frequency", lame_get_highpassfreq( lameGlobalFlags)); } // not configurable lame settings if ( 0 > lame_set_quality( lameGlobalFlags, 2) ) { throw Exception( __FILE__, __LINE__, "lame lib setting quality error", 2 ); } reportEvent( 5, "set lame quality", lame_get_quality( lameGlobalFlags)); if ( 0 > lame_set_exp_nspsytune( lameGlobalFlags, 1) ) { throw Exception( __FILE__, __LINE__, "lame lib setting psycho acoustic model error"); } reportEvent( 5, "set lame psycho acoustic model", lame_get_exp_nspsytune( lameGlobalFlags)); if ( 0 > lame_set_error_protection( lameGlobalFlags, 1) ) { throw Exception( __FILE__, __LINE__, "lame lib setting error protection error", 1 ); } reportEvent( 5, "set lame error protection", lame_get_error_protection( lameGlobalFlags)); // let lame init its own params based on our settings if ( 0 > lame_init_params( lameGlobalFlags) ) { throw Exception( __FILE__, __LINE__, "lame lib initializing params error" ); } lame_print_config( lameGlobalFlags); // open the underlying sink if ( !sink->open() ) { throw Exception( __FILE__, __LINE__, "lame lib opening underlying sink error"); } return true; }
bool ACMStream::open(const AEncodeProperties & the_Properties) { bool bResult = false; // Init the MP3 Stream // Init the global flags structure gfp = lame_init(); // Set input sample frequency lame_set_in_samplerate( gfp, my_SamplesPerSec ); // Set output sample frequency lame_set_out_samplerate( gfp, my_OutBytesPerSec ); lame_set_num_channels( gfp, my_Channels ); if (my_Channels == 1) lame_set_mode( gfp, MONO ); else lame_set_mode( gfp, (MPEG_mode_e)the_Properties.GetChannelModeValue()) ; /// \todo Get the mode from the default configuration // lame_set_VBR( gfp, vbr_off ); /// \note VBR not supported for the moment lame_set_VBR( gfp, my_VBRMode ); /// \note VBR not supported for the moment if (my_VBRMode == vbr_abr) { lame_set_VBR_q( gfp, 1 ); lame_set_VBR_mean_bitrate_kbps( gfp, (my_AvgBytesPerSec * 8 + 500) / 1000 ); if (24000 > lame_get_in_samplerate( gfp )) { // For MPEG-II lame_set_VBR_min_bitrate_kbps( gfp, 8); lame_set_VBR_max_bitrate_kbps( gfp, 160); } else { // For MPEG-I lame_set_VBR_min_bitrate_kbps( gfp, 32); lame_set_VBR_max_bitrate_kbps( gfp, 320); } } // Set bitrate lame_set_brate( gfp, my_AvgBytesPerSec * 8 / 1000 ); /// \todo Get the mode from the default configuration // Set copyright flag? lame_set_copyright( gfp, the_Properties.GetCopyrightMode()?1:0 ); // Do we have to tag it as non original lame_set_original( gfp, the_Properties.GetOriginalMode()?1:0 ); // Add CRC? lame_set_error_protection( gfp, the_Properties.GetCRCMode()?1:0 ); // Set private bit? lame_set_extension( gfp, the_Properties.GetPrivateMode()?1:0 ); // INFO tag support not possible in ACM - it requires rewinding // output stream to the beginning after encoding is finished. lame_set_bWriteVbrTag( gfp, 0 ); if (0 == lame_init_params( gfp )) { //LAME encoding call will accept any number of samples. if ( 0 == lame_get_version( gfp ) ) { // For MPEG-II, only 576 samples per frame per channel my_SamplesPerBlock = 576 * lame_get_num_channels( gfp ); } else { // For MPEG-I, 1152 samples per frame per channel my_SamplesPerBlock = 1152 * lame_get_num_channels( gfp ); } } my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "version =%d",lame_get_version( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Layer =3"); switch ( lame_get_mode( gfp ) ) { case STEREO: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Stereo" ); break; case JOINT_STEREO: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Joint-Stereo" ); break; case DUAL_CHANNEL: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Forced Stereo" ); break; case MONO: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Mono" ); break; case NOT_SET: /* FALLTROUGH */ default: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "mode =Error (unknown)" ); break; } my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "sampling frequency =%.1f kHz", lame_get_in_samplerate( gfp ) /1000.0 ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "bitrate =%d kbps", lame_get_brate( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Vbr Min bitrate =%d kbps", lame_get_VBR_min_bitrate_kbps( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Vbr Max bitrate =%d kbps", lame_get_VBR_max_bitrate_kbps( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Quality Setting =%d", lame_get_quality( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Low pass frequency =%d", lame_get_lowpassfreq( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Low pass width =%d", lame_get_lowpasswidth( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "High pass frequency =%d", lame_get_highpassfreq( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "High pass width =%d", lame_get_highpasswidth( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "No Short Blocks =%d", lame_get_no_short_blocks( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "de-emphasis =%d", lame_get_emphasis( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "private flag =%d", lame_get_extension( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "copyright flag =%d", lame_get_copyright( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "original flag =%d", lame_get_original( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "CRC =%s", lame_get_error_protection( gfp ) ? "on" : "off" ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Fast mode =%s", ( lame_get_quality( gfp ) )? "enabled" : "disabled" ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Force mid/side stereo =%s", ( lame_get_force_ms( gfp ) )?"enabled":"disabled" ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Padding Type =%d", lame_get_padding_type( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Disable Resorvoir =%d", lame_get_disable_reservoir( gfp ) ); my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "VBR =%s, VBR_q =%d, VBR method =", ( lame_get_VBR( gfp ) !=vbr_off ) ? "enabled": "disabled", lame_get_VBR_q( gfp ) ); switch ( lame_get_VBR( gfp ) ) { case vbr_off: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_off" ); break; case vbr_mt : my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_mt" ); break; case vbr_rh : my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_rh" ); break; case vbr_mtrh: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_mtrh" ); break; case vbr_abr: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "vbr_abr (average bitrate %d kbps)", lame_get_VBR_mean_bitrate_kbps( gfp ) ); break; default: my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "error, unknown VBR setting"); break; } my_debug->OutPut(DEBUG_LEVEL_FUNC_DEBUG, "Write VBR Header =%s\n", ( lame_get_bWriteVbrTag( gfp ) ) ?"Yes":"No"); #ifdef FROM_DLL beConfig.format.LHV1.dwReSampleRate = my_OutBytesPerSec; // force the user resampling #endif // FROM_DLL bResult = true; return bResult; }
//________________________________________________ // Init lame encoder // frequence : Impose frequency , 0 means reuse the incoming fq // mode : ADM_STEREO etc... // bitrate : Bitrate in kbps (96,192...) // return 0 : init failed // 1 : init succeeded //_______________________________________________ uint8_t AVDMProcessAudio_Lame::initLame(uint32_t frequence, uint32_t mode, uint32_t bitrate, ADM_LAME_PRESET preset) { int ret, ratio; MPEG_mode_e mmode; double dratio; myflags = lame_init(); if (myflags == NULL) return 0; // recompute output length // since we compress recompute the length in bytes double comp; comp=_instream->getLength(); comp/=2; // 16 bits sample comp/=_wavheader->channels; // We got sample comp/=_wavheader->frequency; // and no we got seconds comp*=bitrate*1000; comp/=8; // now we got bytes _length=(uint32_t) floor(comp+1); printf("Incoming : %lu bytes, fq : %lu, channel : %lu bitrate: %lu outgoing : %lu\n", _instream->getLength(),_wavheader->frequency,_wavheader->channels,bitrate,_length); //initLame(frequence,mode,bitrate); ret = lame_set_in_samplerate(myflags, _instream->getInfo()->frequency); ret = lame_set_num_channels(myflags, _instream->getInfo()->channels); if (frequence == 0) // keep same as instream frequence = _instream->getInfo()->frequency; printf("\n output frequency : %lu\n", frequence); ret = lame_set_out_samplerate(myflags, frequence); ret = lame_set_quality(myflags, 2); //max quality); if (_instream->getInfo()->channels == 2) { switch (mode) { case ADM_STEREO: mmode = STEREO; break; case ADM_JSTEREO: mmode = JOINT_STEREO; break; default: printf("\n **** unknown mode ***\n"); mmode = STEREO; break; } } else { mmode = MONO; printf("\n mono audio mp3"); } _mode=mmode; ret = lame_set_brate(myflags, bitrate); ret = lame_set_mode(myflags, mmode); // 0 stereo 1 jstero ret = lame_init_params(myflags); if (ret == -1) return 0; // update bitrate in header _wavheader->byterate = (bitrate >> 3) * 1000; // configure CBR/ABR/... _preset=preset; switch(preset) { default: case ADM_LAME_PRESET_CBR: break; case ADM_LAME_PRESET_ABR: lame_set_preset( myflags, bitrate); _wavheader->blockalign=1152; break; case ADM_LAME_PRESET_EXTREME: _wavheader->blockalign=1152; lame_set_preset( myflags, EXTREME); break; } lame_print_config(myflags); lame_print_internals(myflags); return 1; }
void lame_encoder_impl_internal::set_output_sample_rate(int _OutputSampleRate) { int lameRet = lame_set_out_samplerate(m_Lame.get(), _OutputSampleRate); DT_LAME_CHECK_ERR(lameRet); }
////////////////////////////////////////////////////////////////////// // Init - initialized or reiniyialized encoder SDK with given input // and output settings ////////////////////////////////////////////////////////////////////// HRESULT CEncoder::Init() { CAutoLock l(&m_lock); m_outOffset = 0; m_outReadOffset = 0; m_bFinished = FALSE; m_frameCount = 0; if (!pgf) { if (!m_bInpuTypeSet || !m_bOutpuTypeSet) return E_UNEXPECTED; // Init Lame library // note: newer, safer interface which doesn't // allow or require direct access to 'gf' struct is being written // see the file 'API' included with LAME. if (pgf = lame_init()) { lame_set_num_channels(pgf, m_wfex.nChannels); lame_set_in_samplerate(pgf, m_wfex.nSamplesPerSec); lame_set_out_samplerate(pgf, m_mabsi.dwSampleRate); if ((lame_get_out_samplerate(pgf) >= 32000) && (m_mabsi.dwBitrate < 32)) lame_set_brate(pgf, 32); else lame_set_brate(pgf, m_mabsi.dwBitrate); lame_set_VBR(pgf, m_mabsi.vmVariable); lame_set_VBR_min_bitrate_kbps(pgf, m_mabsi.dwVariableMin); lame_set_VBR_max_bitrate_kbps(pgf, m_mabsi.dwVariableMax); lame_set_copyright(pgf, m_mabsi.bCopyright); lame_set_original(pgf, m_mabsi.bOriginal); lame_set_error_protection(pgf, m_mabsi.bCRCProtect); lame_set_bWriteVbrTag(pgf, m_mabsi.dwXingTag); lame_set_strict_ISO(pgf, m_mabsi.dwStrictISO); lame_set_VBR_hard_min(pgf, m_mabsi.dwEnforceVBRmin); if (lame_get_num_channels(pgf) == 2 && !m_mabsi.bForceMono) { //int act_br = pgf->VBR ? pgf->VBR_min_bitrate_kbps + pgf->VBR_max_bitrate_kbps / 2 : pgf->brate; // Disabled. It's for user's consideration now //int rel = pgf->out_samplerate / (act_br + 1); //pgf->mode = rel < 200 ? m_mabsi.ChMode : JOINT_STEREO; lame_set_mode(pgf, m_mabsi.ChMode); } else lame_set_mode(pgf, MONO); if (lame_get_mode(pgf) == JOINT_STEREO) lame_set_force_ms(pgf, m_mabsi.dwForceMS); else lame_set_force_ms(pgf, 0); // pgf->mode_fixed = m_mabsi.dwModeFixed; if (m_mabsi.dwVoiceMode != 0) { lame_set_lowpassfreq(pgf,12000); ///pgf->VBR_max_bitrate_kbps = 160; } if (m_mabsi.dwKeepAllFreq != 0) { ///pgf->lowpassfreq = -1; ///pgf->highpassfreq = -1; /// not available anymore } lame_set_quality(pgf, m_mabsi.dwQuality); lame_set_VBR_q(pgf, m_mabsi.dwVBRq); lame_init_params(pgf); // encoder delay compensation { int const nch = lame_get_num_channels(pgf); short * start_padd = (short *)calloc(48, nch * sizeof(short)); int out_bytes = 0; if (nch == 2) out_bytes = lame_encode_buffer_interleaved(pgf, start_padd, 48, m_outFrameBuf, OUT_BUFFER_SIZE); else out_bytes = lame_encode_buffer(pgf, start_padd, start_padd, 48, m_outFrameBuf, OUT_BUFFER_SIZE); if (out_bytes > 0) m_outOffset += out_bytes; free(start_padd); } return S_OK; } return E_FAIL; } return S_OK; }
//________________________________________________ // Init lame encoder // frequence : Impose frequency , 0 means reuse the incoming fq // mode : ADM_STEREO etc... // bitrate : Bitrate in kbps (96,192...) // return 0 : init failed // 1 : init succeeded //_______________________________________________ uint8_t AUDMEncoder_Lame::init(ADM_audioEncoderDescriptor *config) { int ret; MPEG_mode_e mmode; uint32_t frequence; LAME_encoderParam *lameConf=(LAME_encoderParam *)config->param; ADM_assert(config->paramSize==sizeof(LAME_encoderParam)); lameFlags = lame_init(); if (lameFlags == NULL) return 0; if(_incoming->getInfo()->channels>2) { printf("Too many channels\n"); return 0; } // recompute output length ret = lame_set_in_samplerate(MYFLAGS, _wavheader->frequency); ret = lame_set_num_channels(MYFLAGS, _wavheader->channels); frequence = _wavheader->frequency; printf("\n output frequency : %lu\n", frequence); ret = lame_set_out_samplerate(MYFLAGS, frequence); ret = lame_set_quality(MYFLAGS, 2); if (_wavheader->channels == 2) { switch (lameConf->mode) { case ADM_STEREO: mmode = STEREO; break; case ADM_JSTEREO: mmode = JOINT_STEREO; break; default: printf("\n **** unknown mode ***\n"); mmode = STEREO; break; } } else { mmode = MONO; printf("\n mono audio mp3"); } ret = lame_set_brate(MYFLAGS, config->bitrate); ret = lame_set_mode(MYFLAGS, mmode); // 0 stereo 1 jstero ret = lame_set_quality(MYFLAGS, lameConf->quality); // 0 stereo 1 jstero ret = lame_set_disable_reservoir(MYFLAGS,lameConf->disableReservoir); printf("[Lame]Using quality of %d\n",lame_get_quality(MYFLAGS)); ret = lame_init_params(MYFLAGS); if (ret == -1) return 0; // update bitrate in header _wavheader->byterate = (config->bitrate >> 3) * 1000; #define BLOCK_SIZE 1152 // configure CBR/ABR/... _preset=lameConf->preset; switch(_preset) { default: case ADM_LAME_PRESET_CBR: break; case ADM_LAME_PRESET_ABR: lame_set_preset( MYFLAGS, config->bitrate); _wavheader->blockalign=BLOCK_SIZE; break; case ADM_LAME_PRESET_EXTREME: _wavheader->blockalign=BLOCK_SIZE; lame_set_preset( MYFLAGS, EXTREME); break; } lame_print_config(MYFLAGS); lame_print_internals(MYFLAGS); _chunk=BLOCK_SIZE*_wavheader->channels; return 1; }
encoder_funcs_t* init_lame( output_format_t* format, int channels, int bitrate ) { encoder_funcs_t* funcs = NULL; lame_opts = lame_init(); if (lame_opts==NULL) { rotter_error("lame error: failed to initialise."); return NULL; } if ( 0 > lame_set_num_channels( lame_opts, channels ) ) { rotter_error("lame error: failed to set number of channels."); return NULL; } if ( 0 > lame_set_in_samplerate( lame_opts, jack_get_sample_rate( client ) )) { rotter_error("lame error: failed to set input samplerate."); return NULL; } if ( 0 > lame_set_out_samplerate( lame_opts, jack_get_sample_rate( client ) )) { rotter_error("lame error: failed to set output samplerate."); return NULL; } if ( 0 > lame_set_brate( lame_opts, bitrate) ) { rotter_error("lame error: failed to set bitrate."); return NULL; } if ( 0 > lame_init_params( lame_opts ) ) { rotter_error("lame error: failed to initialize parameters."); return NULL; } rotter_info( "Encoding using liblame version %s.", get_lame_version() ); rotter_debug( " Input: %d Hz, %d channels", lame_get_in_samplerate(lame_opts), lame_get_num_channels(lame_opts)); rotter_debug( " Output: %s Layer 3, %d kbps, %s", lame_get_version_name(lame_opts), lame_get_brate(lame_opts), lame_get_mode_name(lame_opts)); // Allocate memory for encoded audio mpeg_buffer = malloc( 1.25*SAMPLES_PER_FRAME + 7200 ); if ( mpeg_buffer==NULL ) { rotter_error( "Failed to allocate memery for encoded audio." ); return NULL; } // Allocate memory for callback functions funcs = calloc( 1, sizeof(encoder_funcs_t) ); if ( funcs==NULL ) { rotter_error( "Failed to allocate memery for encoder callback functions structure." ); return NULL; } funcs->file_suffix = "mp3"; funcs->open = open_mpegaudio_file; funcs->close = close_mpegaudio_file; funcs->write = write_lame; funcs->deinit = deinit_lame; return funcs; }
//core function to encide WAV to MP3, relying on LAME library void encode(char* wavFilePath, char* mp3FilePath) { FILE* wavFile = fopen(wavFilePath, "rb"); FILE* mp3File = fopen(mp3FilePath, "wb+"); int readPCMSampleCount; short int pcmBuffer[PCM_BUF_SIZE]; unsigned char mp3Buffer[MP3_BUF_SIZE]; unsigned short channel; unsigned long sampleRate; unsigned short blockAlign; lame_t lame = lame_init(); if((wavFile == NULL) || (mp3File == NULL)) { printErrorMessage(FILE_IO_EXCEPTION); return; } if(lame == NULL) { printErrorMessage(LAME_API_ERROR); return; } //Set number of channels else if(fseek(wavFile, 22, SEEK_SET) != 0) { printErrorMessage(FILE_IO_EXCEPTION); return; } else if(fread(&channel, 2, 1, wavFile) < 1) { printErrorMessage(FILE_IO_EXCEPTION); return; } else { lame_set_num_channels(lame, channel); lame_set_mode(lame, (channel == 1) ? MONO : JOINT_STEREO); } //Set number of sample rate if(fseek(wavFile, 24, SEEK_SET) != 0) { printErrorMessage(FILE_IO_EXCEPTION); return; } else if(fread(&sampleRate, 4, 1, wavFile) < 1) { printErrorMessage(FILE_IO_EXCEPTION); return; } else { lame_set_in_samplerate(lame, sampleRate); lame_set_out_samplerate(lame, sampleRate); } //Set block align (byte/sample) if(fseek(wavFile, 32, SEEK_SET) != 0) { printErrorMessage(FILE_IO_EXCEPTION); return; } else if(fread(&blockAlign, 4, 1, wavFile) < 1) { printErrorMessage(FILE_IO_EXCEPTION); return; } //Look for data chank in the WAV file if(fseek(wavFile, 36, SEEK_SET) != 0) { printErrorMessage(FILE_IO_EXCEPTION); return; } else { char data[5]; data[4] = '\0'; while(fread(data, 4, 1, wavFile) == 1) { if(strcmp(data, "data") != 0) { //Search data chank by 1 byte fseek(wavFile, -3, SEEK_CUR); continue; } else if(fseek(wavFile, 4, SEEK_CUR)) { //data chank was found, then skip next 4 byte(indicating data size) to proceed printErrorMessage(FILE_IO_EXCEPTION); return; } else { //Now we are pointing the head of the PCM data, let's proceed break; } } //If data chank cannot be detected if(feof(wavFile)) { printErrorMessage(NOT_WAV_HEADER); return; } } //Encoding conficuration with "good" level quality lame_set_quality(lame, 5); lame_set_VBR(lame, vbr_default); lame_set_VBR_q(lame, 5); if(lame_init_params(lame) == -1) { printErrorMessage(LAME_API_ERROR); return; } //Perfoem encoding do { int encodedSampleCount; readPCMSampleCount = fread(pcmBuffer, blockAlign, PCM_BUF_SIZE / blockAlign, wavFile); if(readPCMSampleCount != 0) { if(channel == 1) { //For monoral case short int pcmBufferRight[PCM_BUF_SIZE]; short int pcmBufferLeft[PCM_BUF_SIZE]; int i; for(i = 0; i < PCM_BUF_SIZE; i++) { pcmBufferRight[i] = pcmBuffer[i]; pcmBufferLeft[i] = pcmBuffer[i]; } encodedSampleCount = lame_encode_buffer(lame, pcmBufferLeft, pcmBufferRight, readPCMSampleCount, mp3Buffer, MP3_BUF_SIZE); } else { //For stereo case encodedSampleCount = lame_encode_buffer_interleaved(lame, pcmBuffer, readPCMSampleCount, mp3Buffer, MP3_BUF_SIZE); } } else { encodedSampleCount = lame_encode_flush(lame, mp3Buffer, MP3_BUF_SIZE); } if(encodedSampleCount < 0) { printErrorMessage(LAME_API_ERROR); } else { fwrite(mp3Buffer, encodedSampleCount, 1, mp3File); } } while(readPCMSampleCount != 0); lame_close(lame); fclose(wavFile); fclose(mp3File); }
lame_global_flags* simple_lame_lib_init( JNIEnv* env, jint inSamplerate, jint outChannel, jint outSamplerate, jint outBitrate, jint quality, jstring id3tagTitle, jstring id3tagArtist, jstring id3tagAlbum, jstring id3tagYear, jstring id3tagComment) { if (local_log) { __android_log_print(ANDROID_LOG_VERBOSE, TAG, "Start lame init."); } lame_global_flags* glf = lame_init(); lame_set_in_samplerate(glf, inSamplerate); lame_set_num_channels(glf, outChannel); lame_set_out_samplerate(glf, outSamplerate); lame_set_brate(glf, outBitrate); lame_set_quality(glf, quality); const jchar* title = NULL; const jchar* artist = NULL; const jchar* album = NULL; const jchar* year = NULL; const jchar* comment = NULL; if (id3tagTitle) { title = (*env)->GetStringChars(env, id3tagTitle, NULL); } if (id3tagArtist) { artist = (*env)->GetStringChars(env, id3tagArtist, NULL); } if (id3tagAlbum) { album = (*env)->GetStringChars(env, id3tagAlbum, NULL); } if (id3tagYear) { year = (*env)->GetStringChars(env, id3tagYear, NULL); } if (id3tagComment) { comment = (*env)->GetStringChars(env, id3tagComment, NULL); } if (title || artist || album || year || comment) { id3tag_init(glf); if (title) { id3tag_set_title(glf, (const char*)title); (*env)->ReleaseStringChars(env, id3tagTitle, title); } if (artist) { id3tag_set_artist(glf, (const char*)artist); (*env)->ReleaseStringChars(env, id3tagArtist, artist); } if (album) { id3tag_set_album(glf, (const char*)album); (*env)->ReleaseStringChars(env, id3tagAlbum, album); } if (year) { id3tag_set_year(glf, (const char*)year); (*env)->ReleaseStringChars(env, id3tagYear, year); } if (comment) { id3tag_set_comment(glf, (const char*)comment); (*env)->ReleaseStringChars(env, id3tagComment, comment); } } lame_init_params(glf); if (local_log) { __android_log_print(ANDROID_LOG_VERBOSE, TAG, "End lame init."); } return glf; }
/*------------------------------------------------------------------------------ * Open an encoding session *----------------------------------------------------------------------------*/ bool LameLibEncoder :: open ( void ) throw ( Exception ) { if ( isOpen() ) { close(); } lameGlobalFlags = lame_init(); // ugly lame returns -1 in a pointer on allocation errors if ( !lameGlobalFlags || ((int)lameGlobalFlags) == -1 ) { throw Exception( __FILE__, __LINE__, "lame lib init error", (int) lameGlobalFlags); } if ( 0 > lame_set_num_channels( lameGlobalFlags, getInChannel()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting channels error", getInChannel() ); } if ( 0 > lame_set_mode( lameGlobalFlags, getOutChannel() == 1 ? MONO : JOINT_STEREO) ) { throw Exception( __FILE__, __LINE__, "lame lib setting mode error", JOINT_STEREO ); } reportEvent( 5, "set lame mode", lame_get_mode( lameGlobalFlags)); reportEvent( 5, "set lame channels", lame_get_num_channels( lameGlobalFlags)); if ( 0 > lame_set_in_samplerate( lameGlobalFlags, getInSampleRate()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting input sample rate error", getInSampleRate() ); } reportEvent( 5, "set lame in sample rate", lame_get_in_samplerate( lameGlobalFlags)); if ( 0 > lame_set_out_samplerate( lameGlobalFlags, getOutSampleRate()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting output sample rate error", getOutSampleRate() ); } reportEvent( 5, "set lame out sample rate", lame_get_out_samplerate( lameGlobalFlags)); switch ( getOutBitrateMode() ) { case cbr: { if ( 0 > lame_set_brate( lameGlobalFlags, getOutBitrate()) ) { throw Exception( __FILE__, __LINE__, "lame lib setting output bit rate error", getOutBitrate() ); } reportEvent( 5, "set lame bit rate", lame_get_brate( lameGlobalFlags)); double d = (1.0 - getOutQuality()) * 10.0; int q = int (d + 0.499999); if ( 0 > lame_set_quality( lameGlobalFlags, q) ) { throw Exception( __FILE__, __LINE__, "lame lib setting quality error", q); } reportEvent( 5, "set lame quality", lame_get_quality( lameGlobalFlags)); } break; case abr: if ( 0 > lame_set_VBR( lameGlobalFlags,vbr_abr)) { throw Exception( __FILE__, __LINE__, "lame lib setting abr error", vbr_abr); } reportEvent( 5, "set lame abr bitrate", lame_get_VBR( lameGlobalFlags)); if ( 0 > lame_set_VBR_mean_bitrate_kbps( lameGlobalFlags, getOutBitrate())) { throw Exception( __FILE__, __LINE__, "lame lib setting abr mean bitrate error", getOutBitrate()); } reportEvent( 5, "set lame abr mean bitrate", lame_get_VBR_mean_bitrate_kbps( lameGlobalFlags)); break; case vbr: { if ( 0 > lame_set_VBR( lameGlobalFlags, vbr_mtrh)) { throw Exception( __FILE__, __LINE__, "lame lib setting vbr error", vbr_mtrh ); } reportEvent( 5, "set lame vbr bitrate", lame_get_VBR( lameGlobalFlags)); double d = (1.0 - getOutQuality()) * 10.0; int q = int (d + 0.499999); if ( 0 > lame_set_VBR_q( lameGlobalFlags, q) ) { throw Exception( __FILE__, __LINE__, "lame lib setting vbr quality error", q); } reportEvent( 5, "set lame vbr quality", lame_get_VBR_q( lameGlobalFlags)); } break; } if ( 0 > lame_set_lowpassfreq( lameGlobalFlags, lowpass) ) { throw Exception( __FILE__, __LINE__, "lame lib setting lowpass frequency error", lowpass ); } reportEvent( 5, "set lame lowpass frequency", lame_get_lowpassfreq( lameGlobalFlags)); if ( 0 > lame_set_highpassfreq( lameGlobalFlags, highpass) ) { throw Exception( __FILE__, __LINE__, "lame lib setting highpass frequency error", lowpass ); } reportEvent( 5, "set lame highpass frequency", lame_get_highpassfreq( lameGlobalFlags)); // not configurable lame settings if ( 0 > lame_set_exp_nspsytune( lameGlobalFlags, 1) ) { throw Exception( __FILE__, __LINE__, "lame lib setting psycho acoustic model error"); } reportEvent( 5, "set lame psycho acoustic model", lame_get_exp_nspsytune( lameGlobalFlags)); if ( 0 > lame_set_error_protection( lameGlobalFlags, 1) ) { throw Exception( __FILE__, __LINE__, "lame lib setting error protection error", 1 ); } reportEvent( 5, "set lame error protection", lame_get_error_protection( lameGlobalFlags)); // let lame init its own params based on our settings if ( 0 > lame_init_params( lameGlobalFlags) ) { throw Exception( __FILE__, __LINE__, "lame lib initializing params error" ); } lame_print_config( lameGlobalFlags); // open the underlying sink if ( !sink->open() ) { throw Exception( __FILE__, __LINE__, "lame lib opening underlying sink error"); } return true; }
Mp3OutputStream::Mp3OutputStream() : global_fags(), bytes_per_sample(), bytes_per_second() #ifdef Mp3OutputStream_Buffering m_inBuffer(), m_inBufferLenght(), m_inBufferPos(), #endif ,m_outBuffer(), m_outBufferLenght() { } Mp3OutputStream::~Mp3OutputStream() { Close(); #ifdef Mp3OutputStream_Buffering delete [] m_inBuffer; #endif delete [] m_outBuffer; } bool Mp3OutputStream::Initialize(int samplerate, int numchannels, int bitspersamp) { global_fags = lame_init(); if(global_fags == nullptr) return false; //lame_set_errorf(global_fags, lame_debugger); lame_set_analysis(global_fags, 0); lame_set_in_samplerate(global_fags, samplerate); lame_set_bWriteVbrTag( global_fags, 0 ); lame_set_error_protection( global_fags, 0 ); lame_set_extension( global_fags, 0 ); lame_set_original( global_fags, 0 ); lame_set_VBR(global_fags, vbr_off); lame_set_num_channels(global_fags, numchannels); lame_set_mode( global_fags, STEREO); lame_set_out_samplerate(global_fags, 44100); // 9 = LQP_LOW_QUALITY // 2 = LQP_HIGH_QUALITY: // 0 = LQP_VERYHIGH_QUALITY //lame_set_quality(global_fags, 0 ); //lame_set_preset( global_fags, STANDARD_FAST); Settings& s = Global::Settings; #ifdef STREAMER_PAYD_VERSION lame_set_brate(global_fags, std::min(Mp3OutputStreamConstants::Presets[s.encoder_preset], 320)); #else lame_set_brate(global_fags, 64); #endif if(lame_init_params(global_fags) != 0) { OutputDebugString(_T("lame_init_params failed")); lame_close(global_fags); global_fags = nullptr; return false; } bytes_per_second = lame_get_brate(global_fags) / 8; #ifdef Mp3OutputStream_Buffering if ( 0 == lame_get_version( global_fags ) ) { // For MPEG-II, only 576 samples per frame per channel m_inBufferLenght = 576 * lame_get_num_channels( global_fags ); } else { // For MPEG-I, 1152 samples per frame per channel m_inBufferLenght = 1152 * lame_get_num_channels( global_fags ); } // delete buffers if(m_inBuffer != nullptr) delete [] m_inBuffer; m_inBuffer = new BYTE[m_inBufferLenght * 2]; #endif m_outBufferLenght = static_cast<int>( ( 1.25 * ( samplerate / numchannels ) + 7200 ) * 2.0); if(m_outBuffer != nullptr) delete [] m_outBuffer; m_outBuffer = new BYTE[m_outBufferLenght]; bytes_per_sample = bitspersamp / 8; return true; }
/* initialize the lame library */ static int mp3write_tilde_lame_init(t_mp3write *x) { time_t now; int ret; x->lgfp = lame_init(); /* set default parameters for now */ #ifndef UNIX /* load lame_enc.dll library */ HINSTANCE dll; dll=LoadLibrary("lame_enc.dll"); if(dll==NULL) { error("mp3write~: error loading lame_enc.dll"); closesocket(x->x_fd); x->x_fd = -1; post("mp3write~: connection closed"); return -1; } #endif { const char *lameVersion = get_lame_version(); post( "mp3write~ : using lame version : %s", lameVersion ); } /* setting lame parameters */ lame_set_num_channels( x->lgfp, 2); lame_set_in_samplerate( x->lgfp, sys_getsr() ); lame_set_out_samplerate( x->lgfp, x->x_samplerate ); lame_set_brate( x->lgfp, x->x_bitrate ); lame_set_mode( x->lgfp, x->x_mp3mode ); lame_set_quality( x->lgfp, x->x_mp3quality ); lame_set_emphasis( x->lgfp, 1 ); lame_set_original( x->lgfp, 1 ); lame_set_copyright( x->lgfp, 1 ); /* viva free music societies !!! */ lame_set_disable_reservoir( x->lgfp, 0 ); lame_set_padding_type( x->lgfp, PAD_NO ); ret = lame_init_params( x->lgfp ); if ( ret<0 ) { post( "mp3write~ : error : lame params initialization returned : %d", ret ); return -1; } else { x->x_lame=1; /* magic formula copied from windows dll for MPEG-I */ x->x_lamechunk = 2*1152; post( "mp3write~ : lame initialization done. (%d)", x->x_lame ); } lame_init_bitstream( x->lgfp ); /* setting tag information */ id3tag_init(x->lgfp); id3tag_v1_only(x->lgfp); id3tag_space_v1(x->lgfp); id3tag_set_artist(x->lgfp, "Pd Session"); now=time(NULL); sprintf( x->x_title, "Started at %s", ctime(&now) ); id3tag_set_title(x->lgfp, x->x_title ); return 0; }
int mp3_encode(int fd_in, int fd_out) { lame_global_flags *gfp; uint32_t i, j, k, count; int16_t *b0 = 0, *b1 = 0; unsigned char *c; int ret; /* calculate data size*/ k = (uint32_t) lseek(fd_in, 0, SEEK_CUR); i = (uint32_t) lseek(fd_in, 0, SEEK_END); lseek(fd_in, k, SEEK_SET); i -= k; k = 0; gfp = lame_init(); lame_set_errorf(gfp,lame_error_handler); lame_set_debugf(gfp,lame_error_handler); lame_set_msgf(gfp,lame_error_handler); lame_set_num_channels(gfp,2); lame_set_in_samplerate(gfp,8000); #if 0 lame_set_brate(gfp,64); /* compress 1:4 */ lame_set_mode(gfp,0); /* mode = stereo */ lame_set_quality(gfp,2); /* 2=high 5 = medium 7=low */ #else lame_set_quality(gfp,5); /* 2=high 5 = medium 7=low */ lame_set_mode(gfp,3); /* mode = mono */ if(lame_get_VBR(gfp) == vbr_off) lame_set_VBR(gfp, vbr_default); lame_set_VBR_quality(gfp, 7.0); lame_set_findReplayGain(gfp, 0); lame_set_bWriteVbrTag(gfp, 1); lame_set_out_samplerate(gfp,11025); /* lame_set_num_samples(gfp,i/2); */ #endif if(lame_init_params(gfp) < 0) { log_err("encode: failed to init lame"); return 0; } #define CHSZ (512*1024) #define OCHSZ (5*(CHSZ/8)+7200) b0 = (int16_t *) malloc(OCHSZ); b1 = (int16_t *) malloc(CHSZ); if(!b0 || !b1) { log_err("encode: out of memory"); if(b0) free(b0); if(b1) free(b1); return 0; } do { ret = 0; j = 0; count = 0; for(c = (unsigned char*) b1; count < CHSZ; c += ret) { j = (k + RSZ > i) ? i - k : RSZ; ret = read(fd_in,c,j); if(ret < 0) break; k += ret; count += ret; if(k == i) break; } if(ret < 0) break; if(count) { ret = lame_encode_buffer(gfp,b1,b1,count/2,(unsigned char *)b0,OCHSZ); if(ret < 0) break; c = (unsigned char *) b0; count = ret; for(j = 0; j < count; j += RSZ, c += ret) { ret = (j + RSZ > count) ? count - j : RSZ; write(fd_out,c,ret); } } } while(k < i); k = (uint32_t) lame_encode_flush(gfp,(unsigned char *)b0,OCHSZ); if(k) write(fd_out,b0,k); k = lame_get_lametag_frame(gfp,(unsigned char *)b0,OCHSZ); if(k > 0) write(fd_out,b0,k); lame_close(gfp); free(b0); free(b1); return 1; }
void setOutSamplerate( int rate ) { lame_set_out_samplerate(m_gf, rate); }
static switch_status_t shout_file_open(switch_file_handle_t *handle, const char *path) { shout_context_t *context; char *host, *file; char *username, *password, *port; char *err = NULL; const char *mpg123err = NULL; int portno = 0; if ((context = switch_core_alloc(handle->memory_pool, sizeof(*context))) == 0) { return SWITCH_STATUS_MEMERR; } if (!handle->samplerate) { handle->samplerate = 8000; } context->memory_pool = handle->memory_pool; context->samplerate = handle->samplerate; context->handle = handle; switch_thread_rwlock_create(&(context->rwlock), context->memory_pool); switch_thread_rwlock_rdlock(context->rwlock); switch_mutex_init(&context->audio_mutex, SWITCH_MUTEX_NESTED, context->memory_pool); if (switch_test_flag(handle, SWITCH_FILE_FLAG_READ)) { if (switch_buffer_create_dynamic(&context->audio_buffer, TC_BUFFER_SIZE, TC_BUFFER_SIZE * 2, 0) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n"); goto error; } context->mh = our_mpg123_new(NULL, NULL); if (mpg123_format_all(context->mh) != MPG123_OK) { MPGERROR(); } if (mpg123_param(context->mh, MPG123_FORCE_RATE, context->samplerate, 0) != MPG123_OK) { MPGERROR(); } if (handle->handler) { if (mpg123_param(context->mh, MPG123_FLAGS, MPG123_SEEKBUFFER | MPG123_MONO_MIX, 0) != MPG123_OK) { MPGERROR(); } if (mpg123_open_feed(context->mh) != MPG123_OK) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error opening mpg feed\n"); mpg123err = mpg123_strerror(context->mh); goto error; } context->stream_url = switch_core_sprintf(context->memory_pool, "http://%s", path); context->prebuf = handle->prebuf; launch_read_stream_thread(context); } else { handle->seekable = 1; if (mpg123_param(context->mh, MPG123_FLAGS, MPG123_MONO_MIX, 0) != MPG123_OK) { MPGERROR(); } if (mpg123_open(context->mh, path) != MPG123_OK) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error opening %s\n", path); mpg123err = mpg123_strerror(context->mh); goto error; } } } else if (switch_test_flag(handle, SWITCH_FILE_FLAG_WRITE)) { if (switch_test_flag(handle, SWITCH_FILE_WRITE_APPEND)) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_WARNING, "Appending to MP3 not supported.\n"); } if (!(context->gfp = lame_init())) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate lame\n"); goto error; } if (!handle->handler) { id3tag_init(context->gfp); id3tag_v2_only(context->gfp); id3tag_pad_v2(context->gfp); } context->channels = handle->channels; lame_set_brate(context->gfp, 16 * (handle->samplerate / 8000) * handle->channels); lame_set_num_channels(context->gfp, handle->channels); lame_set_in_samplerate(context->gfp, handle->samplerate); lame_set_out_samplerate(context->gfp, handle->samplerate); if (handle->channels == 2) { lame_set_mode(context->gfp, STEREO); } else { lame_set_mode(context->gfp, MONO); } lame_set_quality(context->gfp, 2); /* 2=high 5 = medium 7=low */ lame_set_errorf(context->gfp, log_error); lame_set_debugf(context->gfp, log_debug); lame_set_msgf(context->gfp, log_msg); if (handle->handler) { if (switch_buffer_create_dynamic(&context->audio_buffer, MY_BLOCK_SIZE, MY_BUF_LEN, 0) != SWITCH_STATUS_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Memory Error!\n"); goto error; } lame_set_bWriteVbrTag(context->gfp, 0); lame_mp3_tags_fid(context->gfp, NULL); username = switch_core_strdup(handle->memory_pool, path); if (!(password = strchr(username, ':'))) { err = "invalid url"; goto error; } *password++ = '\0'; if (!(host = strchr(password, '@'))) { err = "invalid url"; goto error; } *host++ = '\0'; if ((file = strchr(host, '/'))) { *file++ = '\0'; } else { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid URL: %s\n", path); goto error; } if ((port = strchr(host, ':'))) { *port++ = '\0'; if (port) { portno = atoi(port); } } if (!portno) { portno = 8000; } if (!(context->shout = shout_new())) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Could not allocate shout_t\n"); goto error; } if (shout_set_host(context->shout, host) != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting hostname: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_protocol(context->shout, SHOUT_PROTOCOL_HTTP) != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting protocol: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_port(context->shout, portno) != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting port: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_password(context->shout, password) != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting password: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_mount(context->shout, file) != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting mount: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_user(context->shout, username) != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting user: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_url(context->shout, "http://www.freeswitch.org") != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting name: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_description(context->shout, "FreeSWITCH mod_shout Broadcasting Module") != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting description: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_audio_info(context->shout, "bitrate", "24000") != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting bitrate: %s\n", shout_get_error(context->shout)); goto error; } if (shout_set_format(context->shout, SHOUT_FORMAT_MP3) != SHOUTERR_SUCCESS) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error setting format: %s\n", shout_get_error(context->shout)); goto error; } } else { /* lame being lame and all has FILE * coded into it's API for some functions so we gotta use it */ if (!(context->fp = fopen(path, "wb+"))) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error opening %s\n", path); goto error; } } } handle->samples = 0; handle->format = 0; handle->sections = 0; handle->speed = 0; handle->private_info = context; switch_thread_rwlock_unlock(context->rwlock); return SWITCH_STATUS_SUCCESS; error: switch_thread_rwlock_unlock(context->rwlock); if (err) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error: %s\n", err); } if (mpg123err) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error from mpg123: %s\n", mpg123err); } free_context(context); return SWITCH_STATUS_GENERR; }
bool AUDMEncoder_Lame::initialize (void) { int ret; MPEG_mode_e mmode; uint32_t frequence; lameFlags = lame_init (); if (lameFlags == NULL) return false; if (_incoming->getInfo ()->channels > 2) { printf ("[Lame]Too many channels\n"); return false; } // recompute output length ret = lame_set_in_samplerate (MYFLAGS, wavheader.frequency); ret = lame_set_num_channels (MYFLAGS, wavheader.channels); frequence = wavheader.frequency; printf ("[Lame] output frequency : %"PRIu32"\n", frequence); ret = lame_set_out_samplerate (MYFLAGS, frequence); ret = lame_set_quality (MYFLAGS, 2); if (wavheader.channels == 2) { mmode = STEREO; } else { mmode = MONO; printf ("[Lame] mono audio mp3"); } ret = lame_set_brate (MYFLAGS, _config.bitrate); ret = lame_set_mode (MYFLAGS, mmode); // 0 stereo 1 jstero ret = lame_set_quality (MYFLAGS, _config.quality); // 0 stereo 1 jstero ret = lame_set_disable_reservoir (MYFLAGS, _config.disableBitReservoir); printf ("[Lame]Using quality of %d\n", lame_get_quality (MYFLAGS)); // update bitrate in header wavheader.byterate = (_config.bitrate >> 3) * 1000; #define BLOCK_SIZE 1152 // configure CBR/ABR/... switch (_config.preset) { default: case ADM_LAME_PRESET_CBR: ADM_info("Lame : CBR Mode\n"); break; case ADM_LAME_PRESET_ABR: ADM_info("Lame : ABR Mode\n"); lame_set_preset (MYFLAGS, _config.bitrate); wavheader.blockalign = BLOCK_SIZE; break; case ADM_LAME_PRESET_EXTREME: ADM_info("Lame : Extreme Mode\n"); wavheader.blockalign = BLOCK_SIZE; lame_set_preset (MYFLAGS, EXTREME); break; } ret = lame_init_params (MYFLAGS); if (ret == -1) { printf("[Lame] Init params failes %d\n",ret); return false; } lame_print_config (MYFLAGS); lame_print_internals (MYFLAGS); _chunk = BLOCK_SIZE * wavheader.channels; return true; }