File indexing completed on 2024-05-12 04:51:32

0001 /*
0002     SPDX-FileCopyrightText: 1998-2008 Sebastian Trueg <trueg@k3b.org>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 
0008 //
0009 // Some notes on mp3:
0010 // A mp3 Frame is always samples/samplerate seconds in length
0011 //
0012 //
0013 //
0014 // What we need are raw 16 bit stereo samples at 44100 Hz which results in 588 samples
0015 // per block (2352 bytes: 32*588 bit). 1 second are 75 blocks.
0016 //
0017 
0018 #include "k3bmaddecoder.h"
0019 #include "k3bmad.h"
0020 #include "k3bplugin_i18n.h"
0021 
0022 #include <config-k3b.h>
0023 
0024 #include <QDebug>
0025 #include <QString>
0026 #include <QFile>
0027 #include <QVector>
0028 
0029 #include <stdlib.h>
0030 #include <cmath>
0031 #include <cstdlib>
0032 
0033 #ifdef ENABLE_TAGLIB
0034 #include <tag.h>
0035 #include <mpegfile.h>
0036 #endif
0037 
0038 
0039 K_PLUGIN_CLASS_WITH_JSON(K3bMadDecoderFactory, "k3bmaddecoder.json")
0040 
0041 int K3bMadDecoder::MaxAllowedRecoverableErrors = 10;
0042 
0043 
0044 
0045 class K3bMadDecoder::MadDecoderPrivate
0046 {
0047 public:
0048     MadDecoderPrivate()
0049         : outputBuffer(0),
0050           outputPointer(0),
0051           outputBufferEnd(0) {
0052         mad_header_init( &firstHeader );
0053     }
0054 
0055     K3bMad* handle;
0056 
0057     QVector<unsigned long long> seekPositions;
0058 
0059     bool bOutputFinished;
0060 
0061     char* outputBuffer;
0062     char* outputPointer;
0063     char* outputBufferEnd;
0064 
0065     // the first frame header for technical info
0066     mad_header firstHeader;
0067     bool vbr;
0068 };
0069 
0070 
0071 
0072 
0073 K3bMadDecoder::K3bMadDecoder( QObject* parent  )
0074     : K3b::AudioDecoder( parent )
0075 {
0076     d = new MadDecoderPrivate();
0077     d->handle = new K3bMad();
0078 }
0079 
0080 
0081 K3bMadDecoder::~K3bMadDecoder()
0082 {
0083     cleanup();
0084     delete d->handle;
0085     delete d;
0086 }
0087 
0088 
0089 QString K3bMadDecoder::metaInfo( MetaDataField f )
0090 {
0091 #ifdef ENABLE_TAGLIB
0092     TagLib::MPEG::File file( QFile::encodeName( filename() ).data() );
0093 
0094     if ( file.tag() ) {
0095         switch( f ) {
0096         case META_TITLE:
0097             return TStringToQString( file.tag()->title() );
0098         case META_ARTIST:
0099             return TStringToQString( file.tag()->artist() );
0100         case META_COMMENT:
0101             return TStringToQString( file.tag()->comment() );
0102         default:
0103             return QString();
0104         }
0105     }
0106     else {
0107         return QString();
0108     }
0109 
0110 #else
0111     return K3b::AudioDecoder::metaInfo( f );
0112 #endif
0113 }
0114 
0115 
0116 bool K3bMadDecoder::analyseFileInternal( K3b::Msf& frames, int& samplerate, int& ch )
0117 {
0118     initDecoderInternal();
0119     frames = countFrames();
0120     if( frames > 0 ) {
0121         // we convert mono to stereo all by ourselves. :)
0122         ch = 2;
0123         samplerate = d->firstHeader.samplerate;
0124         return true;
0125     }
0126     else
0127         return false;
0128 }
0129 
0130 
0131 bool K3bMadDecoder::initDecoderInternal()
0132 {
0133     cleanup();
0134 
0135     d->bOutputFinished = false;
0136 
0137     if( !d->handle->open( filename() ) )
0138         return false;
0139 
0140     if( !d->handle->skipTag() )
0141         return false;
0142 
0143     if( !d->handle->seekFirstHeader() )
0144         return false;
0145 
0146     return true;
0147 }
0148 
0149 
0150 unsigned long K3bMadDecoder::countFrames()
0151 {
0152     qDebug() << "(K3bMadDecoder::countFrames)";
0153 
0154     unsigned long frames = 0;
0155     bool error = false;
0156     d->vbr = false;
0157     bool bFirstHeaderSaved = false;
0158 
0159     d->seekPositions.clear();
0160 
0161     while( !error && d->handle->findNextHeader() ) {
0162 
0163         if( !bFirstHeaderSaved ) {
0164             bFirstHeaderSaved = true;
0165             d->firstHeader = d->handle->madFrame->header;
0166         }
0167         else if( d->handle->madFrame->header.bitrate != d->firstHeader.bitrate )
0168             d->vbr = true;
0169 
0170         //
0171         // position in stream: position in file minus the not yet used buffer
0172         //
0173         unsigned long long seekPos = d->handle->inputPos() -
0174                                      (d->handle->madStream->bufend - d->handle->madStream->this_frame + 1);
0175 
0176         // save the number of bytes to be read to decode i-1 frames at position i
0177         // in other words: when seeking to seekPos the next decoded frame will be i
0178         d->seekPositions.append( seekPos );
0179     }
0180 
0181     if( !d->handle->inputError() && !error ) {
0182         // we need the length of the track to be multiple of frames (1/75 second)
0183         float seconds = (float)d->handle->madTimer->seconds +
0184                         (float)d->handle->madTimer->fraction/(float)MAD_TIMER_RESOLUTION;
0185         frames = (unsigned long)ceil(seconds * 75.0);
0186         qDebug() << "(K3bMadDecoder) length of track " << seconds;
0187     }
0188 
0189     cleanup();
0190 
0191     qDebug() << "(K3bMadDecoder::countFrames) end";
0192 
0193     return frames;
0194 }
0195 
0196 
0197 int K3bMadDecoder::decodeInternal( char* _data, int maxLen )
0198 {
0199     d->outputBuffer = _data;
0200     d->outputBufferEnd = d->outputBuffer + maxLen;
0201     d->outputPointer = d->outputBuffer;
0202 
0203     bool bOutputBufferFull = false;
0204 
0205     while( !bOutputBufferFull && d->handle->fillStreamBuffer() ) {
0206 
0207         // a mad_synth contains of the data of one mad_frame
0208         // one mad_frame represents a mp3-frame which is always 1152 samples
0209         // for us that means we need 4*1152 bytes of output buffer for every frame
0210         // since one sample has 16 bit
0211         if( d->outputBufferEnd - d->outputPointer < 4*1152 ) {
0212             bOutputBufferFull = true;
0213         }
0214         else if( d->handle->decodeNextFrame() ) {
0215             //
0216             // Once decoded the frame is synthesized to PCM samples. No errors
0217             // are reported by mad_synth_frame();
0218             //
0219             mad_synth_frame( d->handle->madSynth, d->handle->madFrame );
0220 
0221             // this fills the output buffer
0222             if( !createPcmSamples( d->handle->madSynth ) ) {
0223                 return -1;
0224             }
0225         }
0226         else if( d->handle->inputError() ) {
0227             return -1;
0228         }
0229     }
0230 
0231     // flush the output buffer
0232     size_t buffersize = d->outputPointer - d->outputBuffer;
0233 
0234     return buffersize;
0235 }
0236 
0237 
0238 unsigned short K3bMadDecoder::linearRound( mad_fixed_t fixed )
0239 {
0240     // round
0241     fixed += (1L << ( MAD_F_FRACBITS - 16 ));
0242 
0243     // clip
0244     if( fixed >= MAD_F_ONE - 1 )
0245         fixed = MAD_F_ONE - 1;
0246     else if( fixed < -MAD_F_ONE )
0247         fixed = -MAD_F_ONE;
0248 
0249     // quatisize
0250     return fixed >> (MAD_F_FRACBITS + 1 - 16 );
0251 }
0252 
0253 
0254 bool K3bMadDecoder::createPcmSamples( mad_synth* synth )
0255 {
0256     unsigned short nsamples = synth->pcm.length;
0257 
0258     // this should not happen since we only decode if the
0259     // output buffer has enough free space
0260     if( d->outputBufferEnd - d->outputPointer < nsamples*4 ) {
0261         qDebug() <<  "(K3bMadDecoder) buffer overflow!";
0262         return false;
0263     }
0264 
0265     // now create the output
0266     for( int i = 0; i < nsamples; i++ ) {
0267 
0268         /* Left channel */
0269         unsigned short sample = linearRound( synth->pcm.samples[0][i] );
0270         *(d->outputPointer++) = (sample >> 8) & 0xff;
0271         *(d->outputPointer++) = sample & 0xff;
0272 
0273         /* Right channel. If the decoded stream is monophonic then
0274          * the right output channel is the same as the left one.
0275          */
0276         if( synth->pcm.channels == 2 )
0277             sample = linearRound( synth->pcm.samples[1][i] );
0278 
0279         *(d->outputPointer++) = (sample >> 8) & 0xff;
0280         *(d->outputPointer++) = sample & 0xff;
0281     } // pcm conversion
0282 
0283     return true;
0284 }
0285 
0286 
0287 void K3bMadDecoder::cleanup()
0288 {
0289     d->handle->cleanup();
0290 }
0291 
0292 
0293 bool K3bMadDecoder::seekInternal( const K3b::Msf& pos )
0294 {
0295     //
0296     // we need to reset the complete mad stuff
0297     //
0298     if( !initDecoderInternal() )
0299         return false;
0300 
0301     //
0302     // search a position
0303     // This is all hacking, I don't really know what I am doing here... ;)
0304     //
0305     double mp3FrameSecs = static_cast<double>(d->firstHeader.duration.seconds)
0306                           + static_cast<double>(d->firstHeader.duration.fraction) / static_cast<double>(MAD_TIMER_RESOLUTION);
0307 
0308     double posSecs = static_cast<double>(pos.totalFrames()) / 75.0;
0309 
0310     // seekPosition to seek after frame i
0311     unsigned int frame = static_cast<unsigned int>( posSecs / mp3FrameSecs );
0312 
0313     // Rob said: 29 frames is the theoretically max frame reservoir limit (whatever that means...)
0314     // it seems that mad needs at most 29 frames to get ready
0315     unsigned int frameReservoirProtect = ( frame > 29 ? 29 : frame );
0316 
0317     frame -= frameReservoirProtect;
0318 
0319     // seek in the input file behind the already decoded data
0320     d->handle->inputSeek( d->seekPositions[frame] );
0321 
0322     qDebug() << "(K3bMadDecoder) Seeking to frame " << frame << " with "
0323              << frameReservoirProtect << " reservoir frames." << Qt::endl;
0324 
0325     // decode some frames ignoring MAD_ERROR_BADDATAPTR errors
0326     unsigned int i = 1;
0327     while( i <= frameReservoirProtect ) {
0328         d->handle->fillStreamBuffer();
0329         if( mad_frame_decode( d->handle->madFrame, d->handle->madStream ) ) {
0330             if( MAD_RECOVERABLE( d->handle->madStream->error ) ) {
0331                 if( d->handle->madStream->error == MAD_ERROR_BUFLEN )
0332                     continue;
0333                 else if( d->handle->madStream->error != MAD_ERROR_BADDATAPTR ) {
0334                     qDebug() << "(K3bMadDecoder) Seeking: recoverable mad error ("
0335                              << mad_stream_errorstr(d->handle->madStream) << ")" << Qt::endl;
0336                     continue;
0337                 }
0338                 else {
0339                     qDebug() << "(K3bMadDecoder) Seeking: ignoring ("
0340                              << mad_stream_errorstr(d->handle->madStream) << ")" << Qt::endl;
0341                 }
0342             }
0343             else
0344                 return false;
0345         }
0346 
0347         if( i == frameReservoirProtect )  // synth only the last frame (Rob said so ;)
0348             mad_synth_frame( d->handle->madSynth, d->handle->madFrame );
0349 
0350         ++i;
0351     }
0352 
0353     return true;
0354 }
0355 
0356 
0357 QString K3bMadDecoder::fileType() const
0358 {
0359     switch( d->firstHeader.layer ) {
0360     case MAD_LAYER_I:
0361         return "MPEG1 Layer I";
0362     case MAD_LAYER_II:
0363         return "MPEG1 Layer II";
0364     case MAD_LAYER_III:
0365         return "MPEG1 Layer III";
0366     default:
0367         return "Mp3";
0368     }
0369 }
0370 
0371 QStringList K3bMadDecoder::supportedTechnicalInfos() const
0372 {
0373     return QString( i18n("Channels") + ';' +
0374                     i18n("Sampling Rate") + ';' +
0375                     i18n("Bitrate") + ';' +
0376                     i18n("Layer") + ';' +
0377                     i18n("Emphasis") + ';' +
0378                     i18n("Copyright") + ';' +
0379                     i18n("Original") + ';' +
0380                     i18n("CRC") ).split( ';' );
0381 }
0382 
0383 
0384 QString K3bMadDecoder::technicalInfo( const QString& name ) const
0385 {
0386     if( name == i18n("Channels") ) {
0387         switch( d->firstHeader.mode ) {
0388         case MAD_MODE_SINGLE_CHANNEL:
0389             return i18n("Mono");
0390         case MAD_MODE_DUAL_CHANNEL:
0391             return i18n("Dual");
0392         case MAD_MODE_JOINT_STEREO:
0393             return i18n("Joint Stereo");
0394         case MAD_MODE_STEREO:
0395             return i18n("Stereo");
0396         default:
0397             return "?";
0398         }
0399     }
0400     else if( name == i18n("Sampling Rate") )
0401         return i18n("%1 Hz",d->firstHeader.samplerate);
0402     else if( name == i18n("Bitrate") ) {
0403         if( d->vbr )
0404             return i18n("VBR");
0405         else
0406             return i18n("%1 bps",d->firstHeader.bitrate);
0407     }
0408     else if(  name == i18n("Layer") ){
0409         switch( d->firstHeader.layer ) {
0410         case MAD_LAYER_I:
0411             return "I";
0412         case MAD_LAYER_II:
0413             return "II";
0414         case MAD_LAYER_III:
0415             return "III";
0416         default:
0417             return "?";
0418         }
0419     }
0420     else if( name == i18n("Emphasis") ) {
0421         switch( d->firstHeader.emphasis ) {
0422         case MAD_EMPHASIS_NONE:
0423             return i18n("None");
0424         case MAD_EMPHASIS_50_15_US:
0425             return i18n("50/15 ms");
0426         case MAD_EMPHASIS_CCITT_J_17:
0427             return i18n("CCITT J.17");
0428         default:
0429             return i18n("Unknown");
0430         }
0431     }
0432     else if( name == i18n("Copyright") )
0433         return ( d->firstHeader.flags & MAD_FLAG_COPYRIGHT ? i18n("Yes") : i18n("No") );
0434     else if( name == i18n("Original") )
0435         return ( d->firstHeader.flags & MAD_FLAG_ORIGINAL ? i18n("Yes") : i18n("No") );
0436     else if( name == i18n("CRC") )
0437         return ( d->firstHeader.flags & MAD_FLAG_PROTECTION ? i18n("Yes") : i18n("No") );
0438     else
0439         return QString();
0440 }
0441 
0442 
0443 K3bMadDecoderFactory::K3bMadDecoderFactory( QObject* parent, const QVariantList& )
0444     : K3b::AudioDecoderFactory( parent )
0445 {
0446 }
0447 
0448 
0449 K3bMadDecoderFactory::~K3bMadDecoderFactory()
0450 {
0451 }
0452 
0453 
0454 K3b::AudioDecoder* K3bMadDecoderFactory::createDecoder( QObject* parent) const
0455 {
0456     return new K3bMadDecoder( parent );
0457 }
0458 
0459 
0460 bool K3bMadDecoderFactory::canDecode( const QUrl& url )
0461 {
0462     //
0463     // HACK:
0464     //
0465     // I am simply no good at this and this detection code is no good as well
0466     // It always takes waves for mp3 files so we introduce this hack to
0467     // filter out wave files. :(
0468     //
0469     QFile f( url.toLocalFile() );
0470     if( !f.open( QIODevice::ReadOnly ) )
0471         return false;
0472     char buffer[12];
0473     if( f.read( buffer, 12 ) != 12 )
0474         return false;
0475     if( !qstrncmp( buffer, "RIFF", 4 ) &&
0476         !qstrncmp( buffer + 8, "WAVE", 4 ) )
0477         return false;
0478     f.close();
0479 
0480 
0481     K3bMad handle;
0482     if( !handle.open( url.toLocalFile() ) )
0483         return false;
0484 
0485     handle.skipTag();
0486     if( !handle.seekFirstHeader() )
0487         return false;
0488 
0489     if( handle.findNextHeader() ) {
0490         int c = MAD_NCHANNELS( &handle.madFrame->header );
0491         int layer = handle.madFrame->header.layer;
0492         unsigned int s = handle.madFrame->header.samplerate;
0493 
0494         //
0495         // find 4 more mp3 headers (random value since 2 was not enough)
0496         // This way we get most of the mp3 files while sorting out
0497         // for example wave files.
0498         //
0499         int cnt = 1;
0500         while( handle.findNextHeader() ) {
0501             // compare the found headers
0502             if( MAD_NCHANNELS( &handle.madFrame->header ) == c &&
0503                 handle.madFrame->header.layer == layer &&
0504                 handle.madFrame->header.samplerate == s ) {
0505                 // only support layer III for now since otherwise some wave files
0506                 // are taken for layer I
0507                 if( ++cnt >= 5 ) {
0508                     qDebug() << "(K3bMadDecoder) valid mpeg 1 layer " << layer
0509                              << " file with " << c << " channels and a samplerate of "
0510                              << s << Qt::endl;
0511                     return ( layer == MAD_LAYER_III );
0512                 }
0513             }
0514             else
0515                 break;
0516         }
0517     }
0518 
0519     qDebug() << "(K3bMadDecoder) unsupported format: " << url.toLocalFile();
0520 
0521     return false;
0522 }
0523 
0524 #include "k3bmaddecoder.moc"
0525 
0526 #include "moc_k3bmaddecoder.cpp"