// Initialise the codec MastCodec_MPA::MastCodec_MPA( MastMimeType *type) : MastCodec(type) { // Set default values this->samplerate = MPA_DEFAULT_SAMPLERATE; this->channels = MPA_DEFAULT_CHANNELS; // Initialise twolame this->twolame = twolame_init(); if (this->twolame==NULL) { MAST_FATAL( "Failed to initialise TwoLame" ); } // Configure twolame if (twolame_set_num_channels( this->twolame, this->channels )) { MAST_WARNING( "Failed to set number of input channels" ); } if (twolame_set_in_samplerate( this->twolame, this->samplerate )) { MAST_WARNING( "Failed to set number of input samplerate" ); } // Apply MIME type parameters to the codec this->apply_mime_type_params( type ); // Get TwoLAME ready to go... twolame_init_params( this->twolame ); }
static bool twolame_encoder_setup(struct twolame_encoder *encoder, GError **error) { if (encoder->quality >= -1.0) { /* a quality was configured (VBR) */ if (0 != twolame_set_VBR(encoder->options, true)) { g_set_error(error, twolame_encoder_quark(), 0, "error setting twolame VBR mode"); return false; } if (0 != twolame_set_VBR_q(encoder->options, encoder->quality)) { g_set_error(error, twolame_encoder_quark(), 0, "error setting twolame VBR quality"); return false; } } else { /* a bit rate was configured */ if (0 != twolame_set_brate(encoder->options, encoder->bitrate)) { g_set_error(error, twolame_encoder_quark(), 0, "error setting twolame bitrate"); return false; } } if (0 != twolame_set_num_channels(encoder->options, encoder->audio_format.channels)) { g_set_error(error, twolame_encoder_quark(), 0, "error setting twolame num channels"); return false; } if (0 != twolame_set_in_samplerate(encoder->options, encoder->audio_format.sample_rate)) { g_set_error(error, twolame_encoder_quark(), 0, "error setting twolame sample rate"); return false; } if (0 > twolame_init_params(encoder->options)) { g_set_error(error, twolame_encoder_quark(), 0, "error initializing twolame params"); return false; } return true; }
/** \fn initialize */ bool AUDMEncoder_Twolame::initialize(void) { int ret; TWOLAME_MPEG_mode mmode; uint32_t frequence; int channels=wavheader.channels; _twolameOptions = twolame_init(); if (_twolameOptions == NULL) return 0; if(channels>2) { printf("[TwoLame]Too many channels\n"); return 0; } wavheader.byterate=(_config.bitrate*1000)>>3; _chunk = 1152*channels; printf("[TwoLame]Incoming :fq : %"PRIu32", channel : %"PRIu32" bitrate: %"PRIu32" \n", wavheader.frequency,channels,_config.bitrate); twolame_set_in_samplerate(OPTIONS, wavheader.frequency); twolame_set_out_samplerate (OPTIONS, wavheader.frequency); twolame_set_num_channels(OPTIONS, channels); if(channels==1) mmode=TWOLAME_MONO; else mmode = TWOLAME_STEREO; twolame_set_mode(OPTIONS,mmode); twolame_set_error_protection(OPTIONS,TRUE); //toolame_setPadding (options,TRUE); twolame_set_bitrate (OPTIONS,_config.bitrate); twolame_set_verbosity(OPTIONS, 2); if(twolame_init_params(OPTIONS)) { printf("[TwoLame]Twolame init failed\n"); return false; } printf("[TwoLame]Libtoolame successfully initialized\n"); return true; }
static gboolean gst_two_lame_get_default_settings (void) { twolame_options *glopts = NULL; glopts = twolame_init (); if (glopts == NULL) { GST_ERROR ("Couldn't initialize TwoLAME"); return FALSE; } twolame_set_num_channels (glopts, 2); twolame_set_in_samplerate (glopts, 44100); if (twolame_init_params (glopts) != 0) { GST_ERROR ("Couldn't set default parameters"); return FALSE; } gst_two_lame_default_settings.mode = TWOLAME_JOINT_STEREO; /* twolame_get_mode (glopts); */ gst_two_lame_default_settings.psymodel = twolame_get_psymodel (glopts); gst_two_lame_default_settings.bitrate = twolame_get_bitrate (glopts); gst_two_lame_default_settings.padding = twolame_get_padding (glopts); gst_two_lame_default_settings.energy_level_extension = twolame_get_energy_levels (glopts); gst_two_lame_default_settings.emphasis = twolame_get_emphasis (glopts); gst_two_lame_default_settings.error_protection = twolame_get_error_protection (glopts); gst_two_lame_default_settings.copyright = twolame_get_copyright (glopts); gst_two_lame_default_settings.original = twolame_get_original (glopts); gst_two_lame_default_settings.vbr = twolame_get_VBR (glopts); gst_two_lame_default_settings.vbr_level = twolame_get_VBR_level (glopts); gst_two_lame_default_settings.ath_level = twolame_get_ATH_level (glopts); gst_two_lame_default_settings.vbr_max_bitrate = twolame_get_VBR_max_bitrate_kbps (glopts); gst_two_lame_default_settings.quick_mode = twolame_get_quick_mode (glopts); gst_two_lame_default_settings.quick_mode_count = twolame_get_quick_count (glopts); twolame_close (&glopts); return TRUE; }
int ExportMP2::Export(AudacityProject *project, int channels, const wxString &fName, bool selectionOnly, double t0, double t1, MixerSpec *mixerSpec, const Tags *metadata, int WXUNUSED(subformat)) { bool stereo = (channels == 2); long bitrate = gPrefs->Read(wxT("/FileFormats/MP2Bitrate"), 160); double rate = project->GetRate(); const TrackList *tracks = project->GetTracks(); wxLogNull logNo; /* temporarily disable wxWidgets error messages */ twolame_options *encodeOptions; encodeOptions = twolame_init(); twolame_set_in_samplerate(encodeOptions, (int)(rate + 0.5)); twolame_set_out_samplerate(encodeOptions, (int)(rate + 0.5)); twolame_set_bitrate(encodeOptions, bitrate); twolame_set_num_channels(encodeOptions, stereo ? 2 : 1); if (twolame_init_params(encodeOptions) != 0) { wxMessageBox(_("Cannot export MP2 with this sample rate and bit rate"), _("Error"), wxICON_STOP); twolame_close(&encodeOptions); return false; } // Put ID3 tags at beginning of file if (metadata == NULL) metadata = project->GetTags(); FileIO outFile(fName, FileIO::Output); if (!outFile.IsOpened()) { wxMessageBox(_("Unable to open target file for writing")); twolame_close(&encodeOptions); return false; } char *id3buffer = NULL; int id3len; bool endOfFile; id3len = AddTags(project, &id3buffer, &endOfFile, metadata); if (id3len && !endOfFile) outFile.Write(id3buffer, id3len); // Values taken from the twolame simple encoder sample const int pcmBufferSize = 9216 / 2; // number of samples const int mp2BufferSize = 16384; // bytes // We allocate a buffer which is twice as big as the // input buffer, which should always be enough. // We have to multiply by 4 because one sample is 2 bytes wide! unsigned char* mp2Buffer = new unsigned char[mp2BufferSize]; const WaveTrackConstArray waveTracks = tracks->GetWaveTrackConstArray(selectionOnly, false); int updateResult = eProgressSuccess; { auto mixer = CreateMixer(waveTracks, tracks->GetTimeTrack(), t0, t1, stereo ? 2 : 1, pcmBufferSize, true, rate, int16Sample, true, mixerSpec); ProgressDialog progress(wxFileName(fName).GetName(), selectionOnly ? wxString::Format(_("Exporting selected audio at %ld kbps"), bitrate) : wxString::Format(_("Exporting entire file at %ld kbps"), bitrate)); while (updateResult == eProgressSuccess) { sampleCount pcmNumSamples = mixer->Process(pcmBufferSize); if (pcmNumSamples == 0) break; short *pcmBuffer = (short *)mixer->GetBuffer(); int mp2BufferNumBytes = twolame_encode_buffer_interleaved( encodeOptions, pcmBuffer, pcmNumSamples, mp2Buffer, mp2BufferSize); outFile.Write(mp2Buffer, mp2BufferNumBytes); updateResult = progress.Update(mixer->MixGetCurrentTime() - t0, t1 - t0); } } int mp2BufferNumBytes = twolame_encode_flush( encodeOptions, mp2Buffer, mp2BufferSize); if (mp2BufferNumBytes > 0) outFile.Write(mp2Buffer, mp2BufferNumBytes); twolame_close(&encodeOptions); delete[] mp2Buffer; /* Write ID3 tag if it was supposed to be at the end of the file */ if (id3len && endOfFile) outFile.Write(id3buffer, id3len); if (id3buffer) { free(id3buffer); } /* Close file */ outFile.Close(); return updateResult; }
/* set up the encoder state */ static gboolean gst_two_lame_setup (GstTwoLame * twolame) { #define CHECK_ERROR(command) G_STMT_START {\ if ((command) < 0) { \ GST_ERROR_OBJECT (twolame, "setup failed: " G_STRINGIFY (command)); \ return FALSE; \ } \ }G_STMT_END int retval; GstCaps *allowed_caps; GST_DEBUG_OBJECT (twolame, "starting setup"); /* check if we're already setup; if we are, we might want to check * if this initialization is compatible with the previous one */ /* FIXME: do this */ if (twolame->setup) { GST_WARNING_OBJECT (twolame, "already setup"); twolame->setup = FALSE; } twolame->glopts = twolame_init (); if (twolame->glopts == NULL) return FALSE; /* copy the parameters over */ twolame_set_in_samplerate (twolame->glopts, twolame->samplerate); /* let twolame choose default samplerate unless outgoing sample rate is fixed */ allowed_caps = gst_pad_get_allowed_caps (twolame->srcpad); if (allowed_caps != NULL) { GstStructure *structure; gint samplerate; structure = gst_caps_get_structure (allowed_caps, 0); if (gst_structure_get_int (structure, "rate", &samplerate)) { GST_DEBUG_OBJECT (twolame, "Setting sample rate to %d as fixed in src caps", samplerate); twolame_set_out_samplerate (twolame->glopts, samplerate); } else { GST_DEBUG_OBJECT (twolame, "Letting twolame choose sample rate"); twolame_set_out_samplerate (twolame->glopts, 0); } gst_caps_unref (allowed_caps); allowed_caps = NULL; } else { GST_DEBUG_OBJECT (twolame, "No peer yet, letting twolame choose sample rate"); twolame_set_out_samplerate (twolame->glopts, 0); } /* force mono encoding if we only have one channel */ if (twolame->num_channels == 1) twolame->mode = 3; /* Fix bitrates and MPEG version */ CHECK_ERROR (twolame_set_num_channels (twolame->glopts, twolame->num_channels)); CHECK_ERROR (twolame_set_mode (twolame->glopts, twolame->mode)); CHECK_ERROR (twolame_set_psymodel (twolame->glopts, twolame->psymodel)); CHECK_AND_FIXUP_BITRATE (twolame, "bitrate", twolame->bitrate); CHECK_ERROR (twolame_set_bitrate (twolame->glopts, twolame->bitrate)); CHECK_ERROR (twolame_set_padding (twolame->glopts, twolame->padding)); CHECK_ERROR (twolame_set_energy_levels (twolame->glopts, twolame->energy_level_extension)); CHECK_ERROR (twolame_set_emphasis (twolame->glopts, twolame->emphasis)); CHECK_ERROR (twolame_set_error_protection (twolame->glopts, twolame->error_protection)); CHECK_ERROR (twolame_set_copyright (twolame->glopts, twolame->copyright)); CHECK_ERROR (twolame_set_original (twolame->glopts, twolame->original)); CHECK_ERROR (twolame_set_VBR (twolame->glopts, twolame->vbr)); CHECK_ERROR (twolame_set_VBR_level (twolame->glopts, twolame->vbr_level)); CHECK_ERROR (twolame_set_ATH_level (twolame->glopts, twolame->ath_level)); CHECK_AND_FIXUP_BITRATE (twolame, "vbr-max-bitrate", twolame->vbr_max_bitrate); CHECK_ERROR (twolame_set_VBR_max_bitrate_kbps (twolame->glopts, twolame->vbr_max_bitrate)); CHECK_ERROR (twolame_set_quick_mode (twolame->glopts, twolame->quick_mode)); CHECK_ERROR (twolame_set_quick_count (twolame->glopts, twolame->quick_mode_count)); /* initialize the twolame encoder */ if ((retval = twolame_init_params (twolame->glopts)) >= 0) { twolame->setup = TRUE; /* FIXME: it would be nice to print out the mode here */ GST_INFO ("twolame encoder setup (%d kbit/s, %d Hz, %d channels)", twolame->bitrate, twolame->samplerate, twolame->num_channels); } else { GST_ERROR_OBJECT (twolame, "twolame_init_params returned %d", retval); } GST_DEBUG_OBJECT (twolame, "done with setup"); return twolame->setup; #undef CHECK_ERROR }
int main(int argc, char **argv) { twolame_options *encopts = NULL; SNDFILE *inputfile = NULL; FILE *outputfile = NULL; short int *pcmaudio = NULL; int samples_read = 0; unsigned int frame_count = 0; unsigned char *mp2buffer = NULL; int mp2fill_size = 0; int audioReadSize = 0; // Allocate memory for the PCM audio data if ((pcmaudio = (short int *) calloc(AUDIOBUFSIZE, sizeof(short int))) == NULL) { fprintf(stderr, "Error: pcmaudio memory allocation failed\n"); exit(ERR_MEM_ALLOC); } // Allocate memory for the encoded MP2 audio data if ((mp2buffer = (unsigned char *) calloc(MP2BUFSIZE, sizeof(unsigned char))) == NULL) { fprintf(stderr, "Error: mp2buffer memory allocation failed\n"); exit(ERR_MEM_ALLOC); } // Initialise Encoder Options Structure encopts = twolame_init(); if (encopts == NULL) { fprintf(stderr, "Error: initializing libtwolame encoder failed.\n"); exit(ERR_MEM_ALLOC); } // Get options and parameters from the command line parse_args(argc, argv, encopts); // Open the input file inputfile = open_input_file( inputfilename ); twolame_set_num_channels( encopts, sfinfo.channels ); twolame_set_in_samplerate( encopts, sfinfo.samplerate ); // Open the output file outputfile = open_output_file( outputfilename ); // display file settings print_file_config( inputfile, twolame_get_verbosity(encopts) ); // initialise twolame with this set of options if (twolame_init_params( encopts ) != 0) { fprintf(stderr, "Error: configuring libtwolame encoder failed.\n"); exit(ERR_INVALID_PARAM); } // display encoder settings twolame_print_config( encopts ); // Only encode a single frame of mpeg audio ? if (single_frame_mode) audioReadSize = 1152; else audioReadSize = AUDIOBUFSIZE; // Now do the reading/encoding/writing while ((samples_read = sf_read_short( inputfile, pcmaudio, audioReadSize )) > 0) { int bytes_out = 0; // Force byte swapping if requested if (byteswap) { int i; for (i = 0; i<samples_read; i++) { short tmp = pcmaudio[i]; char *src = (char*)&tmp; char *dst = (char*)&pcmaudio[i]; dst[0] = src[1]; dst[1] = src[0]; } } // Calculate the number of samples we have (per channel) samples_read /= sfinfo.channels; // Do swapping of left and right channels if requested if (channelswap && sfinfo.channels == 2) { int i; for(i=0; i<samples_read; i++) { short tmp = pcmaudio[(2*i)]; pcmaudio[(2*i)] = pcmaudio[(2*i)+1]; pcmaudio[(2*i)+1] = tmp; } } // Encode the audio to MP2 mp2fill_size = twolame_encode_buffer_interleaved( encopts, pcmaudio, samples_read, mp2buffer, MP2BUFSIZE); // Stop if we don't have any bytes (probably don't have enough audio for a full frame of mpeg audio) if (mp2fill_size==0) break; if (mp2fill_size<0) { fprintf(stderr,"error while encoding audio: %d\n", mp2fill_size); exit(ERR_WRITING_OUTPUT); } // Write the encoded audio out bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile); if (bytes_out<=0) { perror("error while writing to output file"); exit(ERR_WRITING_OUTPUT); } // Only single frame ? if (single_frame_mode) break; // Display Progress frame_count += (samples_read / 1152); if (twolame_get_verbosity(encopts)>0) { fprintf(stderr, "[%04i", frame_count); //fprintf(stderr, "/%04i", (int)(sfinfo.frames / sfinfo.channels / 1152)); fprintf(stderr, "]\r"); fflush(stderr); } } // // flush any remaining audio. (don't send any new audio data) There // should only ever be a max of 1 frame on a flush. There may be zero // frames if the audio data was an exact multiple of 1152 // mp2fill_size = twolame_encode_flush( encopts, mp2buffer, MP2BUFSIZE); if (mp2fill_size>0) { int bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile); if (bytes_out<=0) { perror("error while writing to output file"); exit(ERR_WRITING_OUTPUT); } } if (twolame_get_verbosity(encopts)>1) { fprintf(stderr, "\nEncoding Finished.\n"); } // Close input and output files sf_close( inputfile ); fclose( outputfile ); // Close the libtwolame encoder twolame_close(&encopts); // Free up memory free(pcmaudio); free(mp2buffer); return (ERR_NO_ERROR); }
static int OpenEncoder( vlc_object_t *p_this ) { encoder_t *p_enc = (encoder_t *)p_this; encoder_sys_t *p_sys; int i_frequency; if( p_enc->fmt_out.i_codec != VLC_CODEC_MP2 && p_enc->fmt_out.i_codec != VLC_CODEC_MPGA && p_enc->fmt_out.i_codec != VLC_FOURCC( 'm', 'p', '2', 'a' ) && !p_enc->obj.force ) { return VLC_EGENERIC; } if( p_enc->fmt_in.audio.i_channels > 2 ) { msg_Err( p_enc, "doesn't support > 2 channels" ); return VLC_EGENERIC; } for ( i_frequency = 0; i_frequency < 6; i_frequency++ ) { if ( p_enc->fmt_out.audio.i_rate == mpa_freq_tab[i_frequency] ) break; } if ( i_frequency == 6 ) { msg_Err( p_enc, "MPEG audio doesn't support frequency=%d", p_enc->fmt_out.audio.i_rate ); return VLC_EGENERIC; } /* Allocate the memory needed to store the decoder's structure */ if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL ) return VLC_ENOMEM; p_enc->p_sys = p_sys; p_enc->fmt_in.i_codec = VLC_CODEC_S16N; p_enc->fmt_out.i_cat = AUDIO_ES; p_enc->fmt_out.i_codec = VLC_CODEC_MPGA; config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg ); p_sys->p_twolame = twolame_init(); /* Set options */ twolame_set_in_samplerate( p_sys->p_twolame, p_enc->fmt_out.audio.i_rate ); twolame_set_out_samplerate( p_sys->p_twolame, p_enc->fmt_out.audio.i_rate ); if( var_GetBool( p_enc, ENC_CFG_PREFIX "vbr" ) ) { float f_quality = var_GetFloat( p_enc, ENC_CFG_PREFIX "quality" ); if ( f_quality > 50.f ) f_quality = 50.f; if ( f_quality < 0.f ) f_quality = 0.f; twolame_set_VBR( p_sys->p_twolame, 1 ); twolame_set_VBR_q( p_sys->p_twolame, f_quality ); } else { int i; for ( i = 1; i < 14; i++ ) { if ( p_enc->fmt_out.i_bitrate / 1000 <= mpa_bitrate_tab[i_frequency / 3][i] ) break; } if ( p_enc->fmt_out.i_bitrate / 1000 != mpa_bitrate_tab[i_frequency / 3][i] ) { msg_Warn( p_enc, "MPEG audio doesn't support bitrate=%d, using %d", p_enc->fmt_out.i_bitrate, mpa_bitrate_tab[i_frequency / 3][i] * 1000 ); p_enc->fmt_out.i_bitrate = mpa_bitrate_tab[i_frequency / 3][i] * 1000; } twolame_set_bitrate( p_sys->p_twolame, p_enc->fmt_out.i_bitrate / 1000 ); } if ( p_enc->fmt_in.audio.i_channels == 1 ) { twolame_set_num_channels( p_sys->p_twolame, 1 ); twolame_set_mode( p_sys->p_twolame, TWOLAME_MONO ); } else { twolame_set_num_channels( p_sys->p_twolame, 2 ); switch( var_GetInteger( p_enc, ENC_CFG_PREFIX "mode" ) ) { case 1: twolame_set_mode( p_sys->p_twolame, TWOLAME_DUAL_CHANNEL ); break; case 2: twolame_set_mode( p_sys->p_twolame, TWOLAME_JOINT_STEREO ); break; case 0: default: twolame_set_mode( p_sys->p_twolame, TWOLAME_STEREO ); break; } } twolame_set_psymodel( p_sys->p_twolame, var_GetInteger( p_enc, ENC_CFG_PREFIX "psy" ) ); if ( twolame_init_params( p_sys->p_twolame ) ) { msg_Err( p_enc, "twolame initialization failed" ); return -VLC_EGENERIC; } p_enc->pf_encode_audio = Encode; p_sys->i_nb_samples = 0; return VLC_SUCCESS; }
bool MpegL2Codec::startCodec() { #ifdef HAVE_TWOLAME // // Load Library // if((twolame_handle=dlopen("libtwolame.so.0",RTLD_LAZY))==NULL) { Log(LOG_ERR,"unsupported audio format (library not found)"); return false; } *(void **)(&twolame_init)=dlsym(twolame_handle,"twolame_init"); *(void **)(&twolame_set_mode)=dlsym(twolame_handle,"twolame_set_mode"); *(void **)(&twolame_set_num_channels)= dlsym(twolame_handle,"twolame_set_num_channels"); *(void **)(&twolame_set_in_samplerate)= dlsym(twolame_handle,"twolame_set_in_samplerate"); *(void **)(&twolame_set_out_samplerate)= dlsym(twolame_handle,"twolame_set_out_samplerate"); *(void **)(&twolame_set_bitrate)= dlsym(twolame_handle,"twolame_set_bitrate"); *(void **)(&twolame_init_params)= dlsym(twolame_handle,"twolame_init_params"); *(void **)(&twolame_close)=dlsym(twolame_handle,"twolame_close"); *(void **)(&twolame_encode_buffer_interleaved)= dlsym(twolame_handle,"twolame_encode_buffer_interleaved"); *(void **)(&twolame_encode_buffer_float32_interleaved)= dlsym(twolame_handle,"twolame_encode_buffer_float32_interleaved"); *(void **)(&twolame_encode_flush)= dlsym(twolame_handle,"twolame_encode_flush"); *(void **)(&twolame_set_energy_levels)= dlsym(twolame_handle,"twolame_set_energy_levels"); *(void **)(&twolame_set_VBR)=dlsym(twolame_handle,"twolame_set_VBR"); *(void **)(&twolame_set_VBR_level)= dlsym(twolame_handle,"twolame_set_VBR_level"); // // Initialize Encoder Instance // TWOLAME_MPEG_mode mpeg_mode=TWOLAME_STEREO; switch(channels()) { case 1: mpeg_mode=TWOLAME_MONO; break; case 2: mpeg_mode=TWOLAME_STEREO; break; } if((twolame_lameopts=twolame_init())==NULL) { Log(LOG_ERR,"unable to initialize MP2 encoder"); return false; } twolame_set_mode(twolame_lameopts,mpeg_mode); twolame_set_num_channels(twolame_lameopts,channels()); twolame_set_in_samplerate(twolame_lameopts,streamSamplerate()); twolame_set_out_samplerate(twolame_lameopts,streamSamplerate()); if(bitrate()==0) { twolame_set_VBR(twolame_lameopts,TRUE); twolame_set_VBR_level(twolame_lameopts,(int)(20.0*quality()-10.0)); } else { twolame_set_bitrate(twolame_lameopts,bitrate()); } twolame_set_energy_levels(twolame_lameopts,1); if(twolame_init_params(twolame_lameopts)!=0) { Log(LOG_ERR,"unable to start MP2 encoder"); return false; } return true; #else Log(LOG_ERR,"unsupported audio format (no build support)"); return false; #endif // HAVE_TWOLAME }
//________________________________________________ // 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_Twolame::init(ADM_audioEncoderDescriptor *config) { int ret; TWOLAME_MPEG_mode mmode; uint32_t frequence; TWOLAME_encoderParam *lameConf=(TWOLAME_encoderParam *)config->param; ADM_assert(config->paramSize==sizeof(TWOLAME_encoderParam)); _twolameOptions = twolame_init(); if (_twolameOptions == NULL) return 0; if(_wavheader->channels>2) { printf("[TwoLame]Too many channels\n"); return 0; } _wavheader->byterate=(config->bitrate*1000)>>3; _chunk = 1152*_wavheader->channels; printf("[TwoLame]Incoming :fq : %lu, channel : %lu bitrate: %lu \n", _wavheader->frequency,_wavheader->channels,config->bitrate); twolame_set_in_samplerate(OPTIONS, _wavheader->frequency); twolame_set_out_samplerate (OPTIONS, _wavheader->frequency); twolame_set_num_channels(OPTIONS, _wavheader->channels); if(_wavheader->channels==1) mmode=TWOLAME_MONO; else switch (lameConf->mode) { case ADM_STEREO: mmode = TWOLAME_STEREO; break; case ADM_JSTEREO: mmode = TWOLAME_JOINT_STEREO; break; case ADM_MONO: mmode=TWOLAME_MONO; break; default: printf("\n **** unknown mode, going stereo ***\n"); mmode = TWOLAME_STEREO; break; } twolame_set_mode(OPTIONS,mmode); twolame_set_error_protection(OPTIONS,TRUE); //toolame_setPadding (options,TRUE); twolame_set_bitrate (OPTIONS,config->bitrate); twolame_set_verbosity(OPTIONS, 2); if(twolame_init_params(OPTIONS)) { printf("[TwoLame]Twolame init failed\n"); return 0; } printf("[TwoLame]Libtoolame successfully initialized\n"); return 1; }
int main(int argc, char **argv) { twolame_options *encodeOptions; char *inputfilename = argv[1]; char *outputfilename = argv[2]; FILE *outfile, *fpSrc = NULL; short int *pcmaudio; unsigned char *mp2buffer; int num_samples = 0; int mp2fill_size = 0; int frames = 0; wave_info_t *wave_info = NULL; int nReadSize = 0; if (argc != 3) usage(); /* Allocate some space for the PCM audio data */ if ((pcmaudio = (short *) calloc(AUDIOBUFSIZE, sizeof(short))) == NULL) { fprintf(stderr, "pcmaudio alloc failed\n"); exit(99); } /* Allocate some space for the encoded MP2 audio data */ if ((mp2buffer = (unsigned char *) calloc(MP2BUFSIZE, sizeof(unsigned char))) == NULL) { fprintf(stderr, "mp2buffer alloc failed\n"); exit(99); } /* grab a set of default encode options */ encodeOptions = twolame_init(); printf("Using libtwolame version %s.\n", get_twolame_version()); /* Open the wave file */ if ((wave_info = wave_init(inputfilename)) == NULL) { fprintf(stderr, "Not a recognised WAV file.\n"); exit(99); } // Use sound file to over-ride preferences for // mono/stereo and sampling-frequency twolame_set_num_channels(encodeOptions, wave_info->channels); if (wave_info->channels == 1) { twolame_set_mode(encodeOptions, TWOLAME_MONO); } else { twolame_set_mode(encodeOptions, TWOLAME_STEREO); } /* Set the input and output sample rate to the same */ twolame_set_in_samplerate(encodeOptions, wave_info->samplerate); twolame_set_out_samplerate(encodeOptions, wave_info->samplerate); /* Set the bitrate to 192 kbps */ twolame_set_bitrate(encodeOptions, 64); /* initialise twolame with this set of options */ if (twolame_init_params(encodeOptions) != 0) { fprintf(stderr, "Error: configuring libtwolame encoder failed.\n"); exit(99); } /* Open the output file for the encoded MP2 data */ if ((outfile = fopen(outputfilename, "wb")) == 0) { fprintf(stderr, "error opening output file %s\n", outputfilename); exit(99); } // Read num_samples of audio data *per channel* from the input file //while ((num_samples = wave_get_samples(wave_info, pcmaudio, AUDIOBUFSIZE/2)) != 0) { fpSrc = fopen( "a2002011001-e02.wav", "rb" ); while(1) { num_samples = fread( pcmaudio, sizeof( char ), AUDIOBUFSIZE/2, fpSrc ); // Encode the audio!2024*4 if( num_samples != AUDIOBUFSIZE/2 ) break; num_samples /= 2; mp2fill_size = twolame_encode_buffer_interleaved(encodeOptions, pcmaudio, num_samples/2, mp2buffer, MP2BUFSIZE); // Write the MPEG bitstream to the file fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outfile); // Display the number of MPEG audio frames we have encoded frames += (num_samples / TWOLAME_SAMPLES_PER_FRAME); printf("[%04i]\r", frames); fflush(stdout); } /* flush any remaining audio. (don't send any new audio data) There should only ever be a max of 1 frame on a flush. There may be zero frames if the audio data was an exact multiple of 1152 */ mp2fill_size = twolame_encode_flush(encodeOptions, mp2buffer, MP2BUFSIZE); fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outfile); twolame_close(&encodeOptions); free(pcmaudio); printf("\nFinished nicely.\n"); return (0); }
int mpae_init_twolame(audio_encoder_t *encoder) { int mode; mpae_twolame_ctx *ctx = NULL; if(encoder->params.channels == 1) { mp_msg(MSGT_MENCODER, MSGL_INFO, "ae_twolame, 1 audio channel, forcing mono mode\n"); mode = TWOLAME_MONO; } else if(encoder->params.channels == 2) { if(! strcasecmp(param_mode, "dual")) mode = TWOLAME_DUAL_CHANNEL; else if(! strcasecmp(param_mode, "jstereo")) mode = TWOLAME_JOINT_STEREO; else if(! strcasecmp(param_mode, "stereo")) mode = TWOLAME_STEREO; else { mp_msg(MSGT_MENCODER, MSGL_ERR, "ae_twolame, unknown mode %s, exiting\n", param_mode); } } else mp_msg(MSGT_MENCODER, MSGL_ERR, "ae_twolame, Twolame can't encode > 2 channels, exiting\n"); ctx = (mpae_twolame_ctx *) calloc(1, sizeof(mpae_twolame_ctx)); if(ctx == NULL) { mp_msg(MSGT_MENCODER, MSGL_ERR, "ae_twolame, couldn't alloc a %d bytes context, exiting\n", sizeof(mpae_twolame_ctx)); return 0; } ctx->twolame_ctx = twolame_init(); if(ctx->twolame_ctx == NULL) { mp_msg(MSGT_MENCODER, MSGL_ERR, "ae_twolame, couldn't initial parameters from libtwolame, exiting\n"); free(ctx); return 0; } ctx->vbr = 0; if(twolame_set_num_channels(ctx->twolame_ctx, encoder->params.channels) != 0) return 0; if(twolame_set_mode(ctx->twolame_ctx, mode) != 0) return 0; if(twolame_set_in_samplerate(ctx->twolame_ctx, encoder->params.sample_rate) != 0) return 0; if(twolame_set_out_samplerate(ctx->twolame_ctx, encoder->params.sample_rate) != 0) return 0; if(encoder->params.sample_rate < 32000) twolame_set_version(ctx->twolame_ctx, TWOLAME_MPEG2); else twolame_set_version(ctx->twolame_ctx, TWOLAME_MPEG1); if(twolame_set_psymodel(ctx->twolame_ctx, param_psy) != 0) return 0; if(twolame_set_bitrate(ctx->twolame_ctx, param_bitrate) != 0) return 0; if(param_errprot) if(twolame_set_error_protection(ctx->twolame_ctx, TRUE) != 0) return 0; if(param_vbr != 0) { if(twolame_set_VBR(ctx->twolame_ctx, TRUE) != 0) return 0; if(twolame_set_VBR_q(ctx->twolame_ctx, param_vbr) != 0) return 0; if(twolame_set_padding(ctx->twolame_ctx, FALSE) != 0) return 0; if(param_maxvbr) { if(twolame_set_VBR_max_bitrate_kbps(ctx->twolame_ctx, param_maxvbr) != 0) return 0; } ctx->vbr = 1; } if(twolame_set_verbosity(ctx->twolame_ctx, param_debug) != 0) return 0; if(twolame_init_params(ctx->twolame_ctx) != 0) return 0; encoder->params.bitrate = param_bitrate * 1000; encoder->params.samples_per_frame = 1152; encoder->priv = ctx; encoder->decode_buffer_size = 1152 * 2 * encoder->params.channels; encoder->bind = bind_twolame; encoder->get_frame_size = get_frame_size; encoder->encode = encode_twolame; encoder->close = close_twolame; return 1; }
int main(int argc, char **argv) { twolame_options *encopts = NULL; audioin_t *inputfile = NULL; FILE *outputfile = NULL; short int *pcmaudio = NULL; unsigned int frame_count = 0; unsigned int total_frames = 0; unsigned int frame_len = 0; unsigned int total_bytes = 0; unsigned char *mp2buffer = NULL; int samples_read = 0; int mp2fill_size = 0; int audioReadSize = 0; // Allocate memory for the PCM audio data if ((pcmaudio = (short int *) calloc(AUDIO_BUF_SIZE, sizeof(short int))) == NULL) { fprintf(stderr, "Error: pcmaudio memory allocation failed\n"); exit(ERR_MEM_ALLOC); } // Allocate memory for the encoded MP2 audio data if ((mp2buffer = (unsigned char *) calloc(MP2_BUF_SIZE, sizeof(unsigned char))) == NULL) { fprintf(stderr, "Error: mp2buffer memory allocation failed\n"); exit(ERR_MEM_ALLOC); } // Initialise Encoder Options Structure encopts = twolame_init(); if (encopts == NULL) { fprintf(stderr, "Error: initializing libtwolame encoder failed.\n"); exit(ERR_MEM_ALLOC); } // Get options and parameters from the command line parse_args(argc, argv, encopts); // Display the filenames print_filenames(twolame_get_verbosity(encopts)); // Open the input file if (use_raw) { // use raw input handler inputfile = open_audioin_raw(inputfilename, &sfinfo, sample_size); } else { // use libsndfile inputfile = open_audioin_sndfile(inputfilename, &sfinfo); } // Display input information if (twolame_get_verbosity(encopts) > 1) { inputfile->print_info(inputfile); } // Use information from input file to configure libtwolame twolame_set_num_channels(encopts, sfinfo.channels); twolame_set_in_samplerate(encopts, sfinfo.samplerate); // Open the output file outputfile = open_output_file(outputfilename); // initialise twolame with this set of options if (twolame_init_params(encopts) != 0) { fprintf(stderr, "Error: configuring libtwolame encoder failed.\n"); exit(ERR_INVALID_PARAM); } // display encoder settings twolame_print_config(encopts); // Only encode a single frame of mpeg audio ? if (single_frame_mode) audioReadSize = TWOLAME_SAMPLES_PER_FRAME; else audioReadSize = AUDIO_BUF_SIZE; // Calculate the size and number of frames we are going to encode frame_len = twolame_get_framelength(encopts); if (sfinfo.frames) total_frames = sfinfo.frames / TWOLAME_SAMPLES_PER_FRAME; // Now do the reading/encoding/writing while ((samples_read = inputfile->read(inputfile, pcmaudio, audioReadSize)) > 0) { int bytes_out = 0; // Force byte swapping if requested if (byteswap) { int i; for (i = 0; i < samples_read; i++) { short tmp = pcmaudio[i]; char *src = (char *) &tmp; char *dst = (char *) &pcmaudio[i]; dst[0] = src[1]; dst[1] = src[0]; } } // Calculate the number of samples we have (per channel) samples_read /= sfinfo.channels; // Do swapping of left and right channels if requested if (channelswap && sfinfo.channels == 2) { int i; for (i = 0; i < samples_read; i++) { short tmp = pcmaudio[(2 * i)]; pcmaudio[(2 * i)] = pcmaudio[(2 * i) + 1]; pcmaudio[(2 * i) + 1] = tmp; } } // Encode the audio to MP2 mp2fill_size = twolame_encode_buffer_interleaved(encopts, pcmaudio, samples_read, mp2buffer, MP2_BUF_SIZE); // Stop if we don't have any bytes (probably don't have enough audio for a full frame of // mpeg audio) if (mp2fill_size == 0) break; if (mp2fill_size < 0) { fprintf(stderr, "error while encoding audio: %d\n", mp2fill_size); exit(ERR_ENCODING); } // Check that a whole number of frame was written // if (mp2fill_size % frame_len != 0) { // fprintf(stderr,"error while encoding audio: non-whole number of frames written\n"); // exit(ERR_ENCODING); // } // Write the encoded audio out bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile); if (bytes_out != mp2fill_size) { perror("error while writing to output file"); exit(ERR_WRITING_OUTPUT); } total_bytes += bytes_out; // Only single frame ? if (single_frame_mode) break; // Display Progress frame_count += (mp2fill_size / frame_len); if (twolame_get_verbosity(encopts) > 0) { fprintf(stderr, "\rEncoding frame: %i", frame_count); if (total_frames) { fprintf(stderr, "/%i (%i%%)", total_frames, (frame_count * 100) / total_frames); } fflush(stderr); } } // Was there an error reading the audio? if (inputfile->error_str(inputfile)) { fprintf(stderr, "Error reading from input file: %s\n", inputfile->error_str(inputfile)); } // // flush any remaining audio. (don't send any new audio data) There // should only ever be a max of 1 frame on a flush. There may be zero // frames if the audio data was an exact multiple of 1152 // mp2fill_size = twolame_encode_flush(encopts, mp2buffer, MP2_BUF_SIZE); if (mp2fill_size > 0) { int bytes_out = fwrite(mp2buffer, sizeof(unsigned char), mp2fill_size, outputfile); frame_count++; if (bytes_out <= 0) { perror("error while writing to output file"); exit(ERR_WRITING_OUTPUT); } total_bytes += bytes_out; } if (twolame_get_verbosity(encopts) > 1) { char *filesize = format_filesize_string(total_bytes); fprintf(stderr, "\nEncoding Finished.\n"); fprintf(stderr, "Total bytes written: %s.\n", filesize); free(filesize); } // Close input and output streams inputfile->close(inputfile); fclose(outputfile); // Close the libtwolame encoder twolame_close(&encopts); // Free up memory free(pcmaudio); free(mp2buffer); return (ERR_NO_ERROR); }