2 * MP3/MPlayer plugin to VDR (C++)
4 * (C) 2001-2007 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 // --- cSongInfo ---------------------------------------------------------------
58 cSongInfo::cSongInfo(void)
64 cSongInfo::~cSongInfo()
69 void cSongInfo::Clear(void)
71 Frames=0; Total=-1; DecoderID=0;
72 SampleFreq=Channels=Bitrate=MaxBitrate=ChMode=-1;
74 free(Artist); Artist=0;
81 void cSongInfo::Set(cSongInfo *si)
86 SampleFreq=si->SampleFreq;
87 Channels=si->Channels;
89 MaxBitrate=si->MaxBitrate;
92 Title=si->Title ? strdup(si->Title):0;
93 Artist=si->Artist ? strdup(si->Artist):0;
94 Album=si->Album ? strdup(si->Album):0;
95 if(si->Level>0.0) { // preserve old level
99 DecoderID=si->DecoderID;
102 void cSongInfo::FakeTitle(const char *filename, const char *extention)
104 // if no title, try to build a reasonable from the filename
105 if(!Title && filename) {
106 char *s=rindex(filename,'/');
110 strreplace(Title,'_',' ');
111 if(extention) { // strip given extention
112 int l=strlen(Title)-strlen(extention);
113 if(l>0 && !strcasecmp(Title+l,extention)) Title[l]=0;
115 else { // strip any extention
117 if(s && *s=='.' && strlen(s)<=5) *s=0;
119 d(printf("mp3: faking title '%s' from filename '%s'\n",Title,filename))
124 // --- cFileInfo ---------------------------------------------------------------
126 cFileInfo::cFileInfo(void)
128 Filename=FsID=0; Clear();
131 cFileInfo::cFileInfo(const char *Name)
133 Filename=FsID=0; Clear();
134 Filename=strdup(Name);
137 cFileInfo::~cFileInfo()
142 void cFileInfo::Clear(void)
144 free(Filename); Filename=0;
146 Filesize=0; CTime=0; FsType=0; removable=-1;
150 bool cFileInfo::Removable(void)
152 if(removable<0 && Filename) {
153 cFileSource *src=MP3Sources.FindSource(Filename);
154 if(src) removable=src->NeedsMount();
157 return (removable!=0);
160 void cFileInfo::Set(cFileInfo *fi)
163 Filename=fi->Filename ? strdup(fi->Filename):0;
164 FsID=fi->FsID ? strdup(fi->FsID):0;
165 Filesize=fi->Filesize;
170 bool cFileInfo::FileInfo(bool log)
174 if(!stat64(Filename,&ds)) {
175 if(S_ISREG(ds.st_mode)) {
179 if(!statfs64(Filename,&sfs)) {
180 if(Removable()) asprintf(&FsID,"%llx:%llx",sfs.f_blocks,sfs.f_files);
183 else if(errno!=ENOSYS && log) { esyslog("ERROR: can't statfs %s: %s",Filename,strerror(errno)); }
187 if(FsType==CDFS_MAGIC) CTime=0; // CDFS returns mount time as ctime
192 else if(log) { esyslog("ERROR: %s is not a regular file",Filename); }
194 else if(log) { esyslog("ERROR: can't stat %s: %s",Filename,strerror(errno)); }
199 // --- cDecoders ---------------------------------------------------------------
201 cDecoder *cDecoders::FindDecoder(cFileObj *Obj)
203 const char *full=Obj->FullPath();
207 if(fi.FileInfo(false) && (dat=InfoCache.Search(&fi))) {
209 //d(printf("mp3: found DecoderID '%s' for %s from cache\n",cDecoders::ID2Str(dat->DecoderID),Filename))
210 switch(dat->DecoderID) {
211 case DEC_MP3: decoder=new cMP3Decoder(full); break;
212 case DEC_MP3S: decoder=new cMP3StreamDecoder(full); break;
214 case DEC_SND: decoder=new cSndDecoder(full); break;
216 #ifdef HAVE_VORBISFILE
217 case DEC_OGG: decoder=new cOggDecoder(full); break;
219 default: esyslog("ERROR: bad DecoderID '%s' from info cache: %s",cDecoders::ID2Str(dat->DecoderID),full); break;
225 if(!decoder || !decoder->Valid()) {
226 // no decoder in cache or cached decoder doesn't matches.
227 // try to detect a decoder
229 delete decoder; decoder=0;
232 decoder=new cSndDecoder(full);
233 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
236 #ifdef HAVE_VORBISFILE
238 decoder=new cOggDecoder(full);
239 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
243 decoder=new cMP3StreamDecoder(full);
244 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
247 decoder=new cMP3Decoder(full);
248 if(!decoder || !decoder->Valid()) { delete decoder; decoder=0; }
250 if(!decoder) esyslog("ERROR: no decoder found for %s",Obj->Name());
255 const char *cDecoders::ID2Str(int id)
258 case DEC_MP3: return DEC_MP3_STR;
259 case DEC_MP3S: return DEC_MP3S_STR;
260 case DEC_SND: return DEC_SND_STR;
261 case DEC_OGG: return DEC_OGG_STR;
266 int cDecoders::Str2ID(const char *str)
268 if (!strcmp(str,DEC_MP3_STR )) return DEC_MP3;
269 else if(!strcmp(str,DEC_MP3S_STR)) return DEC_MP3S;
270 else if(!strcmp(str,DEC_SND_STR )) return DEC_SND;
271 else if(!strcmp(str,DEC_OGG_STR )) return DEC_OGG;
275 // --- cDecoder ----------------------------------------------------------------
277 cDecoder::cDecoder(const char *Filename)
279 filename=strdup(Filename);
280 locked=0; urgentLock=playing=false;
283 cDecoder::~cDecoder()
288 void cDecoder::Lock(bool urgent)
291 if(urgent && locked) urgentLock=true; // signal other locks to release quickly
293 locklock.Unlock(); // don't hold the "locklock" when locking "lock", may cause a deadlock
298 void cDecoder::Unlock(void)
306 bool cDecoder::TryLock(void)
310 if(!locked && !playing) {
318 // --- cCacheData -----------------------------------------------------
320 cCacheData::cCacheData(void)
325 void cCacheData::Touch(void)
330 #define SECS_PER_DAY (24*60*60)
332 bool cCacheData::Purge(void)
335 //XXX does this realy made sense?
336 //if(touch+CACHEPURGETIMEOUT*SECS_PER_DAY < now) {
337 // d(printf("cache: purged: timeout %s\n",Filename))
340 if(touch+CACHEPURGETIMEOUT*SECS_PER_DAY/10 < now) {
341 if(!Removable()) { // is this a permant source?
342 struct stat64 ds; // does the file exists? if not, purge
343 if(stat64(Filename,&ds) || !S_ISREG(ds.st_mode) || access(Filename,R_OK)) {
344 d(printf("cache: purged: file not found %s\n",Filename))
352 bool cCacheData::Upgrade(void)
355 if(DecoderID==DEC_SND || (Title && startswith(Title,"track-")))
356 return false; // Trash older SND entries (incomplete)
359 if(!FsID) FsID=strdup("old"); // Dummy entry, will be replaced in InfoCache::Search()
361 else { free(FsID); FsID=0; }
364 Touch(); // Touch entry
366 if(version<3 && !Title) {
367 FakeTitle(Filename,".mp3"); // Fake title
369 if(version<2 && Bitrate<=0) {
370 return false; // Trash entry without bitrate
375 void cCacheData::Create(cFileInfo *fi, cSongInfo *si)
379 hash=MakeHash(Filename);
383 bool cCacheData::Save(FILE *f)
385 fprintf(f,"##BEGIN\n"
401 Filename,Filesize,CTime,touch,CACHE_VERSION,Frames,Total,SampleFreq,Channels,Bitrate,MaxBitrate,ChMode,Year,Level,Peak);
402 if(Title) fprintf(f,"Title=%s\n" ,Title);
403 if(Artist) fprintf(f,"Artist=%s\n" ,Artist);
404 if(Album) fprintf(f,"Album=%s\n" ,Album);
405 if(DecoderID) fprintf(f,"DecoderID=%s\n",cDecoders::ID2Str(DecoderID));
406 if(FsID) fprintf(f,"FsID=%s\n" ,FsID);
407 fprintf(f,"##END\n");
411 bool cCacheData::Load(FILE *f)
413 static const char delimiters[] = { "=\n" };
418 while(fgets(buf,sizeof(buf),f)) {
420 char *name =strtok_r(buf ,delimiters,&ptrptr);
421 char *value=strtok_r(0,delimiters,&ptrptr);
423 if(!strcasecmp(name,"##END")) break;
425 if (!strcasecmp(name,"Filename")) Filename =strdup(value);
426 else if(!strcasecmp(name,"Filesize") ||
427 !strcasecmp(name,"Size")) Filesize =atoll(value);
428 else if(!strcasecmp(name,"FsID")) FsID =strdup(value);
429 else if(!strcasecmp(name,"Timestamp")) CTime =atol(value);
430 else if(!strcasecmp(name,"Touch")) touch =atol(value);
431 else if(!strcasecmp(name,"Version")) version =atoi(value);
432 else if(!strcasecmp(name,"DecoderID")) DecoderID =cDecoders::Str2ID(value);
433 else if(!strcasecmp(name,"Frames")) Frames =atoi(value);
434 else if(!strcasecmp(name,"Total")) Total =atoi(value);
435 else if(!strcasecmp(name,"SampleFreq")) SampleFreq=atoi(value);
436 else if(!strcasecmp(name,"Channels")) Channels =atoi(value);
437 else if(!strcasecmp(name,"Bitrate")) Bitrate =atoi(value);
438 else if(!strcasecmp(name,"MaxBitrate")) MaxBitrate=atoi(value);
439 else if(!strcasecmp(name,"ChMode")) ChMode =atoi(value);
440 else if(!strcasecmp(name,"Year")) Year =atoi(value);
441 else if(!strcasecmp(name,"Title")) Title =strdup(value);
442 else if(!strcasecmp(name,"Artist")) Artist =strdup(value);
443 else if(!strcasecmp(name,"Album")) Album =strdup(value);
444 else if(!strcasecmp(name,"Level")) Level =atof(value);
445 else if(!strcasecmp(name,"Peak")) Peak =atof(value);
446 else d(printf("cache: ignoring bad token '%s' from cache file\n",name))
451 if(ferror(f) || !Filename) return false;
452 hash=MakeHash(Filename);
456 // --- cInfoCache ----------------------------------------------------
458 cInfoCache::cInfoCache(void)
460 lasttime=0; modified=false;
461 lastpurge=time(0)-(50*60);
464 void cInfoCache::Shutdown(void)
470 void cInfoCache::Cache(cSongInfo *info, cFileInfo *file)
473 cCacheData *dat=Search(file);
475 dat->Create(file,info);
478 d(printf("cache: updating infos for %s\n",file->Filename))
482 dat->Create(file,info);
484 d(printf("cache: caching infos for %s\n",file->Filename))
489 cCacheData *cInfoCache::Search(cFileInfo *file)
491 int hash=MakeHash(file->Filename);
493 cCacheData *dat=FirstEntry(hash);
495 if(dat->hash==hash && !strcmp(dat->Filename,file->Filename) && dat->Filesize==file->Filesize) {
497 if(file->FsID && dat->FsID && !strcmp(dat->FsID,"old")) { // duplicate FsID for old entries
498 dat->FsID=strdup(file->FsID);
499 dat->Touch(); Modified();
500 //d(printf("adding FsID for %s\n",dat->Filename))
503 if((!file->FsID && !dat->FsID) || (file->FsID && dat->FsID && !strcmp(dat->FsID,file->FsID))) {
504 //d(printf("cache: found cache entry for %s\n",dat->Filename))
505 dat->Touch(); Modified();
506 if(dat->CTime!=file->CTime) {
507 d(printf("cache: ctime differs, removing from cache: %s\n",dat->Filename))
508 DelEntry(dat); dat=0;
514 dat=(cCacheData *)dat->Next();
520 void cInfoCache::AddEntry(cCacheData *dat)
522 lists[dat->hash%CACHELINES].Add(dat);
526 void cInfoCache::DelEntry(cCacheData *dat)
529 lists[dat->hash%CACHELINES].Del(dat);
533 cCacheData *cInfoCache::FirstEntry(int hash)
535 return lists[hash%CACHELINES].First();
538 bool cInfoCache::Purge(void)
541 if(now-lastpurge>(60*60)) {
542 isyslog("cleaning up id3 cache");
549 void cInfoCache::Action(void)
551 d(printf("cache: id3 cache purge thread started (pid=%d)\n",getpid()))
554 for(int i=0,n=0 ; i<CACHELINES && Running(); i++) {
555 cCacheData *dat=FirstEntry(i);
556 while(dat && Running()) {
557 cCacheData *ndat=(cCacheData *)dat->Next();
558 if(dat->Purge()) DelEntry(dat);
563 lock.Unlock(); lock.Lock(); // give concurrent thread an access chance
564 if(lastmod) dat=FirstEntry(i); // restart line, if cache changed meanwhile
569 d(printf("cache: id3 cache purge thread ended (pid=%d)\n",getpid()))
572 char *cInfoCache::CacheFile(void)
574 return AddPath(cachedir?cachedir:VideoDirectory,CACHEFILENAME);
577 void cInfoCache::Save(bool force)
579 if(modified && (force || (!Purge() && time(0)>lasttime))) {
580 char *name=CacheFile();
585 fprintf(f,"## This is a generated file. DO NOT EDIT!!\n"
586 "## This file will be OVERWRITTEN WITHOUT WARNING!!\n");
587 for(int i=0 ; i<CACHELINES ; i++) {
588 cCacheData *dat=FirstEntry(i);
590 if(!dat->Save(f)) { i=CACHELINES+1; break; }
591 dat=(cCacheData *)dat->Next();
596 modified=false; lasttime=time(0)+CACHESAVETIMEOUT;
597 d(printf("cache: saved cache to file\n"))
602 void cInfoCache::Load(void)
604 char *name=CacheFile();
605 if(access(name,F_OK)==0) {
606 isyslog("loading id3 cache from %s",name);
607 FILE *f=fopen(name,"r");
612 for(int i=0 ; i<CACHELINES ; i++) lists[i].Clear();
613 while(fgets(buf,sizeof(buf),f)) {
614 if(!strcasecmp(buf,"##BEGIN\n")) {
615 cCacheData *dat=new cCacheData;
617 if(dat->version!=CACHE_VERSION) {
618 if(dat->Upgrade()) mod=true;
619 else { delete dat; continue; }
626 esyslog("ERROR: failed to load id3 cache");
634 modified=false; if(mod) Modified();
636 else LOG_ERROR_STR(name);