2 * Copyright (C) 2005-2008 Team XBMC
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with XBMC; see the file COPYING. If not, write to
17 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 #include "utils/log.h"
25 #include "cores/AudioEngine/Utils/AEUtil.h"
27 using namespace MUSIC_INFO;
29 #define DECODER_DELAY 529 // decoder delay in samples
31 #define DEFAULT_CHUNK_SIZE 16384
33 #define DECODING_ERROR -1
34 #define DECODING_SUCCESS 0
35 #define DECODING_CALLAGAIN 1
37 #define SAMPLESPERFRAME 1152
38 #define CHANNELSPERSAMPLE 2
39 #define BITSPERSAMPLE 32
40 #define OUTPUTFRAMESIZE (SAMPLESPERFRAME * CHANNELSPERSAMPLE * (BITSPERSAMPLE >> 3))
52 m_CallAgainWithSameBuffer = false;
54 m_InputBufferSize = 64*1024; // 64k is a reasonable amount, considering that we actual are
55 // using a background reader thread now that caches in advance.
56 m_InputBuffer = new BYTE[m_InputBufferSize];
59 memset(&m_Formatdata,0,sizeof(m_Formatdata));
60 m_DataFormat = AE_FMT_S32NE;
62 // create our output buffer
63 m_OutputBufferSize = OUTPUTFRAMESIZE * 4; // enough for 4 frames
64 m_OutputBuffer = new BYTE[m_OutputBufferSize];
65 m_OutputBufferPos = 0;
67 m_IgnoreFirst = true; // we want to be gapless
72 memset(&mxhouse, 0, sizeof(madx_house));
73 memset(&mxstat, 0, sizeof(madx_stat));
86 delete[] m_InputBuffer;
89 delete[] m_OutputBuffer;
90 m_OutputBuffer = NULL;
93 madx_deinit(&mxhouse);
96 //Eventhandler if filereader is clearedwe flush the decoder.
97 void MP3Codec::OnFileReaderClearEvent()
102 bool MP3Codec::Init(const CStdString &strFile, unsigned int filecache)
108 m_InputBufferPos = 0;
109 m_OutputBufferPos = 0;
110 m_IgnoreFirst = true; // we want to be gapless
113 m_lastByteOffset = 0;
115 m_CallAgainWithSameBuffer = false;
118 CFileItem item(strFile, false);
119 CMusicInfoTagLoaderMP3 mp3info;
126 if (!m_file.Open(strFile, READ_CACHED))
128 CLog::Log(LOGERROR, "MP3Codec: Unable to open file %s", strFile.c_str());
132 bTags = mp3info.ReadSeekAndReplayGainInfo(strFile);
135 // Guess Bitrate and obtain replayGain information etc.
136 mp3info.ReadSeekAndReplayGainInfo(strFile);
137 mp3info.GetSeekInfo(m_seekInfo);
138 mp3info.GetReplayGain(m_replayGain);
141 length = m_file.GetLength();
143 m_TotalTime = (int64_t)(m_seekInfo.GetDuration() * 1000.0f);
145 // Read in some data so we can determine the sample size and so on
146 // This needs to be made more intelligent - possibly use a temp output buffer
147 // and cycle around continually reading until we have the necessary data
148 // as a first workaround skip the id3v2 tag at the beginning of the file
151 if (m_seekInfo.GetNumOffsets() > 0)
153 const float* offsets=m_seekInfo.GetOffsets();
154 id3v2Size=(int)offsets[0];
155 m_file.Seek(id3v2Size);
159 CLog::Log(LOGERROR, "MP3Codec: Seek info unavailable for file <%s> (corrupt?)", strFile.c_str());
164 if ( m_TotalTime && (length - id3v2Size > 0) )
166 m_Bitrate = (int)(((length - id3v2Size) / m_seekInfo.GetDuration()) * 8); // average bitrate
170 while ((result != DECODING_SUCCESS) && !m_eof && (m_OutputBufferPos < OUTPUTFRAMESIZE)) // eof can be set from outside (when stopping playback)
172 result = Read(8192, true);
173 if (result == DECODING_ERROR)
175 CLog::Log(LOGERROR, "MP3Codec: Unable to determine file format of %s (corrupt start of mp3?)", strFile.c_str());
178 if (bTags && !m_Bitrate) //use tag bitrate if average bitrate is not available
179 m_Bitrate = m_Formatdata[4];
189 void MP3Codec::DeInit()
195 void MP3Codec::FlushDecoder()
199 m_InputBufferPos = 0;
200 m_OutputBufferPos = 0;
201 m_CallAgainWithSameBuffer = false;
204 int64_t MP3Codec::Seek(int64_t iSeekTime)
206 // calculate our offset to seek to in the file
207 m_lastByteOffset = m_seekInfo.GetByteOffset(0.001f * iSeekTime);
208 m_file.Seek(m_lastByteOffset, SEEK_SET);
213 int MP3Codec::Read(int size, bool init)
215 int inputBufferToRead = (int)(m_InputBufferSize - m_InputBufferPos);
216 if ( inputBufferToRead && !m_CallAgainWithSameBuffer && !m_eof )
218 if (m_file.GetLength() > 0)
220 int fileLeft=(int)(m_file.GetLength() - m_file.GetPosition());
221 if (inputBufferToRead > fileLeft ) inputBufferToRead = fileLeft;
224 DWORD dwBytesRead = m_file.Read(m_InputBuffer + m_InputBufferPos , inputBufferToRead);
227 CLog::Log(LOGERROR, "MP3Codec: Error reading file");
228 return DECODING_ERROR;
230 // add the size of read PAP data to the buffer size
231 m_InputBufferPos += dwBytesRead;
232 if (m_file.GetLength() > 0 && m_file.GetLength() == m_file.GetPosition() )
235 // Decode data if we have some to decode
236 if ( m_InputBufferPos || m_CallAgainWithSameBuffer || (m_eof && m_Decoding) )
244 m_CallAgainWithSameBuffer = false;
245 int outputsize = m_OutputBufferSize - m_OutputBufferPos;
246 // See if there is an ID3v2 tag at the beginning of the stream.
247 // For file-based internet streams (i.e UPnP/HTTP), it is very likely to happen.
248 // If we don't skip it, we may never be able to snyc to the MPEG stream
251 // Check for an ID3v2 tag header
252 unsigned int tagSize = CMusicInfoTagLoaderMP3::IsID3v2Header(m_InputBuffer,m_InputBufferPos);
255 if (tagSize != m_file.Seek(tagSize, SEEK_SET))
256 return DECODING_ERROR;
258 // Reset the read state before we return
259 m_InputBufferPos = 0;
260 m_CallAgainWithSameBuffer = false;
262 // Please try your call again later...
263 return DECODING_CALLAGAIN;
267 // Now decode data into the vacant frame buffer.
268 result = Decode(&outputsize);
269 if ( result != DECODING_ERROR)
273 if (result == 0 && m_readRetries-- > 0)
274 return Read(size,init);
275 // Make sure some data was decoded. Without a valid frame, we cannot determine the audio format
277 return DECODING_ERROR;
279 m_Channels = m_Formatdata[2];
280 m_SampleRate = m_Formatdata[1];
281 m_BitsPerSample = m_Formatdata[3];
284 // let's check if we need to ignore the decoded data.
285 if ( m_IgnoreFirst && outputsize && m_seekInfo.GetFirstSample() )
287 // starting up - lets ignore the first (typically 576) samples
288 int iDelay = DECODER_DELAY + m_seekInfo.GetFirstSample(); // decoder delay + encoder delay
289 iDelay *= m_Channels * (m_BitsPerSample >> 3); // sample size
290 if (outputsize + m_IgnoredBytes >= iDelay)
292 // have enough data to ignore - let's move the valid data to the start
293 int iAmountToMove = outputsize + m_IgnoredBytes - iDelay;
294 memmove(m_OutputBuffer, m_OutputBuffer + outputsize - iAmountToMove, iAmountToMove);
295 outputsize = iAmountToMove;
296 m_IgnoreFirst = false;
300 { // not enough data yet - ignore all of this
301 m_IgnoredBytes += outputsize;
306 // Do we still have data in the buffer to decode?
307 if ( result == DECODING_CALLAGAIN )
308 m_CallAgainWithSameBuffer = true;
310 { // There are no more complete frames in the input buffer
311 //m_InputBufferPos = 0;
312 // Check for the end of file (as we need to remove data from the end of the track)
316 // EOF reached - let's remove any unused samples from our frame buffers
317 if (m_IgnoreLast && m_seekInfo.GetLastSample())
319 unsigned int samplestoremove = (m_seekInfo.GetLastSample() - DECODER_DELAY);
320 samplestoremove *= m_Channels * (m_BitsPerSample >> 3);
321 if (samplestoremove > m_OutputBufferPos)
322 samplestoremove = m_OutputBufferPos;
323 m_OutputBufferPos -= samplestoremove;
324 m_IgnoreLast = false;
328 m_OutputBufferPos += outputsize;
329 ASSERT(m_OutputBufferPos <= m_OutputBufferSize);
335 return DECODING_SUCCESS;
338 int MP3Codec::ReadPCM(BYTE *pBuffer, int size, int *actualsize)
341 if (Read(size) == DECODING_ERROR)
344 // check whether we can move data out of our output buffer
345 // we leave some data in our output buffer to allow us to remove samples
346 // at the end of the track for gapless playback
348 if ((m_eof && !m_Decoding) || m_OutputBufferPos <= OUTPUTFRAMESIZE)
349 move = m_OutputBufferPos;
351 move = m_OutputBufferPos - OUTPUTFRAMESIZE;
352 move = std::min(move, size);
354 memcpy(pBuffer, m_OutputBuffer, move);
355 m_OutputBufferPos -= move;
356 memmove(m_OutputBuffer, m_OutputBuffer + move, m_OutputBufferPos);
359 // only return READ_EOF when we've reached the end of the mp3 file, we've finished decoding, and our output buffer is depleated.
360 if (m_eof && !m_Decoding && !m_OutputBufferPos)
366 bool MP3Codec::CanInit()
368 return m_dll.CanLoad();
371 bool MP3Codec::SkipNext()
373 return m_file.SkipNext();
376 bool MP3Codec::CanSeek()
381 int MP3Codec::Decode(int *out_len)
385 if (!m_dll.IsLoaded())
388 //MAD needs padding at the end of the stream to decode the last frame, this doesn't hurt winamps in_mp3.dll
393 if (m_InputBufferPos + madguard > m_InputBufferSize)
394 madguard = m_InputBufferSize - m_InputBufferPos;
395 memset(m_InputBuffer + m_InputBufferPos, 0, madguard);
398 m_dll.mad_stream_buffer( &mxhouse.stream, m_InputBuffer, m_InputBufferPos + madguard );
399 mxhouse.stream.error = (mad_error)0;
400 m_dll.mad_stream_sync(&mxhouse.stream);
401 if ((mxstat.flushed) && (flushcnt == 2))
407 if (m_dll.mad_frame_decode(&mxhouse.frame, &mxhouse.stream) == 0)
410 m_dll.mad_synth_frame(&mxhouse.synth, &mxhouse.frame);
412 else if (!MAD_RECOVERABLE(mxhouse.stream.error))
416 mxstat.flushed = false;
419 int maxtowrite = *out_len;
421 mxsig = ERROR_OCCURED;
422 while ((mxsig != FLUSH_BUFFER) && (*out_len + mxstat.framepcmsize < (size_t)maxtowrite))
424 mxsig = madx_read(&mxhouse, &mxstat, maxtowrite);
432 if (mxstat.remaining > 0)
434 memcpy(m_InputBuffer, mxhouse.stream.next_frame, mxstat.remaining);
435 m_InputBufferPos = mxstat.remaining;
440 m_Formatdata[2] = mxhouse.synth.pcm.channels;
441 m_Formatdata[1] = mxhouse.synth.pcm.samplerate;
442 m_Formatdata[3] = BITSPERSAMPLE;
443 m_Formatdata[4] = mxhouse.frame.header.bitrate;
444 *out_len += (int)mxstat.write_size;
445 mxstat.write_size = 0;
451 if (!mxhouse.stream.next_frame || (mxhouse.stream.bufend - mxhouse.stream.next_frame <= 0))
460 void MP3Codec::Flush()
462 if (!m_dll.IsLoaded())
464 m_dll.mad_frame_mute(&mxhouse.frame);
465 m_dll.mad_synth_mute(&mxhouse.synth);
466 m_dll.mad_stream_finish(&mxhouse.stream);
467 m_dll.mad_stream_init(&mxhouse.stream);
468 ZeroMemory(&mxstat, sizeof(madx_stat));
469 mxstat.flushed = true;
470 if (flushcnt < 2) flushcnt++;
472 m_InputBufferPos = 0;
475 int MP3Codec::madx_init (madx_house *mxhouse )
477 if (!m_dll.IsLoaded())
479 // Initialize libmad structures
480 m_dll.mad_stream_init(&mxhouse->stream);
481 mxhouse->stream.options = MAD_OPTION_IGNORECRC;
482 m_dll.mad_frame_init(&mxhouse->frame);
483 m_dll.mad_synth_init(&mxhouse->synth);
484 mxhouse->timer = m_dll.Get_mad_timer_zero();
489 madx_sig MP3Codec::madx_read(madx_house *mxhouse, madx_stat *mxstat, int maxwrite)
491 if (!m_dll.IsLoaded())
493 mxhouse->output_ptr = m_OutputBuffer + m_OutputBufferPos;
495 if( m_dll.mad_frame_decode(&mxhouse->frame, &mxhouse->stream) )
497 if( !MAD_RECOVERABLE(mxhouse->stream.error) )
499 if( mxhouse->stream.error == MAD_ERROR_BUFLEN )
501 //printf("Need more input (%s)", mad_stream_errorstr(&mxhouse->stream));
502 mxstat->remaining = mxhouse->stream.bufend - mxhouse->stream.next_frame;
508 CLog::Log(LOGERROR, "(MAD)Unrecoverable frame level error (%s).", m_dll.mad_stream_errorstr(&mxhouse->stream));
509 return(ERROR_OCCURED);
515 m_dll.mad_synth_frame( &mxhouse->synth, &mxhouse->frame );
517 mxstat->framepcmsize = mxhouse->synth.pcm.length * mxhouse->synth.pcm.channels * (int)(BITSPERSAMPLE >> 3);
518 mxhouse->frame_cnt++;
519 m_dll.mad_timer_add( &mxhouse->timer, mxhouse->frame.header.duration );
521 int32_t *dest = (int32_t*)mxhouse->output_ptr;
522 for(int i=0; i < mxhouse->synth.pcm.length; i++)
525 *dest++ = (int32_t)(mxhouse->synth.pcm.samples[0][i] << 2);
528 if(MAD_NCHANNELS(&mxhouse->frame.header) == 2)
529 *dest++ = (int32_t)(mxhouse->synth.pcm.samples[1][i] << 2);
532 // Tell calling code buffer size
533 mxhouse->output_ptr = (unsigned char*)dest;
534 mxstat->write_size = mxhouse->output_ptr - (m_OutputBuffer + m_OutputBufferPos);
536 return(FLUSH_BUFFER);
539 void MP3Codec::madx_deinit( madx_house *mxhouse )
541 if (!m_dll.IsLoaded())
543 mad_synth_finish(&mxhouse->synth);
544 m_dll.mad_frame_finish(&mxhouse->frame);
545 m_dll.mad_stream_finish(&mxhouse->stream);
548 CAEChannelInfo MP3Codec::GetChannelInfo()
550 static enum AEChannel map[2][3] = {
551 {AE_CH_FC, AE_CH_NULL},
552 {AE_CH_FL, AE_CH_FR , AE_CH_NULL}
556 return CAEUtil::GuessChLayout(m_Channels);
558 return CAEChannelInfo(map[m_Channels - 1]);