13 #define DEFAULT_MP3_RATE 44100
17 #ifdef CSL_MP3_AS_FLOATS
19 static double samp_scale = 0.01 / (double) (1L << MAD_F_FRACBITS);
23 return (
float) (fsample / samp_scale);
26 #define MP3_SAMP_TYPE float
27 #define MP3_WRITE sf_writef_float
30 #else // CSL_MP3_AS_INTS
32 #define MP3_SAMP_TYPE short
42 sample += (1L << (MAD_F_FRACBITS - 16));
43 if (sample >= MAD_F_ONE)
44 sample = MAD_F_ONE - 1;
45 else if (sample < -MAD_F_ONE)
50 #define MP3_WRITE sf_writef_short
55 #define scale_MP3F(v) (((float) scale_MP3(v)) / 32768.0f)
121 unsigned nsamples = num_samples;
125 if ((tot + nsamples) >= maxFrames) {
127 nsamples = maxFrames - tot;
141 int * left_ch, * right_ch;
153 unsigned nsamples = num_samples;
157 if ((tot + nsamples) >= maxFrames) {
160 nsamples = (tot > maxFrames) ? 0 : maxFrames - tot;
173 sample * outL, * outR, * inP;
186 if ((tot + nsamples) >= maxFrames) {
188 nsamples = maxFrames - tot;
205 for (BufferVector::iterator it =
mBuffers.begin(); it !=
mBuffers.end(); it++)
206 totS += (*it)->mNumFrames;
229 for (BufferVector::iterator it =
mBuffers.begin(); it !=
mBuffers.end(); it++) {
251 for (BufferVector::iterator it =
mBuffers.begin(); it !=
mBuffers.end(); it++)
257 throw IOError(
"Decoded files cannot be written");
261 throw IOError(
"Decoded files cannot be written");
285 #ifdef WRITE_MP3_TO_FILE
287 static SNDFILE * sfOutput = NULL;
297 static enum mad_flow
m3_input(
void *
data,
struct mad_stream * stream) {
300 return MAD_FLOW_STOP;
301 mad_stream_buffer(stream, buffer->
start, buffer->
length);
303 return MAD_FLOW_CONTINUE;
308 static enum mad_flow
m3_output(
void *
data,
struct mad_header
const * header,
struct mad_pcm * pcm) {
309 unsigned int nchannels, nsamples;
310 mad_fixed_t
const *left_ch, *right_ch;
311 bool continueDecoding =
true;
313 nchannels = pcm->channels;
314 nsamples = pcm->length;
315 left_ch = pcm->samples[0];
316 right_ch = pcm->samples[1];
318 #ifdef WRITE_MP3_TO_FILE
325 MP3_WRITE(sfOutput, xlate_buffer, pcm->length);
327 #else // else write to buffer
334 continueDecoding = mp3File->
writeBuffer((
int *) left_ch, (
int *) right_ch, nsamples);
337 return continueDecoding ? MAD_FLOW_CONTINUE : MAD_FLOW_STOP;
345 static enum mad_flow
m3_error(
void *
data,
struct mad_stream *stream,
struct mad_frame *frame) {
350 return MAD_FLOW_CONTINUE;
355 static enum mad_flow
m3_header(
void *
data,
struct mad_header
const *header) {
359 mp3File->
mMP3Rate = header->samplerate;
361 return MAD_FLOW_CONTINUE;
379 inFile = open(
mPath.c_str(), O_RDONLY);
380 if (fstat(inFile, &stat) == -1 || stat.st_size == 0)
384 void * mapped_data = mmap(0, stat.st_size, PROT_READ, MAP_SHARED, inFile, 0);
386 #ifdef WRITE_MP3_TO_FILE
389 MP3_TEMP_NAME(
mPath.c_str(), mTempPath, mTempDir)
391 AIFF_TEMP_NAME(
mPath.c_str(), mTempPath)
393 mTempFile =
new LSoundFile(mTempPath, -1, -1,
false);
398 struct mad_decoder decoder;
400 vbf.
start = (
unsigned char const *) mapped_data;
401 vbf.
length = stat.st_size;
410 #ifdef WRITE_MP3_TO_FILE // set up the statics
411 sfOutput = mTempFile->sndFile();
415 mad_decoder_init(&decoder, &vbf,
424 result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
426 mad_decoder_finish(&decoder);
428 logMsg(
"MP3 decoder returned %d; temp file %s", result, tempPath);
430 munmap(mapped_data, stat.st_size);
432 #ifdef WRITE_MP3_TO_FILE
435 #else // handle MP3 buffer vector
445 mMode = kSoundFileClosed;
453 mMode = kSoundFileClosed;
491 #ifdef WRITE_MP3_TO_FILE
493 mTempFile->openForRead();
496 mMode = mTempFile->mode();
497 mStart = mTempFile->startFrame();
498 mStop = mTempFile->stopFrame();
508 #ifdef USE_libFAAD // Support AAC/MP4 file reading using libFAAD
514 static int fill_buffer(aac_buffer *b) {
516 if (b->bytes_consumed > 0) {
517 if (b->bytes_into_buffer) {
518 memmove((
void*)b->buffer, (
void*)(b->buffer + b->bytes_consumed),
519 b->bytes_into_buffer*
sizeof(
unsigned char));
522 bread = fread((
void*)(b->buffer + b->bytes_into_buffer), 1,
523 b->bytes_consumed, b->infile);
525 if (bread != b->bytes_consumed)
528 b->bytes_into_buffer += bread;
530 b->bytes_consumed = 0;
531 if (b->bytes_into_buffer > 3) {
532 if (memcmp(b->buffer,
"TAG", 3) == 0)
533 b->bytes_into_buffer = 0;
535 if (b->bytes_into_buffer > 11) {
536 if (memcmp(b->buffer,
"LYRICSBEGIN", 11) == 0)
537 b->bytes_into_buffer = 0;
539 if (b->bytes_into_buffer > 8) {
540 if (memcmp(b->buffer,
"APETAGEX", 8) == 0)
541 b->bytes_into_buffer = 0;
547 static void advance_buffer(aac_buffer *b,
int bytes) {
548 b->file_offset += bytes;
549 b->bytes_consumed = bytes;
550 b->bytes_into_buffer -= bytes;
551 if (b->bytes_into_buffer < 0)
552 b->bytes_into_buffer = 0;
555 static int adts_sample_rates[] =
556 {96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350,0,0,0};
558 static int adts_parse(aac_buffer *b,
int *bitrate,
float *length) {
559 int frames, frame_length;
560 int t_framelength = 0;
562 float frames_per_sec, bytes_per_frame;
565 for (frames = 0; ; frames++) {
567 if (b->bytes_into_buffer > 7) {
569 if (!((b->buffer[0] == 0xFF)&&((b->buffer[1] & 0xF6) == 0xF0)))
572 samplerate = adts_sample_rates[(b->buffer[2]&0x3c)>>2];
573 frame_length = ((((
unsigned int)b->buffer[3] & 0x3)) << 11)
574 | (((
unsigned int)b->buffer[4]) << 3) | (b->buffer[5] >> 5);
575 t_framelength += frame_length;
576 if (frame_length > b->bytes_into_buffer)
579 advance_buffer(b, frame_length);
584 frames_per_sec = (float)samplerate/1024.0f;
586 bytes_per_frame = (float)t_framelength/(
float)(frames*1000);
589 *bitrate = (int)(8. * bytes_per_frame * frames_per_sec + 0.5);
590 if (frames_per_sec != 0)
591 *length = (float)frames/frames_per_sec;
597 uint32_t read_callback(
void *user_data,
void *buffer, uint32_t length) {
598 return fread(buffer, 1, length, (FILE*)user_data);
601 uint32_t seek_callback(
void *user_data, uint64_t position) {
602 return fseek((FILE*)user_data, position, SEEK_SET);
693 static int GetAACTrack(mp4ff_t *infile) {
695 int numTracks = mp4ff_total_tracks(infile);
697 for (i = 0; i < numTracks; i++) {
698 unsigned char * buff = NULL;
699 unsigned int buff_size = 0;
700 mp4AudioSpecificConfig mp4ASC;
701 mp4ff_get_decoder_config(infile, i, &buff, &buff_size);
703 rc = NeAACDecAudioSpecificConfig(buff, buff_size, &mp4ASC);
713 static const unsigned long srates[] =
714 { 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000 };
718 void MP4File::printMP4(mp4ff_t * infile,
int track,
unsigned *song_length) {
719 logMsg(
"%s file info:", mPath.c_str());
720 char *tag = NULL, *item = NULL;
722 const char *ot[6] = {
"NULL",
"MAIN AAC",
"LC AAC",
"SSR AAC",
"LTP AAC",
"HE AAC" };
723 long samples = mp4ff_num_samples(infile, track);
726 if (mp4ASC.sbr_present_flag == 1)
728 seconds = (float)samples * (
float)(f-1.0) / (float)mp4ASC.samplingFrequency;
729 *song_length = (
unsigned) samples * (unsigned) (f - 1);
730 logMsg(
"%s\t%.3f secs, %d ch, %d Hz", ot[(mp4ASC.objectTypeIndex > 5) ? 0 : mp4ASC.objectTypeIndex],
731 seconds, mp4ASC.channelsConfiguration, mp4ASC.samplingFrequency);
732 #define PRINT_MP4_METADATA
733 #ifdef PRINT_MP4_METADATA
734 j = mp4ff_meta_get_num_items(infile);
735 for (k = 0; k < j; k++) {
736 if (mp4ff_meta_get_by_index(infile, k, &item, &tag)) {
737 if (item != NULL && tag != NULL) {
738 logMsg(
"\t\t%s: %s", item, tag);
739 free(item); item = NULL;
740 free(tag); tag = NULL;
750 MP4File::MP4File(
string tpath,
int start,
int stop)
752 mMode = kSoundFileClosed;
756 MP4File::MP4File(
float maxDurInSecs,
string tpath)
758 mMode = kSoundFileClosed;
762 MP4File::~MP4File() {
768 void MP4File::openForRead() throw (
CException) {
769 unsigned char header[8];
783 FILE * hMP4File = fopen(mPath.c_str(),
"rb");
785 logMsg(
"Error opening file (fopen): %s", mPath.c_str());
788 fread(header, 1, 8, hMP4File);
792 if (memcmp(&header[4],
"ftyp", 4) == 0)
796 result = this->decodeMP4file(hMP4File);
798 result = this->decodeAACfile(hMP4File);
805 this->mergeBuffers();
814 Status MP4File::decodeAACfile(FILE * inFile)
throw (CException){
820 unsigned long samplerate;
821 unsigned char tchannels;
826 memset(&aacBuff, 0,
sizeof(aac_buffer));
827 aacBuff.infile = inFile;
828 fseek(aacBuff.infile, 0, SEEK_END);
829 fileread = ftell(aacBuff.infile);
830 fseek(aacBuff.infile, 0, SEEK_SET);
832 if ( ! (aacBuff.buffer = (
unsigned char *) malloc(FAAD_MIN_STREAMSIZE * MAX_CHANNELS))) {
833 logMsg(
"Memory allocation error");
836 memset(aacBuff.buffer, 0, FAAD_MIN_STREAMSIZE * MAX_CHANNELS);
838 bread = fread(aacBuff.buffer, 1, FAAD_MIN_STREAMSIZE*MAX_CHANNELS, aacBuff.infile);
839 aacBuff.bytes_into_buffer = bread;
840 aacBuff.bytes_consumed = 0;
841 aacBuff.file_offset = 0;
843 if (bread != FAAD_MIN_STREAMSIZE*MAX_CHANNELS)
847 if (!memcmp(aacBuff.buffer,
"ID3", 3)) {
849 tagsize = (aacBuff.buffer[6] << 21) | (aacBuff.buffer[7] << 14) |
850 (aacBuff.buffer[8] << 7) | (aacBuff.buffer[9] << 0);
853 advance_buffer(&aacBuff, tagsize);
854 fill_buffer(&aacBuff);
856 hDecoder = NeAACDecOpen();
860 config = NeAACDecGetCurrentConfiguration(hDecoder);
861 config->defObjectType = LC;
862 config->outputFormat = 4;
863 config->downMatrix = 1;
864 config->useOldADTSFormat = 0;
866 NeAACDecSetConfiguration(hDecoder, config);
870 if ((aacBuff.buffer[0] == 0xFF) && ((aacBuff.buffer[1] & 0xF6) == 0xF0)) {
871 adts_parse(&aacBuff, &bitrate, &length);
872 fseek(aacBuff.infile, tagsize, SEEK_SET);
874 bread = fread(aacBuff.buffer, 1, FAAD_MIN_STREAMSIZE*MAX_CHANNELS, aacBuff.infile);
875 if (bread != FAAD_MIN_STREAMSIZE*MAX_CHANNELS)
879 aacBuff.bytes_into_buffer = bread;
880 aacBuff.bytes_consumed = 0;
881 aacBuff.file_offset = tagsize;
883 }
else if (memcmp(aacBuff.buffer,
"ADIF", 4) == 0) {
884 int skip_size = (aacBuff.buffer[4] & 0x80) ? 9 : 0;
885 bitrate = ((
unsigned int)(aacBuff.buffer[4 + skip_size] & 0x0F)<<19) |
886 ((
unsigned int)aacBuff.buffer[5 + skip_size]<<11) |
887 ((
unsigned int)aacBuff.buffer[6 + skip_size]<<3) |
888 ((
unsigned int)aacBuff.buffer[7 + skip_size] & 0xE0);
890 length = (float) fileread;
892 length = ((float)length*8.0f)/((float)bitrate) + 0.5f;
894 bitrate = (int)((
float)bitrate/1000.0f + 0.5f);
898 fill_buffer(&aacBuff);
899 if ((bread = NeAACDecInit(hDecoder, aacBuff.buffer,
900 aacBuff.bytes_into_buffer, &samplerate, &tchannels)) < 0) {
902 logMsg(
"Error initializing decoder library.");
904 free(aacBuff.buffer);
905 NeAACDecClose(hDecoder);
906 fclose(aacBuff.infile);
909 advance_buffer(&aacBuff, bread);
910 fill_buffer(&aacBuff);
913 logMsg(
"%s file info:", mPath.c_str());
914 switch (header_type) {
919 logMsg(
"ADTS, %.3f sec, %d kbps, %d Hz", length, bitrate, samplerate);
922 logMsg(
"ADIF, %.3f sec, %d kbps, %d Hz", length, bitrate, samplerate);
927 sample_buffer = NeAACDecDecode(hDecoder, &frameInfo, aacBuff.buffer, aacBuff.bytes_into_buffer);
930 advance_buffer(&aacBuff, frameInfo.bytesconsumed);
932 if (frameInfo.error > 0) {
934 NeAACDecGetErrorMessage(frameInfo.error));
936 if ( ! writeBuffer((
float *) sample_buffer, frameInfo.samples) )
939 fill_buffer(&aacBuff);
940 if (aacBuff.bytes_into_buffer == 0)
941 sample_buffer = NULL;
943 }
while (sample_buffer != NULL);
945 NeAACDecClose(hDecoder);
947 free(aacBuff.buffer);
948 return (frameInfo.error ?
kErr :
kOk);
953 Status MP4File::decodeMP4file(FILE * inFile)
throw (CException) {
956 long sampleId, numSamples;
961 unsigned char *tbuffer = NULL;
962 unsigned int buffer_size;
963 unsigned long samplerate;
964 unsigned char tchannels;
966 unsigned int useAacLength = 1;
967 unsigned int initial = 1;
968 unsigned int framesize;
969 unsigned long timescale;
972 mp4ff_callback_t * mp4cb = (mp4ff_callback_t *) malloc(
sizeof(mp4ff_callback_t));
973 mp4cb->read = read_callback;
974 mp4cb->seek = seek_callback;
975 mp4cb->user_data = inFile;
977 hDecoder = NeAACDecOpen();
980 config = NeAACDecGetCurrentConfiguration(hDecoder);
981 config->outputFormat = 4;
982 config->downMatrix = 1;
984 NeAACDecSetConfiguration(hDecoder, config);
986 mp4File = mp4ff_open_read(mp4cb);
988 if ((track = GetAACTrack(mp4File)) < 0) {
989 logMsg(
"Warning: Unable to find correct AAC sound track in the MP4 file.");
990 NeAACDecClose(hDecoder);
991 mp4ff_close(mp4File);
998 mp4ff_get_decoder_config(mp4File, track, &tbuffer, &buffer_size);
1000 if (NeAACDecInit2(hDecoder, tbuffer, buffer_size, &samplerate, &tchannels) < 0) {
1002 logMsg(
"Error initializing decoder library.");
1003 NeAACDecClose(hDecoder);
1004 mp4ff_close(mp4File);
1009 timescale = mp4ff_time_scale(mp4File, track);
1013 mNumChannels = tchannels;
1015 if (NeAACDecAudioSpecificConfig(tbuffer, buffer_size, &mp4ASC) >= 0) {
1016 if (mp4ASC.frameLengthFlag == 1)
1018 if (mp4ASC.sbr_present_flag == 1)
1023 numSamples = mp4ff_num_samples(mp4File, track);
1025 unsigned songLength;
1029 this->addBuffer(mNumChannels, (songLength +
mFrameRate));
1031 for (sampleId = 0; sampleId < numSamples; sampleId++) {
1034 unsigned int sample_count;
1035 unsigned int delay = 0;
1039 dur = mp4ff_get_sample_duration(mp4File, track, sampleId);
1040 rc = mp4ff_read_sample(mp4File, track, sampleId, &tbuffer, &buffer_size);
1042 logMsg(
"Reading from MP4 file failed.");
1043 NeAACDecClose(hDecoder);
1044 mp4ff_close(mp4File);
1049 sample_buffer = NeAACDecDecode(hDecoder, &frameInfo, tbuffer, buffer_size);
1050 if (tbuffer) free(tbuffer);
1052 if (sampleId == 0) dur = 0;
1054 if (useAacLength || (timescale != samplerate)) {
1055 sample_count = frameInfo.samples;
1057 sample_count = (
unsigned int)(dur * frameInfo.channels);
1058 if (sample_count > frameInfo.samples)
1059 sample_count = frameInfo.samples;
1061 if (!useAacLength && !initial && (sampleId < numSamples/2) && (sample_count != frameInfo.samples)) {
1062 logMsg(
"MP4 seems to have incorrect frame duration, using values from AAC data.");
1064 sample_count = frameInfo.samples;
1067 if (initial && (sample_count < framesize*frameInfo.channels) && (frameInfo.samples > sample_count))
1068 delay = frameInfo.samples - sample_count;
1072 if ((frameInfo.error == 0) && (sample_count > 0))
1073 if ( ! writeBuffer((
float *) sample_buffer, sample_count))
1076 if (frameInfo.error > 0) {
1077 logMsg(
"Warning: %s", NeAACDecGetErrorMessage(frameInfo.error));
1080 NeAACDecClose(hDecoder);
1081 mp4ff_close(mp4File);
1083 return (frameInfo.error ?
kErr :
kOk);