Merge pull request #1129 from jmarshallnz/remove_smb_auth_details_in_add_source
[vuplus_xbmc] / xbmc / cores / paplayer / MP3codec.cpp
1 /*
2  *      Copyright (C) 2005-2008 Team XBMC
3  *      http://www.xbmc.org
4  *
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)
8  *  any later version.
9  *
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.
14  *
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
19  *
20  */
21
22 #include "MP3codec.h"
23 #include "FileItem.h"
24 #include "utils/log.h"
25 #include "cores/AudioEngine/Utils/AEUtil.h"
26
27 using namespace MUSIC_INFO;
28
29 #define DECODER_DELAY 529 // decoder delay in samples
30
31 #define DEFAULT_CHUNK_SIZE 16384
32
33 #define DECODING_ERROR    -1
34 #define DECODING_SUCCESS   0
35 #define DECODING_CALLAGAIN 1
36
37 #define SAMPLESPERFRAME   1152
38 #define CHANNELSPERSAMPLE 2
39 #define BITSPERSAMPLE     32
40 #define OUTPUTFRAMESIZE   (SAMPLESPERFRAME * CHANNELSPERSAMPLE * (BITSPERSAMPLE >> 3))
41
42 MP3Codec::MP3Codec()
43 {
44   m_SampleRate = 0;
45   m_Channels = 0;
46   m_BitsPerSample = 0;
47   m_TotalTime = 0;
48   m_Bitrate = 0;
49   m_CodecName = "MP3";
50
51   // mp3 related
52   m_CallAgainWithSameBuffer = false;
53   m_lastByteOffset = 0;
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];
57   m_InputBufferPos = 0;
58
59   memset(&m_Formatdata,0,sizeof(m_Formatdata));
60   m_DataFormat = AE_FMT_S32NE;
61
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;
66   m_Decoding = false;
67   m_IgnoreFirst = true; // we want to be gapless
68   m_IgnoredBytes = 0;
69   m_IgnoreLast = true;
70   m_eof = false;
71   
72   memset(&mxhouse, 0, sizeof(madx_house));
73   memset(&mxstat,  0, sizeof(madx_stat));
74   
75   m_HaveData = false;
76   flushcnt = 0;
77
78   if (m_dll.Load())
79     madx_init(&mxhouse);
80 }
81
82 MP3Codec::~MP3Codec()
83 {
84   DeInit();
85
86   delete[] m_InputBuffer;
87   m_InputBuffer = NULL;
88
89   delete[] m_OutputBuffer;
90   m_OutputBuffer = NULL;
91   
92   if (m_dll.IsLoaded())
93     madx_deinit(&mxhouse);
94 }
95
96 //Eventhandler if filereader is clearedwe flush the decoder.
97 void MP3Codec::OnFileReaderClearEvent()
98 {
99   FlushDecoder();
100 }
101
102 bool MP3Codec::Init(const CStdString &strFile, unsigned int filecache)
103 {
104   if (!m_dll.Load())
105     return false;
106
107   // set defaults...
108   m_InputBufferPos = 0;
109   m_OutputBufferPos = 0;
110   m_IgnoreFirst = true; // we want to be gapless
111   m_IgnoredBytes = 0;
112   m_IgnoreLast = true;
113   m_lastByteOffset = 0;
114   m_eof = false;
115   m_CallAgainWithSameBuffer = false;
116   m_readRetries = 5;
117
118   CFileItem item(strFile, false);
119   CMusicInfoTagLoaderMP3 mp3info;
120
121   int id3v2Size = 0;
122   int result = -1;
123   int64_t length = 0;
124   bool bTags = false;
125
126   if (!m_file.Open(strFile, READ_CACHED))
127   {
128     CLog::Log(LOGERROR, "MP3Codec: Unable to open file %s", strFile.c_str());
129     goto error;
130   }
131
132   bTags = mp3info.ReadSeekAndReplayGainInfo(strFile);
133   if(bTags)
134   {
135     // Guess Bitrate and obtain replayGain information etc.
136     mp3info.ReadSeekAndReplayGainInfo(strFile);
137     mp3info.GetSeekInfo(m_seekInfo);
138     mp3info.GetReplayGain(m_replayGain);
139   }
140
141   length = m_file.GetLength();
142   if (bTags)
143     m_TotalTime = (int64_t)(m_seekInfo.GetDuration() * 1000.0f);
144
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
149   if (bTags)
150   {
151     if (m_seekInfo.GetNumOffsets() > 0)
152     {
153       const float* offsets=m_seekInfo.GetOffsets();
154       id3v2Size=(int)offsets[0];
155       m_file.Seek(id3v2Size);
156     }
157     else
158     {
159       CLog::Log(LOGERROR, "MP3Codec: Seek info unavailable for file <%s> (corrupt?)", strFile.c_str());
160       goto error;
161     }
162   }
163   
164   if ( m_TotalTime && (length - id3v2Size > 0) )
165   {
166     m_Bitrate = (int)(((length - id3v2Size) / m_seekInfo.GetDuration()) * 8);  // average bitrate
167   }
168
169   m_eof = false;
170   while ((result != DECODING_SUCCESS) && !m_eof && (m_OutputBufferPos < OUTPUTFRAMESIZE)) // eof can be set from outside (when stopping playback)
171   {
172     result = Read(8192, true);
173     if (result == DECODING_ERROR)
174     {
175       CLog::Log(LOGERROR, "MP3Codec: Unable to determine file format of %s (corrupt start of mp3?)", strFile.c_str());
176       goto error;
177     }
178     if (bTags && !m_Bitrate) //use tag bitrate if average bitrate is not available
179       m_Bitrate = m_Formatdata[4];
180   } ;
181
182   return true;
183
184 error:
185   m_file.Close();
186   return false;
187 }
188
189 void MP3Codec::DeInit()
190 {
191   m_file.Close();
192   m_eof = true;
193 }
194
195 void MP3Codec::FlushDecoder()
196 {
197   // Flush the decoder
198   Flush();
199   m_InputBufferPos = 0;
200   m_OutputBufferPos = 0;
201   m_CallAgainWithSameBuffer = false;
202 }
203
204 int64_t MP3Codec::Seek(int64_t iSeekTime)
205 {
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);
209   FlushDecoder();
210   return iSeekTime;
211 }
212
213 int MP3Codec::Read(int size, bool init)
214 {
215   int inputBufferToRead = (int)(m_InputBufferSize - m_InputBufferPos);
216   if ( inputBufferToRead && !m_CallAgainWithSameBuffer && !m_eof )
217   {
218     if (m_file.GetLength() > 0)
219     {
220       int fileLeft=(int)(m_file.GetLength() - m_file.GetPosition());
221       if (inputBufferToRead >  fileLeft ) inputBufferToRead = fileLeft;
222     }
223
224     DWORD dwBytesRead = m_file.Read(m_InputBuffer + m_InputBufferPos , inputBufferToRead);
225     if (!dwBytesRead)
226     {
227       CLog::Log(LOGERROR, "MP3Codec: Error reading file");
228       return DECODING_ERROR;
229     }
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() )
233       m_eof = true;
234   }
235   // Decode data if we have some to decode
236   if ( m_InputBufferPos || m_CallAgainWithSameBuffer || (m_eof && m_Decoding) )
237   {
238     int result;
239
240     m_Decoding = true;
241
242     if ( size )
243     {
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
249       if (init)
250       {
251         // Check for an ID3v2 tag header
252         unsigned int tagSize = CMusicInfoTagLoaderMP3::IsID3v2Header(m_InputBuffer,m_InputBufferPos);
253         if(tagSize)
254         {
255           if (tagSize != m_file.Seek(tagSize, SEEK_SET))
256             return DECODING_ERROR;
257
258           // Reset the read state before we return
259           m_InputBufferPos = 0;
260           m_CallAgainWithSameBuffer = false;
261
262           // Please try your call again later...
263           return DECODING_CALLAGAIN;
264         }
265       }
266
267       // Now decode data into the vacant frame buffer.
268       result = Decode(&outputsize);
269       if ( result != DECODING_ERROR)
270       {
271         if (init)
272         {
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
276           if (!outputsize)
277             return DECODING_ERROR;
278
279           m_Channels              = m_Formatdata[2];
280           m_SampleRate            = m_Formatdata[1];
281           m_BitsPerSample         = m_Formatdata[3];
282         }
283
284         // let's check if we need to ignore the decoded data.
285         if ( m_IgnoreFirst && outputsize && m_seekInfo.GetFirstSample() )
286         {
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)
291           {
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;
297             m_IgnoredBytes = 0;
298           }
299           else
300           { // not enough data yet - ignore all of this
301             m_IgnoredBytes += outputsize;
302             outputsize = 0;
303           }
304         }
305
306         // Do we still have data in the buffer to decode?
307         if ( result == DECODING_CALLAGAIN )
308           m_CallAgainWithSameBuffer = true;
309         else
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)
313           if (m_eof)
314           {
315             m_Decoding = false;
316             // EOF reached - let's remove any unused samples from our frame buffers
317             if (m_IgnoreLast && m_seekInfo.GetLastSample())
318             {
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;
325             }
326           }
327         }
328         m_OutputBufferPos += outputsize;
329         ASSERT(m_OutputBufferPos <= m_OutputBufferSize);
330       }
331       return result;
332     }
333   }
334   m_readRetries = 5;
335   return DECODING_SUCCESS;
336 }
337
338 int MP3Codec::ReadPCM(BYTE *pBuffer, int size, int *actualsize)
339 {
340   *actualsize = 0;
341   if (Read(size) == DECODING_ERROR)
342     return READ_ERROR;
343
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
347   int move;
348   if ((m_eof && !m_Decoding) || m_OutputBufferPos <= OUTPUTFRAMESIZE)
349     move = m_OutputBufferPos;
350   else
351     move = m_OutputBufferPos - OUTPUTFRAMESIZE;
352   move = std::min(move, size);
353
354   memcpy(pBuffer, m_OutputBuffer, move);
355   m_OutputBufferPos -= move;
356   memmove(m_OutputBuffer, m_OutputBuffer + move, m_OutputBufferPos);
357   *actualsize = move;
358
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)
361     return READ_EOF;
362
363   return READ_SUCCESS;
364 }
365
366 bool MP3Codec::CanInit()
367 {
368   return m_dll.CanLoad();
369 }
370
371 bool MP3Codec::SkipNext()
372 {
373   return m_file.SkipNext();
374 }
375
376 bool MP3Codec::CanSeek()
377 {
378   return true;
379 }
380
381 int MP3Codec::Decode(int *out_len)
382 {
383   if (!m_HaveData)
384   {
385     if (!m_dll.IsLoaded())
386       m_dll.Load();
387     
388     //MAD needs padding at the end of the stream to decode the last frame, this doesn't hurt winamps in_mp3.dll
389     int madguard = 0;
390     if (m_eof)
391     {
392       madguard = 8;
393       if (m_InputBufferPos + madguard > m_InputBufferSize)
394         madguard = m_InputBufferSize - m_InputBufferPos;
395       memset(m_InputBuffer + m_InputBufferPos, 0, madguard);
396     }
397
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))
402     {
403       int skip;
404       skip = 2;
405       do
406       {
407         if (m_dll.mad_frame_decode(&mxhouse.frame, &mxhouse.stream) == 0)
408         {
409           if (--skip == 0)
410             m_dll.mad_synth_frame(&mxhouse.synth, &mxhouse.frame);
411         }
412         else if (!MAD_RECOVERABLE(mxhouse.stream.error))
413           break;
414       }
415       while (skip);
416       mxstat.flushed = false;
417     }
418   }
419   int maxtowrite = *out_len;
420   *out_len = 0;
421   mxsig = ERROR_OCCURED;
422   while ((mxsig != FLUSH_BUFFER) && (*out_len + mxstat.framepcmsize < (size_t)maxtowrite))
423   {
424     mxsig = madx_read(&mxhouse, &mxstat, maxtowrite);
425     switch (mxsig)
426     {
427     case ERROR_OCCURED: 
428       *out_len = 0;
429       m_HaveData = false;
430       return -1;
431     case MORE_INPUT: 
432       if (mxstat.remaining > 0)
433       {
434         memcpy(m_InputBuffer, mxhouse.stream.next_frame, mxstat.remaining);
435         m_InputBufferPos = mxstat.remaining;
436       }
437       m_HaveData = false;
438       return 0;
439     case FLUSH_BUFFER:
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;
446       break;
447     default:
448       break;
449     }
450   }
451   if (!mxhouse.stream.next_frame || (mxhouse.stream.bufend - mxhouse.stream.next_frame <= 0))
452   {
453     m_HaveData = false;
454     return 0;
455   }
456   m_HaveData = true;
457   return 1;
458 }
459
460 void MP3Codec::Flush()
461 {
462   if (!m_dll.IsLoaded())
463     m_dll.Load();
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++;
471   m_HaveData = false;
472   m_InputBufferPos = 0;
473 }
474
475 int MP3Codec::madx_init (madx_house *mxhouse )
476 {
477   if (!m_dll.IsLoaded())
478     m_dll.Load();
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();
485
486   return(1);
487 }
488
489 madx_sig MP3Codec::madx_read(madx_house *mxhouse, madx_stat *mxstat, int maxwrite)
490 {
491   if (!m_dll.IsLoaded())
492     m_dll.Load();
493   mxhouse->output_ptr = m_OutputBuffer + m_OutputBufferPos;
494
495   if( m_dll.mad_frame_decode(&mxhouse->frame, &mxhouse->stream) )
496   {
497     if( !MAD_RECOVERABLE(mxhouse->stream.error) )
498     {
499       if( mxhouse->stream.error == MAD_ERROR_BUFLEN )
500       {    
501         //printf("Need more input (%s)",  mad_stream_errorstr(&mxhouse->stream));
502         mxstat->remaining = mxhouse->stream.bufend - mxhouse->stream.next_frame;
503
504         return(MORE_INPUT);      
505       }
506       else
507       {
508         CLog::Log(LOGERROR, "(MAD)Unrecoverable frame level error (%s).", m_dll.mad_stream_errorstr(&mxhouse->stream));
509         return(ERROR_OCCURED); 
510       }
511     }
512     return(SKIP_FRAME); 
513   }
514
515   m_dll.mad_synth_frame( &mxhouse->synth, &mxhouse->frame );
516   
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 );
520
521   int32_t *dest = (int32_t*)mxhouse->output_ptr;
522   for(int i=0; i < mxhouse->synth.pcm.length; i++)
523   {
524     // Left channel
525     *dest++ = (int32_t)(mxhouse->synth.pcm.samples[0][i] << 2);
526
527     // Right channel
528     if(MAD_NCHANNELS(&mxhouse->frame.header) == 2)
529       *dest++ = (int32_t)(mxhouse->synth.pcm.samples[1][i] << 2);
530   }
531
532   // Tell calling code buffer size
533   mxhouse->output_ptr = (unsigned char*)dest;
534   mxstat->write_size  = mxhouse->output_ptr - (m_OutputBuffer + m_OutputBufferPos);
535
536   return(FLUSH_BUFFER);
537 }
538
539 void MP3Codec::madx_deinit( madx_house *mxhouse )
540 {
541   if (!m_dll.IsLoaded())
542     m_dll.Load();
543   mad_synth_finish(&mxhouse->synth);
544   m_dll.mad_frame_finish(&mxhouse->frame);
545   m_dll.mad_stream_finish(&mxhouse->stream);
546 }
547
548 CAEChannelInfo MP3Codec::GetChannelInfo()
549 {
550   static enum AEChannel map[2][3] = {
551     {AE_CH_FC, AE_CH_NULL},
552     {AE_CH_FL, AE_CH_FR  , AE_CH_NULL}
553   };
554
555   if (m_Channels > 2)
556     return CAEUtil::GuessChLayout(m_Channels);
557
558   return CAEChannelInfo(map[m_Channels - 1]);
559 }