Chris@148: 
Chris@148: /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*-  vi:set ts=8 sts=4 sw=4: */
Chris@148: 
Chris@148: /*
Chris@148:     Sonic Visualiser
Chris@148:     An audio file viewer and annotation editor.
Chris@148:     Centre for Digital Music, Queen Mary, University of London.
Chris@148:     This file copyright 2006 Chris Cannam.
Chris@148:     
Chris@148:     This program is free software; you can redistribute it and/or
Chris@148:     modify it under the terms of the GNU General Public License as
Chris@148:     published by the Free Software Foundation; either version 2 of the
Chris@148:     License, or (at your option) any later version.  See the file
Chris@148:     COPYING included with this distribution for more information.
Chris@148: */
Chris@148: 
Chris@148: #ifdef HAVE_MAD
Chris@148: 
Chris@148: #include "MP3FileReader.h"
Chris@392: #include "base/ProgressReporter.h"
Chris@357: 
Chris@150: #include "system/System.h"
Chris@148: 
Chris@148: #include <sys/types.h>
Chris@148: #include <sys/stat.h>
Chris@148: #include <fcntl.h>
Chris@148: 
Chris@148: #include <iostream>
Chris@148: 
Chris@405: #include <cstdlib>
Chris@405: 
Chris@271: #ifdef HAVE_ID3TAG
Chris@271: #include <id3tag.h>
Chris@271: #endif
Chris@273: #define DEBUG_ID3TAG 1
Chris@271: 
Chris@186: #include <QFileInfo>
Chris@148: 
Chris@317: MP3FileReader::MP3FileReader(FileSource source, DecodeMode decodeMode, 
Chris@392:                              CacheMode mode, size_t targetRate,
Chris@392:                              ProgressReporter *reporter) :
Chris@297:     CodedAudioFileReader(mode, targetRate),
Chris@316:     m_source(source),
Chris@316:     m_path(source.getLocalFilename()),
Chris@264:     m_decodeThread(0)
Chris@148: {
Chris@148:     m_channelCount = 0;
Chris@297:     m_fileRate = 0;
Chris@148:     m_fileSize = 0;
Chris@148:     m_bitrateNum = 0;
Chris@148:     m_bitrateDenom = 0;
Chris@148:     m_cancelled = false;
Chris@265:     m_completion = 0;
Chris@263:     m_done = false;
Chris@392:     m_reporter = reporter;
Chris@148: 
Chris@148:     struct stat stat;
Chris@316:     if (::stat(m_path.toLocal8Bit().data(), &stat) == -1 || stat.st_size == 0) {
Chris@316: 	m_error = QString("File %1 does not exist.").arg(m_path);
Chris@148: 	return;
Chris@148:     }
Chris@148: 
Chris@148:     m_fileSize = stat.st_size;
Chris@148: 
Chris@229:     int fd = -1;
Chris@316:     if ((fd = ::open(m_path.toLocal8Bit().data(), O_RDONLY
Chris@231: #ifdef _WIN32
Chris@231:                      | O_BINARY
Chris@231: #endif
Chris@231:                      , 0)) < 0) {
Chris@316: 	m_error = QString("Failed to open file %1 for reading.").arg(m_path);
Chris@148: 	return;
Chris@148:     }	
Chris@148: 
Chris@263:     m_filebuffer = 0;
Chris@297:     m_samplebuffer = 0;
Chris@297:     m_samplebuffersize = 0;
Chris@148: 
Chris@148:     try {
Chris@263:         m_filebuffer = new unsigned char[m_fileSize];
Chris@148:     } catch (...) {
Chris@290:         m_error = QString("Out of memory");
Chris@148:         ::close(fd);
Chris@148: 	return;
Chris@148:     }
Chris@148:     
Chris@229:     ssize_t sz = 0;
Chris@229:     size_t offset = 0;
Chris@229:     while (offset < m_fileSize) {
Chris@263:         sz = ::read(fd, m_filebuffer + offset, m_fileSize - offset);
Chris@229:         if (sz < 0) {
Chris@290:             m_error = QString("Read error for file %1 (after %2 bytes)")
Chris@316:                 .arg(m_path).arg(offset);
Chris@263:             delete[] m_filebuffer;
Chris@229:             ::close(fd);
Chris@229:             return;
Chris@230:         } else if (sz == 0) {
Chris@231:             std::cerr << QString("MP3FileReader::MP3FileReader: Warning: reached EOF after only %1 of %2 bytes")
Chris@231:                 .arg(offset).arg(m_fileSize).toStdString() << std::endl;
Chris@231:             m_fileSize = offset;
Chris@230:             break;
Chris@229:         }
Chris@229:         offset += sz;
Chris@148:     }
Chris@148: 
Chris@148:     ::close(fd);
Chris@148: 
Chris@271:     loadTags();
Chris@271: 
Chris@263:     if (decodeMode == DecodeAtOnce) {
Chris@263: 
Chris@392:         if (m_reporter) {
Chris@392:             connect(m_reporter, SIGNAL(cancelled()), this, SLOT(cancelled()));
Chris@392:             m_reporter->setMessage
Chris@392:                 (tr("Decoding %1...").arg(QFileInfo(m_path).fileName()));
Chris@327:         }
Chris@148: 
Chris@263:         if (!decode(m_filebuffer, m_fileSize)) {
Chris@316:             m_error = QString("Failed to decode file %1.").arg(m_path);
Chris@263:         }
Chris@263:         
Chris@263:         delete[] m_filebuffer;
Chris@263:         m_filebuffer = 0;
Chris@148: 
Chris@263:         if (isDecodeCacheInitialised()) finishDecodeCache();
Chris@398:         endSerialised();
Chris@263: 
Chris@392:     } else {
Chris@263: 
Chris@392:         if (m_reporter) m_reporter->setProgress(100);
Chris@263: 
Chris@263:         m_decodeThread = new DecodeThread(this);
Chris@263:         m_decodeThread->start();
Chris@263: 
Chris@386:         while ((m_channelCount == 0 || m_fileRate == 0 || m_sampleRate == 0)
Chris@386:                && !m_done) {
Chris@263:             usleep(10);
Chris@263:         }
Chris@386:         
Chris@386:         std::cerr << "MP3FileReader ctor: exiting with file rate = " << m_fileRate << std::endl;
Chris@148:     }
Chris@148: }
Chris@148: 
Chris@148: MP3FileReader::~MP3FileReader()
Chris@148: {
Chris@263:     if (m_decodeThread) {
Chris@265:         m_cancelled = true;
Chris@263:         m_decodeThread->wait();
Chris@263:         delete m_decodeThread;
Chris@263:     }
Chris@148: }
Chris@148: 
Chris@263: void
Chris@392: MP3FileReader::cancelled()
Chris@392: {
Chris@392:     m_cancelled = true;
Chris@392: }
Chris@392: 
Chris@392: void
Chris@271: MP3FileReader::loadTags()
Chris@271: {
Chris@271:     m_title = "";
Chris@271: 
Chris@271: #ifdef HAVE_ID3TAG
Chris@271: 
Chris@290:     id3_file *file = id3_file_open(m_path.toLocal8Bit().data(),
Chris@271:                                    ID3_FILE_MODE_READONLY);
Chris@271:     if (!file) return;
Chris@271: 
Chris@273:     // We can do this a lot more elegantly, but we'll leave that for
Chris@273:     // when we implement support for more than just the one tag!
Chris@273:     
Chris@271:     id3_tag *tag = id3_file_tag(file);
Chris@273:     if (!tag) {
Chris@273: #ifdef DEBUG_ID3TAG
Chris@273:         std::cerr << "MP3FileReader::loadTags: No ID3 tag found" << std::endl;
Chris@273: #endif
Chris@273:         id3_file_close(file);
Chris@273:         return;
Chris@271:     }
Chris@271: 
Chris@333:     m_title = loadTag(tag, "TIT2"); // work title
Chris@333:     if (m_title == "") m_title = loadTag(tag, "TIT1");
Chris@273: 
Chris@333:     m_maker = loadTag(tag, "TPE1"); // "lead artist"
Chris@333:     if (m_maker == "") m_maker = loadTag(tag, "TPE2");
Chris@273: 
Chris@271:     id3_file_close(file);
Chris@273: 
Chris@273: #else
Chris@273: #ifdef DEBUG_ID3TAG
Chris@273:     std::cerr << "MP3FileReader::loadTags: ID3 tag support not compiled in"
Chris@273:               << std::endl;
Chris@271: #endif
Chris@273: #endif
Chris@333: }
Chris@273: 
Chris@333: QString
Chris@333: MP3FileReader::loadTag(void *vtag, const char *name)
Chris@333: {
Chris@333: #ifdef HAVE_ID3TAG
Chris@333:     id3_tag *tag = (id3_tag *)vtag;
Chris@333: 
Chris@333:     id3_frame *frame = id3_tag_findframe(tag, name, 0);
Chris@333:     if (!frame) {
Chris@333: #ifdef DEBUG_ID3TAG
Chris@333:         std::cerr << "MP3FileReader::loadTags: No \"" << name << "\" in ID3 tag" << std::endl;
Chris@333: #endif
Chris@333:         return "";
Chris@333:     }
Chris@333:         
Chris@333:     if (frame->nfields < 2) {
Chris@333:         std::cerr << "MP3FileReader::loadTags: WARNING: Not enough fields (" << frame->nfields << ") for \"" << name << "\" in ID3 tag" << std::endl;
Chris@333:         return "";
Chris@333:     }
Chris@333: 
Chris@333:     unsigned int nstrings = id3_field_getnstrings(&frame->fields[1]);
Chris@333:     if (nstrings == 0) {
Chris@333: #ifdef DEBUG_ID3TAG
Chris@348:         std::cerr << "MP3FileReader::loadTags: No strings for \"" << name << "\" in ID3 tag" << std::endl;
Chris@333: #endif
Chris@333:         return "";
Chris@333:     }
Chris@333: 
Chris@333:     id3_ucs4_t const *ustr = id3_field_getstrings(&frame->fields[1], 0);
Chris@333:     if (!ustr) {
Chris@333: #ifdef DEBUG_ID3TAG
Chris@333:         std::cerr << "MP3FileReader::loadTags: Invalid or absent data for \"" << name << "\" in ID3 tag" << std::endl;
Chris@333: #endif
Chris@333:         return "";
Chris@333:     }
Chris@333:         
Chris@333:     id3_utf8_t *u8str = id3_ucs4_utf8duplicate(ustr);
Chris@333:     if (!u8str) {
Chris@333:         std::cerr << "MP3FileReader::loadTags: ERROR: Internal error: Failed to convert UCS4 to UTF8 in ID3 title" << std::endl;
Chris@333:         return "";
Chris@333:     }
Chris@333:         
Chris@333:     QString rv = QString::fromUtf8((const char *)u8str);
Chris@333:     free(u8str);
Chris@334: 
Chris@334: #ifdef DEBUG_ID3TAG
Chris@334: 	std::cerr << "MP3FileReader::loadTags: tag \"" << name << "\" -> \""
Chris@334: 	<< rv.toStdString() << "\"" << std::endl;
Chris@334: #endif
Chris@334: 
Chris@334: 
Chris@333:     return rv;
Chris@333: 
Chris@333: #else
Chris@333:     return "";
Chris@333: #endif
Chris@271: }
Chris@271: 
Chris@271: void
Chris@263: MP3FileReader::DecodeThread::run()
Chris@263: {
Chris@263:     if (!m_reader->decode(m_reader->m_filebuffer, m_reader->m_fileSize)) {
Chris@290:         m_reader->m_error = QString("Failed to decode file %1.").arg(m_reader->m_path);
Chris@263:     }
Chris@263: 
Chris@263:     delete[] m_reader->m_filebuffer;
Chris@263:     m_reader->m_filebuffer = 0;
Chris@297: 
Chris@297:     if (m_reader->m_samplebuffer) {
Chris@297:         for (size_t c = 0; c < m_reader->m_channelCount; ++c) {
Chris@297:             delete[] m_reader->m_samplebuffer[c];
Chris@297:         }
Chris@297:         delete[] m_reader->m_samplebuffer;
Chris@297:         m_reader->m_samplebuffer = 0;
Chris@297:     }
Chris@297: 
Chris@263:     if (m_reader->isDecodeCacheInitialised()) m_reader->finishDecodeCache();
Chris@263: 
Chris@263:     m_reader->m_done = true;
Chris@265:     m_reader->m_completion = 100;
Chris@297: 
Chris@297:     m_reader->endSerialised();
Chris@263: } 
Chris@263: 
Chris@148: bool
Chris@148: MP3FileReader::decode(void *mm, size_t sz)
Chris@148: {
Chris@148:     DecoderData data;
Chris@148:     struct mad_decoder decoder;
Chris@148: 
Chris@148:     data.start = (unsigned char const *)mm;
Chris@148:     data.length = (unsigned long)sz;
Chris@148:     data.reader = this;
Chris@148: 
Chris@148:     mad_decoder_init(&decoder, &data, input, 0, 0, output, error, 0);
Chris@148:     mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
Chris@148:     mad_decoder_finish(&decoder);
Chris@148: 
Chris@263:     m_done = true;
Chris@148:     return true;
Chris@148: }
Chris@148: 
Chris@148: enum mad_flow
Chris@148: MP3FileReader::input(void *dp, struct mad_stream *stream)
Chris@148: {
Chris@148:     DecoderData *data = (DecoderData *)dp;
Chris@148: 
Chris@148:     if (!data->length) return MAD_FLOW_STOP;
Chris@348: 
Chris@348:     unsigned char const *start = data->start;
Chris@348:     unsigned long length = data->length;
Chris@348: 
Chris@348: #ifdef HAVE_ID3TAG
Chris@348:     if (length > ID3_TAG_QUERYSIZE) {
Chris@348:         int taglen = id3_tag_query(start, ID3_TAG_QUERYSIZE);
Chris@348:         if (taglen > 0) {
Chris@348: //            std::cerr << "ID3 tag length to skip: " << taglen << std::endl;
Chris@348:             start += taglen;
Chris@348:             length -= taglen;
Chris@348:         }
Chris@348:     }
Chris@348: #endif
Chris@348: 
Chris@348:     mad_stream_buffer(stream, start, length);
Chris@148:     data->length = 0;
Chris@148: 
Chris@148:     return MAD_FLOW_CONTINUE;
Chris@148: }
Chris@148: 
Chris@148: enum mad_flow
Chris@148: MP3FileReader::output(void *dp,
Chris@148: 		      struct mad_header const *header,
Chris@148: 		      struct mad_pcm *pcm)
Chris@148: {
Chris@148:     DecoderData *data = (DecoderData *)dp;
Chris@148:     return data->reader->accept(header, pcm);
Chris@148: }
Chris@148: 
Chris@148: enum mad_flow
Chris@148: MP3FileReader::accept(struct mad_header const *header,
Chris@148: 		      struct mad_pcm *pcm)
Chris@148: {
Chris@148:     int channels = pcm->channels;
Chris@148:     int frames = pcm->length;
Chris@148: 
Chris@148:     if (header) {
Chris@148:         m_bitrateNum += header->bitrate;
Chris@148:         m_bitrateDenom ++;
Chris@148:     }
Chris@148: 
Chris@148:     if (frames < 1) return MAD_FLOW_CONTINUE;
Chris@148: 
Chris@148:     if (m_channelCount == 0) {
Chris@297: 
Chris@297:         m_fileRate = pcm->samplerate;
Chris@148:         m_channelCount = channels;
Chris@297: 
Chris@297:         initialiseDecodeCache();
Chris@297: 
Chris@297:         if (m_cacheMode == CacheInTemporaryFile) {
Chris@357: //            m_completion = 1;
Chris@297:             std::cerr << "MP3FileReader::accept: channel count " << m_channelCount << ", file rate " << m_fileRate << ", about to start serialised section" << std::endl;
Chris@297:             startSerialised("MP3FileReader::Decode");
Chris@297:         }
Chris@148:     }
Chris@148:     
Chris@148:     if (m_bitrateDenom > 0) {
Chris@148:         double bitrate = m_bitrateNum / m_bitrateDenom;
Chris@148:         double duration = double(m_fileSize * 8) / bitrate;
Chris@148:         double elapsed = double(m_frameCount) / m_sampleRate;
Chris@375:         double percent = 100;
Chris@375:         if (duration > 0.0) percent = ((elapsed * 100.0) / duration);
Chris@357:         int p = int(percent);
Chris@357:         if (p < 1) p = 1;
Chris@357:         if (p > 99) p = 99;
Chris@392:         if (m_completion != p && m_reporter) {
Chris@357:             m_completion = p;
Chris@392:             m_reporter->setProgress(m_completion);
Chris@148:         }
Chris@148:     }
Chris@148: 
Chris@148:     if (m_cancelled) return MAD_FLOW_STOP;
Chris@148: 
Chris@148:     if (!isDecodeCacheInitialised()) {
Chris@148:         initialiseDecodeCache();
Chris@148:     }
Chris@148: 
Chris@297:     if (m_samplebuffersize < frames) {
Chris@297:         if (!m_samplebuffer) {
Chris@297:             m_samplebuffer = new float *[channels];
Chris@297:             for (int c = 0; c < channels; ++c) {
Chris@297:                 m_samplebuffer[c] = 0;
Chris@297:             }
Chris@297:         }
Chris@297:         for (int c = 0; c < channels; ++c) {
Chris@297:             delete[] m_samplebuffer[c];
Chris@297:             m_samplebuffer[c] = new float[frames];
Chris@297:         }
Chris@297:         m_samplebuffersize = frames;
Chris@297:     }
Chris@148: 
Chris@297:     int activeChannels = int(sizeof(pcm->samples) / sizeof(pcm->samples[0]));
Chris@297: 
Chris@297:     for (int ch = 0; ch < channels; ++ch) {
Chris@297: 
Chris@297:         for (int i = 0; i < frames; ++i) {
Chris@297: 
Chris@148: 	    mad_fixed_t sample = 0;
Chris@297: 	    if (ch < activeChannels) {
Chris@148: 		sample = pcm->samples[ch][i];
Chris@148: 	    }
Chris@148: 	    float fsample = float(sample) / float(MAD_F_ONE);
Chris@297:             
Chris@297:             m_samplebuffer[ch][i] = fsample;
Chris@148: 	}
Chris@148:     }
Chris@148: 
Chris@297:     addSamplesToDecodeCache(m_samplebuffer, frames);
Chris@148: 
Chris@148:     return MAD_FLOW_CONTINUE;
Chris@148: }
Chris@148: 
Chris@148: enum mad_flow
Chris@148: MP3FileReader::error(void *dp,
Chris@148: 		     struct mad_stream *stream,
Chris@148: 		     struct mad_frame *)
Chris@148: {
Chris@148:     DecoderData *data = (DecoderData *)dp;
Chris@148: 
Chris@405:     fprintf(stderr, "decoding error 0x%04x (%s) at byte offset %lu\n",
Chris@148: 	    stream->error, mad_stream_errorstr(stream),
Chris@405: 	    (unsigned long)(stream->this_frame - data->start));
Chris@148: 
Chris@148:     return MAD_FLOW_CONTINUE;
Chris@148: }
Chris@148: 
Chris@157: void
Chris@290: MP3FileReader::getSupportedExtensions(std::set<QString> &extensions)
Chris@157: {
Chris@157:     extensions.insert("mp3");
Chris@157: }
Chris@157: 
Chris@316: bool
Chris@316: MP3FileReader::supportsExtension(QString extension)
Chris@316: {
Chris@316:     std::set<QString> extensions;
Chris@316:     getSupportedExtensions(extensions);
Chris@316:     return (extensions.find(extension.toLower()) != extensions.end());
Chris@316: }
Chris@316: 
Chris@316: bool
Chris@316: MP3FileReader::supportsContentType(QString type)
Chris@316: {
Chris@316:     return (type == "audio/mpeg");
Chris@316: }
Chris@316: 
Chris@316: bool
Chris@317: MP3FileReader::supports(FileSource &source)
Chris@316: {
Chris@316:     return (supportsExtension(source.getExtension()) ||
Chris@316:             supportsContentType(source.getContentType()));
Chris@316: }
Chris@316: 
Chris@316: 
Chris@148: #endif