MythTV  0.26-pre
avfdecoder.cpp
Go to the documentation of this file.
00001 /*
00002     MythMusic libav* Decoder
00003     Originally written by Kevin Kuphal with contributions and updates from
00004     many others
00005 
00006     Special thanks to
00007        ffmpeg team for libavcodec and libavformat
00008        qemacs team for their av support which I used to understand the libraries
00009        getid3.sourceforget.net project for the ASF information used here
00010 
00011     This library decodes various media files into PCM data
00012     returned to the MythMusic output buffer.
00013 
00014     Revision History
00015         - Initial release
00016         - 1/9/2004 - Improved seek support
00017         - ?/?/2009 - Extended to support many more filetypes and bug fixes
00018         - ?/7/2010 - Add streaming support 
00019 */
00020 
00021 // QT headers
00022 #include <QObject>
00023 #include <QIODevice>
00024 #include <QFile>
00025 
00026 // Myth headers
00027 #include <mythconfig.h>
00028 #include <mythcontext.h>
00029 #include <audiooutput.h>
00030 #include <mythlogging.h>
00031 
00032 using namespace std;
00033 
00034 // Mythmusic Headers
00035 #include "avfdecoder.h"
00036 #include "metaioavfcomment.h"
00037 #include "metaioid3.h"
00038 #include "metaioflacvorbis.h"
00039 #include "metaiooggvorbis.h"
00040 #include "metaiomp4.h"
00041 #include "metaiowavpack.h"
00042 
00043 extern "C" {
00044 #include "libavformat/avio.h"
00045 }
00046 
00047 // size of the buffer used for streaming
00048 #define BUFFER_SIZE 8192
00049 
00050 // streaming callbacks
00051 static int ReadFunc(void *opaque, uint8_t *buf, int buf_size)
00052 {
00053     QIODevice *io = (QIODevice*)opaque;
00054 
00055     buf_size = min(buf_size, (int) io->bytesAvailable());
00056     return io->read((char*)buf, buf_size);
00057 }
00058 
00059 static int WriteFunc(void *opaque, uint8_t *buf, int buf_size)
00060 {
00061     (void)opaque;
00062     (void)buf;
00063     (void)buf_size;
00064     // we don't support writing to the steam
00065     return -1;
00066 }
00067 
00068 static int64_t SeekFunc(void *opaque, int64_t offset, int whence)
00069 {
00070     (void)opaque;
00071     (void)offset;
00072     (void)whence;
00073     // we dont support seeking while streaming
00074     return -1;
00075 }
00076 
00077 avfDecoder::avfDecoder(const QString &file, DecoderFactory *d, QIODevice *i,
00078                        AudioOutput *o) :
00079     Decoder(d, i, o),
00080     inited(false),              user_stop(false),
00081     stat(0),                    output_buf(NULL),
00082     output_at(0),               bks(0),
00083     bksFrames(0),               decodeBytes(0),
00084     finish(false),
00085     freq(0),                    bitrate(0),
00086     m_sampleFmt(FORMAT_NONE),   m_channels(0),
00087     seekTime(-1.0),             devicename(""),
00088     m_inputFormat(NULL),        m_inputContext(NULL),
00089     m_codec(NULL),
00090     m_audioDec(NULL),           m_inputIsFile(false),
00091     m_buffer(NULL),             m_byteIOContext(NULL),
00092     errcode(0)
00093 {
00094     setObjectName("avfDecoder");
00095     setFilename(file);
00096 }
00097 
00098 avfDecoder::~avfDecoder(void)
00099 {
00100     if (inited)
00101         deinit();
00102 }
00103 
00104 void avfDecoder::stop()
00105 {
00106     user_stop = true;
00107 }
00108 
00109 void avfDecoder::writeBlock()
00110 {
00111     while (!user_stop && seekTime <= 0)
00112     {
00113         if(output()->AddFrames(output_buf, bksFrames, -1))
00114         {
00115             output_at -= bks;
00116             memmove(output_buf, output_buf + bks, output_at);
00117             break;
00118         }
00119         else
00120             usleep(output()->GetAudioBufferedTime()<<9);
00121     }
00122 }
00123 
00124 bool avfDecoder::initialize()
00125 {
00126     inited = user_stop = finish = false;
00127     freq = bitrate = 0;
00128     stat = m_channels = 0;
00129     m_sampleFmt = FORMAT_NONE;
00130     seekTime = -1.0;
00131 
00132     // give up if we dont have an audiooutput set
00133     if (!output())
00134     {
00135         error("avfDecoder: initialise called with a NULL audiooutput"); 
00136         return false;
00137     }
00138 
00139     // register av codecs
00140     av_register_all();
00141 
00142     output()->PauseUntilBuffered();
00143 
00144     m_inputIsFile = !input()->isSequential();
00145 
00146     if (m_inputContext)
00147         avformat_free_context(m_inputContext);
00148 
00149     m_inputContext = avformat_alloc_context();
00150 
00151     // open device
00152     if (m_inputIsFile)
00153     {
00154         filename = ((QFile *)input())->fileName();
00155         LOG(VB_PLAYBACK, LOG_INFO,
00156             QString("avfDecoder: playing file %1").arg(filename));
00157     }
00158     else
00159     {
00160         // if the input is not a file then setup the buffer
00161         // and iocontext to stream from it
00162         m_buffer = (unsigned char*) av_malloc(BUFFER_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
00163         m_byteIOContext = avio_alloc_context(m_buffer, BUFFER_SIZE, 0, input(),
00164                                              &ReadFunc, &WriteFunc, &SeekFunc);
00165         filename = "stream";
00166 
00167         m_byteIOContext->seekable = 0;
00168 
00169         // probe the stream
00170         AVProbeData probe_data;
00171         probe_data.filename = filename.toLocal8Bit().constData();
00172         probe_data.buf_size = min(BUFFER_SIZE, (int) input()->bytesAvailable());
00173         probe_data.buf = m_buffer;
00174         input()->read((char*)probe_data.buf, probe_data.buf_size);
00175         m_inputFormat = av_probe_input_format(&probe_data, 1);
00176 
00177         if (!m_inputFormat)
00178         {
00179             error("Could not identify the stream type in "
00180                   "avfDecoder::initialize"); 
00181             deinit();
00182             return false;
00183         }
00184 
00185         LOG(VB_PLAYBACK, LOG_INFO,
00186             QString("avfDecoder: playing stream, format probed is: %1")
00187                 .arg(m_inputFormat->long_name));
00188     }
00189 
00190     // open the media file
00191     // this should populate the input context
00192     int err;
00193     if (m_inputIsFile)
00194         err = avformat_open_input(&m_inputContext,
00195                                   filename.toLocal8Bit().constData(),
00196                                   m_inputFormat, NULL);
00197     else
00198     {
00199         m_inputContext->pb = m_byteIOContext;
00200         err = avformat_open_input(&m_inputContext, "decoder",
00201                                       m_inputFormat, NULL);
00202     }
00203 
00204     if (err < 0)
00205     {
00206         LOG(VB_GENERAL, LOG_ERR,
00207             QString("Could not open file (%1)").arg(filename));
00208         LOG(VB_GENERAL, LOG_ERR, QString("AV decoder. Error: %1").arg(err));
00209         error(QString("Could not open file  (%1)").arg(filename) +
00210               QString("\nAV decoder. Error: %1").arg(err));
00211         deinit();
00212         return false;
00213     }
00214 
00215     // determine the stream format
00216     // this also populates information needed for metadata
00217     if (avformat_find_stream_info(m_inputContext, NULL) < 0)
00218     {
00219         error("Could not determine the stream format.");
00220         deinit();
00221         return false;
00222     }
00223 
00224     // Store the audio codec of the stream
00225     m_audioDec = m_inputContext->streams[0]->codec;
00226 
00227     // Store the input format of the context
00228     m_inputFormat = m_inputContext->iformat;
00229 
00230     // Prepare the decoding codec
00231     // The format is different than the codec
00232     // While we could get fed a WAV file, it could contain a number
00233     // of different codecs
00234     m_codec = avcodec_find_decoder(m_audioDec->codec_id);
00235     if (!m_codec)
00236     {
00237         error(QString("Could not find audio codec: %1")
00238                               .arg(m_audioDec->codec_id));
00239         deinit();
00240         return false;
00241     }
00242 
00243     if (avcodec_open2(m_audioDec, m_codec, NULL) < 0)
00244     {
00245         error(QString("Could not open audio codec: %1")
00246             .arg(m_audioDec->codec_id));
00247         deinit();
00248         return false;
00249     }
00250 
00251     freq = m_audioDec->sample_rate;
00252     m_channels = m_audioDec->channels;
00253 
00254     if (m_channels <= 0)
00255     {
00256         error(QString("AVCodecContext tells us %1 channels are "
00257                                       "available, this is bad, bailing.")
00258                                       .arg(m_channels));
00259         deinit();
00260         return false;
00261     }
00262 
00263     switch (m_audioDec->sample_fmt)
00264     {
00265         case AV_SAMPLE_FMT_U8:     m_sampleFmt = FORMAT_U8;    break;
00266         case AV_SAMPLE_FMT_S16:    m_sampleFmt = FORMAT_S16;   break;
00267         case AV_SAMPLE_FMT_FLT:    m_sampleFmt = FORMAT_FLT;   break;
00268         case AV_SAMPLE_FMT_DBL:    m_sampleFmt = FORMAT_NONE;  break;
00269         case AV_SAMPLE_FMT_S32:
00270             switch (m_audioDec->bits_per_raw_sample)
00271             {
00272                 case  0:    m_sampleFmt = FORMAT_S32;   break;
00273                 case 24:    m_sampleFmt = FORMAT_S24;   break;
00274                 case 32:    m_sampleFmt = FORMAT_S32;   break;
00275                 default:    m_sampleFmt = FORMAT_NONE;
00276             }
00277             break;
00278         default:            m_sampleFmt = FORMAT_NONE;
00279     }
00280 
00281     if (m_sampleFmt == FORMAT_NONE)
00282     {
00283         int bps = av_get_bytes_per_sample(m_audioDec->sample_fmt) << 3;
00284         if (m_audioDec->sample_fmt == AV_SAMPLE_FMT_S32 &&
00285             m_audioDec->bits_per_raw_sample)
00286         {
00287             bps = m_audioDec->bits_per_raw_sample;
00288         }
00289         error(QString("Error: Unsupported sample format "
00290                       "with %1 bits").arg(bps));
00291         return false;
00292     }
00293 
00294     const AudioSettings settings(m_sampleFmt, m_audioDec->channels,
00295                                     m_audioDec->codec_id,
00296                                     m_audioDec->sample_rate, false);
00297 
00298     output()->Reconfigure(settings);
00299     output()->SetSourceBitrate(m_audioDec->bit_rate);
00300 
00301     // 20ms worth
00302     bks = (freq * m_channels *
00303            AudioOutputSettings::SampleSize(m_sampleFmt)) / 50;
00304 
00305     bksFrames = freq / 50;
00306 
00307     // decode 8 bks worth of samples each time we need more
00308     decodeBytes = bks << 3;
00309 
00310     output_buf = (char *)av_malloc(decodeBytes +
00311                                    AVCODEC_MAX_AUDIO_FRAME_SIZE * 2);
00312     output_at = 0;
00313 
00314     inited = true;
00315     return true;
00316 }
00317 
00318 void avfDecoder::seek(double pos)
00319 {
00320     if (m_inputIsFile)
00321         seekTime = pos;
00322 }
00323 
00324 void avfDecoder::deinit()
00325 {
00326     inited = user_stop = finish = false;
00327     freq = bitrate = 0;
00328     stat = m_channels = 0;
00329     m_sampleFmt = FORMAT_NONE;
00330     setInput(0);
00331     setOutput(0);
00332 
00333     // Cleanup here
00334     if (m_inputContext)
00335     {
00336         avformat_close_input(&m_inputContext);
00337         m_inputContext = NULL;
00338     }
00339 
00340     if (output_buf)
00341         av_free(output_buf);
00342     output_buf = NULL;
00343 
00344     m_codec = NULL;
00345     m_audioDec = NULL;
00346     m_inputFormat = NULL;
00347 
00348     if (m_buffer)
00349     {
00350         av_free(m_buffer);
00351         m_buffer = NULL;
00352     }
00353 
00354     if (m_byteIOContext)
00355     {
00356         delete m_byteIOContext;
00357         m_byteIOContext = NULL;
00358     }
00359 }
00360 
00361 void avfDecoder::run()
00362 {
00363     RunProlog();
00364     if (!inited)
00365     {
00366         RunEpilog();
00367         return;
00368     }
00369 
00370     AVPacket pkt, tmp_pkt;
00371     AVFrame *frame = avcodec_alloc_frame();
00372     int data_size, dec_len;
00373     uint fill, total;
00374     // account for possible frame expansion in aobase (upmix, float conv)
00375     uint thresh = bks * 12 / AudioOutputSettings::SampleSize(m_sampleFmt);
00376 
00377     stat = DecoderEvent::Decoding;
00378     {
00379         DecoderEvent e((DecoderEvent::Type) stat);
00380         dispatch(e);
00381     }
00382 
00383     av_read_play(m_inputContext);
00384 
00385     while (!finish && !user_stop)
00386     {
00387         // Look to see if user has requested a seek
00388         if (seekTime >= 0.0)
00389         {
00390             LOG(VB_GENERAL, LOG_INFO, QString("avfdecoder.o: seek time %1")
00391                     .arg(seekTime));
00392 
00393             if (av_seek_frame(m_inputContext, -1,
00394                               (int64_t)(seekTime * AV_TIME_BASE), 0) < 0)
00395                 LOG(VB_GENERAL, LOG_ERR, "Error seeking");
00396 
00397             seekTime = -1.0;
00398         }
00399 
00400         // Do we need to decode more samples?
00401         if (output_at < bks)
00402         {
00403             while (output_at < decodeBytes &&
00404                    !finish && !user_stop && seekTime <= 0.0)
00405             {
00406                 // Read a packet from the input context
00407                 if (av_read_frame(m_inputContext, &pkt) < 0)
00408                 {
00409                     LOG(VB_GENERAL, LOG_ERR, "Read frame failed");
00410                     LOG(VB_FILE, LOG_ERR, ("... for file '" + filename) + "'");
00411                     finish = true;
00412                     break;
00413                 }
00414 
00415                 av_init_packet(&tmp_pkt);
00416                 tmp_pkt.data = pkt.data;
00417                 tmp_pkt.size = pkt.size;
00418 
00419                 while (tmp_pkt.size > 0 && !finish &&
00420                        !user_stop && seekTime <= 0.0)
00421                 {
00422                     // Decode the stream to the output codec
00423                     int got_frame = 0;
00424 
00425                     data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
00426                     dec_len = avcodec_decode_audio4(m_audioDec, frame,
00427                                                     &got_frame, &tmp_pkt);
00428                     if (dec_len < 0 || !got_frame)
00429                         break;
00430 
00431                     data_size = 
00432                         av_samples_get_buffer_size(NULL,
00433                                                    m_audioDec->channels,
00434                                                    frame->nb_samples,
00435                                                    m_audioDec->sample_fmt,
00436                                                    1);
00437                     // Copy the data to the output buffer
00438                     memcpy((char *)(output_buf + output_at), 
00439                            frame->extended_data[0], data_size);
00440 
00441                     // Increment the output pointer and count
00442                     output_at += data_size;
00443                     tmp_pkt.size -= dec_len;
00444                     tmp_pkt.data += dec_len;
00445                 }
00446 
00447                 av_free_packet(&pkt);
00448             }
00449         }
00450 
00451         if (!output())
00452             continue;
00453 
00454         // Wait until we need to decode or supply more samples
00455         while (!finish && !user_stop && seekTime <= 0.0)
00456         {
00457             output()->GetBufferStatus(fill, total);
00458             // Make sure we have decoded samples ready and that the
00459             // audiobuffer is reasonably populated
00460             if (fill < thresh<<3)
00461                 break;
00462             else
00463                 // Wait for half of the buffer to drain
00464                 usleep(output()->GetAudioBufferedTime()<<9);
00465         }
00466 
00467         // write a block if there's sufficient space for it
00468         if (!user_stop && output_at >= bks && fill <= total - thresh)
00469             writeBlock();
00470     }
00471 
00472     if (user_stop)
00473         inited = false;
00474 
00475     else if (output())
00476     {
00477         // Drain our buffer
00478         while (output_at >= bks)
00479             writeBlock();
00480 
00481         // Drain ao buffer
00482         output()->Drain();
00483     }
00484 
00485     if (finish)
00486         stat = DecoderEvent::Finished;
00487     else if (user_stop)
00488         stat = DecoderEvent::Stopped;
00489 
00490     {
00491         DecoderEvent e((DecoderEvent::Type) stat);
00492         dispatch(e);
00493     }
00494 
00495     av_free(frame);
00496 
00497     deinit();
00498     RunEpilog();
00499 }
00500 
00501 MetaIO* avfDecoder::doCreateTagger(void)
00502 {
00503     QString extension = filename.section('.', -1);
00504 
00505     if (extension == "mp3")
00506         return new MetaIOID3();
00507     else if (extension == "ogg" || extension == "oga")
00508         return new MetaIOOggVorbis();
00509     else if (extension == "flac")
00510     {
00511         MetaIOID3 *file = new MetaIOID3();
00512         if (file->TagExists(filename))
00513             return file;
00514         else
00515             return new MetaIOFLACVorbis();  
00516     }
00517     else if (extension == "m4a")
00518         return new MetaIOMP4();
00519     else if (extension == "wv")
00520         return new MetaIOWavPack();
00521     else
00522         return new MetaIOAVFComment();
00523 }
00524 
00525 bool avfDecoderFactory::supports(const QString &source) const
00526 {
00527     QStringList list = extension().split("|", QString::SkipEmptyParts);
00528     for (QStringList::const_iterator it = list.begin(); it != list.end(); ++it)
00529     {
00530         if (*it == source.right((*it).length()).toLower())
00531             return true;
00532     }
00533 
00534     return false;
00535 }
00536 
00537 const QString &avfDecoderFactory::extension() const
00538 {
00539     static QString ext(".mp3|.mp2|.ogg|.oga|.flac|.wma|.wav|.ac3|.oma|.omg|"
00540                        ".atp|.ra|.dts|.aac|.m4a|.aa3|.tta|.mka|.aiff|.swa|.wv");
00541     return ext;
00542 }
00543 
00544 const QString &avfDecoderFactory::description() const
00545 {
00546     static QString desc(QObject::tr("Internal Decoder"));
00547     return desc;
00548 }
00549 
00550 Decoder *avfDecoderFactory::create(const QString &file, QIODevice *input,
00551                                   AudioOutput *output, bool deletable)
00552 {
00553     if (deletable)
00554         return new avfDecoder(file, this, input, output);
00555 
00556     static avfDecoder *decoder = 0;
00557     if (!decoder)
00558     {
00559         decoder = new avfDecoder(file, this, input, output);
00560     }
00561     else
00562     {
00563         decoder->setInput(input);
00564         decoder->setOutput(output);
00565     }
00566 
00567     return decoder;
00568 }
00569 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends