2 * MP3/MPlayer plugin to VDR (C++)
4 * (C) 2001-2009 Stefan Huelswitt <s.huelswitt@gmx.de>
6 * This code is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This code is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 * Or, point your browser to http://www.gnu.org/copyleft/gpl.html
28 #include <vdr/videodir.h>
34 #include "decoder-core.h"
35 #include "decoder-mp3.h"
36 #include "decoder-mp3-stream.h"
37 #include "decoder-snd.h"
38 #include "decoder-ogg.h"
40 #define CACHEFILENAME "id3info.cache"
41 #define CACHESAVETIMEOUT 120 // secs
42 #define CACHEPURGETIMEOUT 120 // days
44 extern cFileSources MP3Sources;
49 int MakeHashBuff(const char *buff, int len)
52 while(len--) h=(h*13 + *buff++) & 0x7ff;
56 // --- cStrConv ----------------------------------------------------------------
58 class cStrConv : private cMutex {
62 cStrConv(void):toSys("UTF-8",cCharSetConv::SystemCharacterTable()) {}
63 char *ToSys(char *from);
66 static cStrConv *strconv;
68 char *cStrConv::ToSys(char *from)
72 const char *r=toSys.Convert(from);
85 // --- cSongInfo ---------------------------------------------------------------
87 cSongInfo::cSongInfo(void)
93 cSongInfo::~cSongInfo()
98 void cSongInfo::Clear(void)
100 Frames=0; Total=-1; DecoderID=0;
101 SampleFreq=Channels=Bitrate=MaxBitrate=ChMode=-1;
102 free(Title); Title=0;
103 free(Artist); Artist=0;
104 free(Album); Album=0;
107 infoDone=false; utf8clean=true;
110 void cSongInfo::Set(cSongInfo *si, bool update)
112 if(!update || si->Utf8Clean()) {
114 Title=si->Title ? strdup(si->Title):0;
115 Artist=si->Artist ? strdup(si->Artist):0;
116 Album=si->Album ? strdup(si->Album):0;
117 utf8clean=si->utf8clean;
121 SampleFreq=si->SampleFreq;
122 Channels=si->Channels;
124 MaxBitrate=si->MaxBitrate;
127 if(si->Level>0.0) { // preserve old level
131 DecoderID=si->DecoderID;
135 void cSongInfo::FakeTitle(const char *filename, const char *extention)
137 // if no title, try to build a reasonable from the filename
138 if(!Title && filename) {
139 char *s=rindex(filename,'/');
143 strreplace(Title,'_',' ');
144 if(extention) { // strip given extention
145 int l=strlen(Title)-strlen(extention);
146 if(l>0 && !strcasecmp(Title+l,extention)) Title[l]=0;
148 else { // strip any extention
150 if(s && *s=='.' && strlen(s)<=5) *s=0;
152 d(printf("mp3: faking title '%s' from filename '%s'\n",Title,filename))
157 void cSongInfo::ConvertToSys(void)
159 if(cCharSetConv::SystemCharacterTable()) {
160 Title=strconv->ToSys(Title);
161 Artist=strconv->ToSys(Artist);
162 Album=strconv->ToSys(Album);
167 // --- cFileInfo ---------------------------------------------------------------
169 cFileInfo::cFileInfo(void)
171 Filename=FsID=0; Clear();
174 cFileInfo::cFileInfo(const char *Name)
176 Filename=FsID=0; Clear();
177 Filename=strdup(Name);
180 cFileInfo::~cFileInfo()
185 void cFileInfo::Clear(void)
187 free(Filename); Filename=0;
189 Filesize=0; CTime=0; FsType=0; removable=-1;
193 bool cFileInfo::Removable(void)
195 if(removable<0 && Filename) {
196 cFileSource *src=MP3Sources.FindSource(Filename);
197 if(src) removable=src->NeedsMount();
200 return (removable!=0);
203 void cFileInfo::Set(cFileInfo *fi)
206 Filename=fi->Filename ? strdup(fi->Filename):0;
207 FsID=fi->FsID ? strdup(fi->FsID):0;
208 Filesize=fi->Filesize;
213 bool cFileInfo::FileInfo(bool log)
217 if(!stat64(Filename,&ds)) {
218 if(S_ISREG(ds.st_mode)) {
222 if(!statfs64(Filename,&sfs)) {
223 if(Removable()) FsID=aprintf("%llx:%llx",sfs.f_blocks,sfs.f_files);
226 else if(errno!=ENOSYS && log) { esyslog("ERROR: can't statfs %s: %s",Filename,strerror(errno)); }
230 if(FsType==CDFS_MAGIC) CTime=0; // CDFS returns mount time as ctime
235 else if(log) { esyslog("ERROR: %s is not a regular file",Filename); }
237 else if(log) { esyslog("ERROR: can't stat %s: %s",Filename,strerror(errno)); }
242 // --- cDecoders ---------------------------------------------------------------
244 cDecoder *cDecoders::FindDecoder(cFileObj *Obj)
246 const char *full=Obj->FullPath();
250 if(fi.FileInfo(false) && (dat=InfoCache.Search(&fi))) {
252 //d(printf("mp3: found DecoderID '%s' for %s from cache\n",cDecoders::ID2Str(dat->DecoderID),Filename))
253 switch(dat->DecoderID) {
254 case DEC_MP3: decoder=new cMP3Decoder(full); break;
255 case DEC_MP3S: decoder=new cMP3StreamDecoder(full); break;
257 case DEC_SND: decoder=new cSndDecoder(full); break;
259 #ifdef HAVE_VORBISFILE
260 case DEC_OGG: decoder=new cOggDecoder(full); break;
262 default: esyslog("ERROR: bad DecoderID '%s' from info cache: %s",cDecoders::ID2Str(dat->DecoderID),full); break;
268 if(!decoder || !decoder->Valid()) {
269 // no decoder in cache or cached decoder doesn't matches.
270 // try to detect a decoder
272 delete decoder; decoder=0;
275 decoder=new cSndDecoder(full);
276 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
279 #ifdef HAVE_VORBISFILE
281 decoder=new cOggDecoder(full);
282 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
286 decoder=new cMP3StreamDecoder(full);
287 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
290 decoder=new cMP3Decoder(full);
291 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
293 if(!decoder) esyslog("ERROR: no decoder found for %s",Obj->Name());
298 const char *cDecoders::ID2Str(int id)
301 case DEC_MP3: return DEC_MP3_STR;
302 case DEC_MP3S: return DEC_MP3S_STR;
303 case DEC_SND: return DEC_SND_STR;
304 case DEC_OGG: return DEC_OGG_STR;
309 int cDecoders::Str2ID(const char *str)
311 if (!strcmp(str,DEC_MP3_STR )) return DEC_MP3;
312 else if(!strcmp(str,DEC_MP3S_STR)) return DEC_MP3S;
313 else if(!strcmp(str,DEC_SND_STR )) return DEC_SND;
314 else if(!strcmp(str,DEC_OGG_STR )) return DEC_OGG;
318 // --- cDecoder ----------------------------------------------------------------
320 cDecoder::cDecoder(const char *Filename)
322 filename=strdup(Filename);
323 locked=0; urgentLock=playing=false;
326 cDecoder::~cDecoder()
331 void cDecoder::Lock(bool urgent)
334 if(urgent && locked) urgentLock=true; // signal other locks to release quickly
336 locklock.Unlock(); // don't hold the "locklock" when locking "lock", may cause a deadlock
341 void cDecoder::Unlock(void)
349 bool cDecoder::TryLock(void)
353 if(!locked && !playing) {
361 // --- cCacheData -----------------------------------------------------
363 cCacheData::cCacheData(void)
368 void cCacheData::Touch(void)
373 #define SECS_PER_DAY (24*60*60)
375 bool cCacheData::Purge(void)
378 //XXX does this realy made sense?
379 //if(touch+CACHEPURGETIMEOUT*SECS_PER_DAY < now) {
380 // d(printf("cache: purged: timeout %s\n",Filename))
383 if(touch+CACHEPURGETIMEOUT*SECS_PER_DAY/10 < now) {
384 if(!Removable()) { // is this a permant source?
385 struct stat64 ds; // does the file exists? if not, purge
386 if(stat64(Filename,&ds) || !S_ISREG(ds.st_mode) || access(Filename,R_OK)) {
387 d(printf("cache: purged: file not found %s\n",Filename))
395 bool cCacheData::Check8bit(const char *str)
397 if(str) while(*str) if(*str++ & 0x80) return true;
401 bool cCacheData::Upgrade(void)
404 if(Check8bit(Title) || Check8bit(Artist) || Check8bit(Album))
405 return false; // Trash entries not 7bit clean
408 if(DecoderID==DEC_SND || (Title && startswith(Title,"track-")))
409 return false; // Trash older SND entries (incomplete)
412 if(!FsID) FsID=strdup("old"); // Dummy entry, will be replaced in InfoCache::Search()
414 else { free(FsID); FsID=0; }
417 Touch(); // Touch entry
419 if(version<3 && !Title) {
420 FakeTitle(Filename,".mp3"); // Fake title
422 if(version<2 && Bitrate<=0) {
423 return false; // Trash entry without bitrate
428 void cCacheData::Create(cFileInfo *fi, cSongInfo *si, bool update)
431 cSongInfo::Set(si,update);
432 hash=MakeHash(Filename);
436 bool cCacheData::Save(FILE *f)
438 fprintf(f,"##BEGIN\n"
454 Filename,Filesize,CTime,touch,CACHE_VERSION,Frames,Total,SampleFreq,Channels,Bitrate,MaxBitrate,ChMode,Year,Level,Peak);
455 if(Title) fprintf(f,"Title=%s\n" ,Title);
456 if(Artist) fprintf(f,"Artist=%s\n" ,Artist);
457 if(Album) fprintf(f,"Album=%s\n" ,Album);
458 if(DecoderID) fprintf(f,"DecoderID=%s\n",cDecoders::ID2Str(DecoderID));
459 if(FsID) fprintf(f,"FsID=%s\n" ,FsID);
460 fprintf(f,"##END\n");
464 bool cCacheData::Load(FILE *f)
466 static const char delimiters[] = { "=\n" };
471 while(fgets(buf,sizeof(buf),f)) {
473 char *name =strtok_r(buf ,delimiters,&ptrptr);
474 char *value=strtok_r(0,delimiters,&ptrptr);
476 if(!strcasecmp(name,"##END")) break;
478 if (!strcasecmp(name,"Filename")) Filename =strdup(value);
479 else if(!strcasecmp(name,"Filesize") ||
480 !strcasecmp(name,"Size")) Filesize =atoll(value);
481 else if(!strcasecmp(name,"FsID")) FsID =strdup(value);
482 else if(!strcasecmp(name,"Timestamp")) CTime =atol(value);
483 else if(!strcasecmp(name,"Touch")) touch =atol(value);
484 else if(!strcasecmp(name,"Version")) version =atoi(value);
485 else if(!strcasecmp(name,"DecoderID")) DecoderID =cDecoders::Str2ID(value);
486 else if(!strcasecmp(name,"Frames")) Frames =atoi(value);
487 else if(!strcasecmp(name,"Total")) Total =atoi(value);
488 else if(!strcasecmp(name,"SampleFreq")) SampleFreq=atoi(value);
489 else if(!strcasecmp(name,"Channels")) Channels =atoi(value);
490 else if(!strcasecmp(name,"Bitrate")) Bitrate =atoi(value);
491 else if(!strcasecmp(name,"MaxBitrate")) MaxBitrate=atoi(value);
492 else if(!strcasecmp(name,"ChMode")) ChMode =atoi(value);
493 else if(!strcasecmp(name,"Year")) Year =atoi(value);
494 else if(!strcasecmp(name,"Title")) Title =strdup(value);
495 else if(!strcasecmp(name,"Artist")) Artist =strdup(value);
496 else if(!strcasecmp(name,"Album")) Album =strdup(value);
497 else if(!strcasecmp(name,"Level")) Level =atof(value);
498 else if(!strcasecmp(name,"Peak")) Peak =atof(value);
499 else d(printf("cache: ignoring bad token '%s' from cache file\n",name))
504 if(ferror(f) || !Filename) return false;
505 hash=MakeHash(Filename);
509 // --- cInfoCache ----------------------------------------------------
511 cInfoCache::cInfoCache(void)
513 lasttime=0; modified=false;
514 lastpurge=time(0)-(50*60);
517 void cInfoCache::Shutdown(void)
523 void cInfoCache::Cache(cSongInfo *info, cFileInfo *file)
526 cCacheData *dat=Search(file);
528 dat->Create(file,info,true);
531 d(printf("cache: updating infos for %s\n",file->Filename))
535 dat->Create(file,info,false);
537 d(printf("cache: caching infos for %s\n",file->Filename))
542 cCacheData *cInfoCache::Search(cFileInfo *file)
544 int hash=MakeHash(file->Filename);
546 cCacheData *dat=FirstEntry(hash);
548 if(dat->hash==hash && !strcmp(dat->Filename,file->Filename) && dat->Filesize==file->Filesize) {
550 if(file->FsID && dat->FsID && !strcmp(dat->FsID,"old")) { // duplicate FsID for old entries
551 dat->FsID=strdup(file->FsID);
552 dat->Touch(); Modified();
553 //d(printf("adding FsID for %s\n",dat->Filename))
556 if((!file->FsID && !dat->FsID) || (file->FsID && dat->FsID && !strcmp(dat->FsID,file->FsID))) {
557 //d(printf("cache: found cache entry for %s\n",dat->Filename))
558 dat->Touch(); Modified();
559 if(dat->CTime!=file->CTime) {
560 d(printf("cache: ctime differs, removing from cache: %s\n",dat->Filename))
561 DelEntry(dat); dat=0;
567 dat=(cCacheData *)dat->Next();
573 void cInfoCache::AddEntry(cCacheData *dat)
575 lists[dat->hash%CACHELINES].Add(dat);
579 void cInfoCache::DelEntry(cCacheData *dat)
582 lists[dat->hash%CACHELINES].Del(dat);
586 cCacheData *cInfoCache::FirstEntry(int hash)
588 return lists[hash%CACHELINES].First();
591 bool cInfoCache::Purge(void)
594 if(now-lastpurge>(60*60)) {
595 isyslog("cleaning up id3 cache");
602 void cInfoCache::Action(void)
604 d(printf("cache: id3 cache purge thread started (pid=%d)\n",getpid()))
607 for(int i=0,n=0 ; i<CACHELINES && Running(); i++) {
608 cCacheData *dat=FirstEntry(i);
609 while(dat && Running()) {
610 cCacheData *ndat=(cCacheData *)dat->Next();
611 if(dat->Purge()) DelEntry(dat);
616 lock.Unlock(); lock.Lock(); // give concurrent thread an access chance
617 if(lastmod) dat=FirstEntry(i); // restart line, if cache changed meanwhile
622 d(printf("cache: id3 cache purge thread ended (pid=%d)\n",getpid()))
625 char *cInfoCache::CacheFile(void)
627 return AddPath(cachedir?cachedir:VideoDirectory,CACHEFILENAME);
630 void cInfoCache::Save(bool force)
632 if(modified && (force || (!Purge() && time(0)>lasttime))) {
633 char *name=CacheFile();
638 fprintf(f,"## This is a generated file. DO NOT EDIT!!\n"
639 "## This file will be OVERWRITTEN WITHOUT WARNING!!\n");
640 for(int i=0 ; i<CACHELINES ; i++) {
641 cCacheData *dat=FirstEntry(i);
643 if(!dat->Save(f)) { i=CACHELINES+1; break; }
644 dat=(cCacheData *)dat->Next();
649 modified=false; lasttime=time(0)+CACHESAVETIMEOUT;
650 d(printf("cache: saved cache to file\n"))
655 void cInfoCache::Load(void)
657 if(!strconv) strconv=new cStrConv;
659 char *name=CacheFile();
660 if(access(name,F_OK)==0) {
661 isyslog("loading id3 cache from %s",name);
662 FILE *f=fopen(name,"r");
667 for(int i=0 ; i<CACHELINES ; i++) lists[i].Clear();
668 while(fgets(buf,sizeof(buf),f)) {
669 if(!strcasecmp(buf,"##BEGIN\n")) {
670 cCacheData *dat=new cCacheData;
672 if(dat->version!=CACHE_VERSION) {
673 if(dat->Upgrade()) mod=true;
674 else { delete dat; continue; }
681 esyslog("ERROR: failed to load id3 cache");
689 modified=false; if(mod) Modified();
691 else LOG_ERROR_STR(name);