mp3.c
author nathan
Wed, 04 Feb 2009 19:34:25 +0800
branchtrunk
changeset 24 0598c933ccae
parent 23 3b14b8aacaa0
child 25 887faebaba0a
permissions -rw-r--r--
replace fixed-sized buffers in OSD code
     1 /*
     2  * MP3/MPlayer plugin to VDR (C++)
     3  *
     4  * (C) 2001-2009 Stefan Huelswitt <s.huelswitt@gmx.de>
     5  *
     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.
    10  *
    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.
    15  *
    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
    20  */
    21 
    22 #include <stdlib.h>
    23 #include <getopt.h>
    24 #include <strings.h>
    25 #include <typeinfo>
    26 
    27 #include "common.h"
    28 
    29 #include <vdr/menuitems.h>
    30 #include <vdr/status.h>
    31 #include <vdr/plugin.h>
    32 #include <vdr/interface.h>
    33 #include <vdr/skins.h>
    34 
    35 #include "setup.h"
    36 #include "setup-mp3.h"
    37 #include "data-mp3.h"
    38 #include "data-src.h"
    39 #include "player-mp3.h"
    40 #include "menu.h"
    41 #include "menu-async.h"
    42 #include "decoder.h"
    43 #include "i18n.h"
    44 #include "version.h"
    45 #include "service.h"
    46 
    47 #ifdef DEBUG
    48 #include <mad.h>
    49 #endif
    50 
    51 const char *sourcesSub=0;
    52 cFileSources MP3Sources;
    53 
    54 static const char *plugin_name=0;
    55 const char *i18n_name=0;
    56 
    57 // --- cMenuSetupMP3 --------------------------------------------------------
    58 
    59 class cMenuSetupMP3 : public cMenuSetupPage {
    60 private:
    61   cMP3Setup data;
    62   //
    63   const char *cddb[3], *disp[2], *scan[3], *bgr[3];
    64   const char *aout[AUDIOOUTMODES];
    65   int amode, amodes[AUDIOOUTMODES];
    66 protected:
    67   virtual void Store(void);
    68 public:
    69   cMenuSetupMP3(void);
    70   };
    71 
    72 cMenuSetupMP3::cMenuSetupMP3(void)
    73 {
    74   static const char allowed[] = { "abcdefghijklmnopqrstuvwxyz0123456789-_" };
    75   int numModes=0;
    76   aout[numModes]=trVDR("DVB"); amodes[numModes]=AUDIOOUTMODE_DVB; numModes++;
    77 #ifdef WITH_OSS
    78   aout[numModes]=tr("OSS"); amodes[numModes]=AUDIOOUTMODE_OSS; numModes++;
    79 #endif
    80   data=MP3Setup;
    81   amode=0;
    82   for(int i=0; i<numModes; i++)
    83     if(amodes[i]==data.AudioOutMode) { amode=i; break; }
    84 
    85   SetSection(tr("MP3"));
    86   Add(new cMenuEditStraItem(tr("Setup.MP3$Audio output mode"),     &amode,numModes,aout));
    87   Add(new cMenuEditBoolItem(tr("Setup.MP3$Audio mode"),            &data.AudioMode, tr("Round"), tr("Dither")));
    88   Add(new cMenuEditBoolItem(tr("Setup.MP3$Use 48kHz mode only"),   &data.Only48kHz));
    89   disp[0]=tr("classic");
    90   disp[1]=tr("via skin");
    91   Add(new cMenuEditStraItem(tr("Setup.MP3$Replay display"),        &data.ReplayDisplay, 2, disp));
    92   Add(new cMenuEditIntItem( tr("Setup.MP3$Display mode"),          &data.DisplayMode, 1, 3));
    93   bgr[0]=tr("Black");
    94   bgr[1]=tr("Live");
    95   bgr[2]=tr("Images");
    96   Add(new cMenuEditStraItem(tr("Setup.MP3$Background mode"),       &data.BackgrMode, 3, bgr));
    97   Add(new cMenuEditBoolItem(tr("Setup.MP3$Initial loop mode"),     &data.InitLoopMode));
    98   Add(new cMenuEditBoolItem(tr("Setup.MP3$Initial shuffle mode"),  &data.InitShuffleMode));
    99   Add(new cMenuEditBoolItem(tr("Setup.MP3$Abort player at end of list"),&data.AbortAtEOL));
   100   scan[0]=tr("disabled");
   101   scan[1]=tr("ID3 only");
   102   scan[2]=tr("ID3 & Level");
   103   Add(new cMenuEditStraItem(tr("Setup.MP3$Background scan"),       &data.BgrScan, 3, scan));
   104   Add(new cMenuEditBoolItem(tr("Setup.MP3$Editor display mode"),   &data.EditorMode, tr("Filenames"), tr("ID3 names")));
   105   Add(new cMenuEditBoolItem(tr("Setup.MP3$Mainmenu mode"),         &data.MenuMode, tr("Playlists"), tr("Browser")));
   106   Add(new cMenuEditBoolItem(tr("Setup.MP3$Keep selection menu"),   &data.KeepSelect));
   107   Add(new cMenuEditBoolItem(tr("Setup.MP3$Title/Artist order"),    &data.TitleArtistOrder, tr("Normal"), tr("Reversed")));
   108   Add(new cMenuEditBoolItem(tr("Hide mainmenu entry"),             &data.HideMainMenu));
   109   Add(new cMenuEditIntItem( tr("Setup.MP3$Normalizer level"),      &data.TargetLevel, 0, MAX_TARGET_LEVEL));
   110   Add(new cMenuEditIntItem( tr("Setup.MP3$Limiter level"),         &data.LimiterLevel, MIN_LIMITER_LEVEL, 100));
   111   Add(new cMenuEditBoolItem(tr("Setup.MP3$Use HTTP proxy"),        &data.UseProxy));
   112   Add(new cMenuEditStrItem( tr("Setup.MP3$HTTP proxy host"),       data.ProxyHost,MAX_HOSTNAME,allowed));
   113   Add(new cMenuEditIntItem( tr("Setup.MP3$HTTP proxy port"),       &data.ProxyPort,1,65535));
   114   cddb[0]=tr("disabled");
   115   cddb[1]=tr("local only");
   116   cddb[2]=tr("local&remote");
   117   Add(new cMenuEditStraItem(tr("Setup.MP3$CDDB for CD-Audio"),     &data.UseCddb,3,cddb));
   118   Add(new cMenuEditStrItem( tr("Setup.MP3$CDDB server"),           data.CddbHost,MAX_HOSTNAME,allowed));
   119   Add(new cMenuEditIntItem( tr("Setup.MP3$CDDB port"),             &data.CddbPort,1,65535));
   120 }
   121 
   122 void cMenuSetupMP3::Store(void)
   123 {
   124   data.AudioOutMode=amodes[amode];
   125 
   126   MP3Setup=data;
   127   SetupStore("InitLoopMode",     MP3Setup.InitLoopMode   );
   128   SetupStore("InitShuffleMode",  MP3Setup.InitShuffleMode);
   129   SetupStore("AudioMode",        MP3Setup.AudioMode      );
   130   SetupStore("AudioOutMode",     MP3Setup.AudioOutMode   );
   131   SetupStore("BgrScan",          MP3Setup.BgrScan        );
   132   SetupStore("EditorMode",       MP3Setup.EditorMode     );
   133   SetupStore("DisplayMode",      MP3Setup.DisplayMode    );
   134   SetupStore("BackgrMode",       MP3Setup.BackgrMode     );
   135   SetupStore("MenuMode",         MP3Setup.MenuMode       );
   136   SetupStore("TargetLevel",      MP3Setup.TargetLevel    );
   137   SetupStore("LimiterLevel",     MP3Setup.LimiterLevel   );
   138   SetupStore("Only48kHz",        MP3Setup.Only48kHz      );
   139   SetupStore("UseProxy",         MP3Setup.UseProxy       );
   140   SetupStore("ProxyHost",        MP3Setup.ProxyHost      );
   141   SetupStore("ProxyPort",        MP3Setup.ProxyPort      );
   142   SetupStore("UseCddb",          MP3Setup.UseCddb        );
   143   SetupStore("CddbHost",         MP3Setup.CddbHost       );
   144   SetupStore("CddbPort",         MP3Setup.CddbPort       );
   145   SetupStore("AbortAtEOL",       MP3Setup.AbortAtEOL     );
   146   SetupStore("ReplayDisplay",    MP3Setup.ReplayDisplay  );
   147   SetupStore("HideMainMenu",     MP3Setup.HideMainMenu   );
   148   SetupStore("KeepSelect",       MP3Setup.KeepSelect     );
   149   SetupStore("TitleArtistOrder", MP3Setup.TitleArtistOrder);
   150 }
   151 
   152 // --- cAsyncStatus ------------------------------------------------------------
   153 
   154 cAsyncStatus asyncStatus;
   155 
   156 cAsyncStatus::cAsyncStatus(void)
   157 {
   158   text=0;
   159   changed=false;
   160 }
   161 
   162 cAsyncStatus::~cAsyncStatus()
   163 {
   164   free((void *)text);
   165 }
   166 
   167 void cAsyncStatus::Set(const char *Text)
   168 {
   169   Lock();
   170   free((void *)text);
   171   text=Text ? strdup(Text) : 0;
   172   changed=true;
   173   Unlock();
   174 }
   175 
   176 const char *cAsyncStatus::Begin(void)
   177 {
   178   Lock();
   179   return text;
   180 }
   181 
   182 void cAsyncStatus::Finish(void)
   183 {
   184   changed=false;
   185   Unlock();
   186 }
   187 
   188 // --- --------------------------------------------------------------------
   189 
   190 static cString TitleArtist(const char *title, const char *artist)
   191 {
   192   const char *fmt;
   193   if(artist && artist[0]) {
   194     if(MP3Setup.TitleArtistOrder) fmt="%2$s - %1$s";
   195     else  fmt="%s - %s";
   196     }
   197   else fmt="%s";
   198   return cString::sprintf(fmt,title,artist);
   199 }
   200 
   201 // --- cMP3Control --------------------------------------------------------
   202 
   203 #define MAXROWS 120
   204 
   205 class cMP3Control : public cControl {
   206 private:
   207   cOsd *osd;
   208   const cFont *font;
   209   cSkinDisplayReplay *disp;
   210   int bw, bh, bwc, fw, fh;
   211   //
   212   cMP3Player *player;
   213   bool visible, shown, bigwin, statusActive;
   214   time_t timeoutShow, greentime, oktime;
   215   cTimeMs lastkeytime;
   216   int number;
   217   bool selecting;
   218   //
   219   cMP3PlayInfo *lastMode;
   220   time_t fliptime, listtime;
   221   int hashlist[MAXROWS];
   222   int flip, flipint, top, rows;
   223   int lastIndex, lastTotal, lastTop;
   224   int framesPerSecond;
   225   //
   226   bool jumpactive, jumphide, jumpsecs;
   227   int jumpmm;
   228   //
   229   void ShowTimed(int Seconds=0);
   230   void ShowProgress(bool open=false, bool bigWin=false);
   231   void ShowStatus(bool force);
   232   void HideStatus(void);
   233   void DisplayInfo(const char *s=0);
   234   void JumpDisplay(void);
   235   void JumpProcess(eKeys Key);
   236   void Jump(void);
   237   void Stop(void);
   238   void Write(int x, int y, int w, const char *text, int fg=clrWhite, int bg=clrGray50);
   239   void Fill(int x, int y, int w, int h, int fg);
   240   inline void Flush(void);
   241 public:
   242   cMP3Control(void);
   243   virtual ~cMP3Control();
   244   virtual eOSState ProcessKey(eKeys Key);
   245   virtual void Show(void) { ShowTimed(); }
   246   virtual void Hide(void);
   247   bool Visible(void) { return visible; }
   248   static bool SetPlayList(cPlayList *plist);
   249   };
   250 
   251 cMP3Control::cMP3Control(void)
   252 :cControl(player=new cMP3Player)
   253 {
   254   visible=shown=bigwin=selecting=jumpactive=jumphide=statusActive=false;
   255   timeoutShow=greentime=oktime=0;
   256   number=0;
   257   lastMode=0;
   258   framesPerSecond=SecondsToFrames(1);
   259   osd=0; disp=0;
   260   font=cFont::GetFont(fontOsd);
   261   cStatus::MsgReplaying(this,"MP3",0,true);
   262 }
   263 
   264 cMP3Control::~cMP3Control()
   265 {
   266   delete lastMode;
   267   Hide();
   268   Stop();
   269 }
   270 
   271 void cMP3Control::Stop(void)
   272 {
   273   cStatus::MsgReplaying(this,0,0,false);
   274   delete player; player=0;
   275   mgr->Halt();
   276   mgr->Flush(); //XXX remove later
   277 }
   278 
   279 bool cMP3Control::SetPlayList(cPlayList *plist)
   280 {
   281   bool res;
   282   cControl *control=cControl::Control();
   283   // is there a running MP3 player?
   284   if(control && typeid(*control)==typeid(cMP3Control)) {
   285     // add songs to running playlist
   286     mgr->Add(plist);
   287     res=true;
   288     }
   289   else {
   290     mgr->Flush();
   291     mgr->Add(plist);
   292     cControl::Launch(new cMP3Control);
   293     res=false;
   294     }
   295   delete plist;
   296   return res;
   297 }
   298 
   299 void cMP3Control::ShowTimed(int Seconds)
   300 {
   301   if(!visible) {
   302     ShowProgress(true);
   303     timeoutShow=(Seconds>0) ? time(0)+Seconds : 0;
   304     }
   305 }
   306 
   307 void cMP3Control::Hide(void)
   308 {
   309   HideStatus();
   310   timeoutShow=0;
   311   if(visible) {
   312     delete osd; osd=0;
   313     delete disp; disp=0;
   314     visible=bigwin=false;
   315 #if APIVERSNUM >= 10500
   316     SetNeedsFastResponse(false);
   317 #else
   318     needsFastResponse=false;
   319 #endif
   320     }
   321 }
   322 
   323 void cMP3Control::ShowStatus(bool force)
   324 {
   325   if((asyncStatus.Changed() || (force && !statusActive)) && !jumpactive) {
   326     const char *text=asyncStatus.Begin();
   327     if(text) {
   328       if(MP3Setup.ReplayDisplay || !osd) {
   329         if(statusActive) Skins.Message(mtStatus,0);
   330         Skins.Message(mtStatus,text);
   331         }
   332       else {
   333         if(!statusActive) osd->SaveRegion(0,bh-2*fh,bw-1,bh-fh-1);
   334         osd->DrawText(0,bh-2*fh,text,clrBlack,clrCyan,font,bw,fh,taCenter);
   335         osd->Flush();
   336         }
   337       statusActive=true;
   338       }
   339     else
   340       HideStatus();
   341     asyncStatus.Finish();
   342     }
   343 }
   344 
   345 void cMP3Control::HideStatus(void)
   346 {
   347   if(statusActive) {
   348     if(MP3Setup.ReplayDisplay || !osd)
   349       Skins.Message(mtStatus,0);
   350     else {
   351       osd->RestoreRegion();
   352       osd->Flush();
   353       }
   354     }
   355   statusActive=false;
   356 }
   357 
   358 #define CTAB    11 // some tabbing values for the progress display
   359 #define CTAB2   5
   360 
   361 void cMP3Control::Write(int x, int y, int w, const char *text, int fg, int bg)
   362 {
   363   if(osd) {
   364     x*=fw; if(x<0) x+=bw;
   365     y*=fh; if(y<0) y+=bh;
   366     osd->DrawText(x,y,text,fg,bg,font,w*fw);
   367     }
   368 }
   369 
   370 void cMP3Control::Fill(int x, int y, int w, int h, int fg)
   371 {
   372   if(osd) {
   373     x*=fw; if(x<0) x+=bw;
   374     y*=fh; if(y<0) y+=bh;
   375     osd->DrawRectangle(x,y,x+w*fw-1,y+h*fh-1,fg);
   376     }
   377 }
   378 
   379 void cMP3Control::Flush(void)
   380 {
   381   if(MP3Setup.ReplayDisplay) Skins.Flush();
   382   else if(osd) osd->Flush();
   383 }
   384 
   385 void cMP3Control::ShowProgress(bool open, bool bigWin)
   386 {
   387   int index, total;
   388 
   389   if(player->GetIndex(index,total) && total>=0) {
   390     if(!visible && open) {
   391       HideStatus();
   392       if(MP3Setup.ReplayDisplay) {
   393         disp=Skins.Current()->DisplayReplay(false);
   394         if(!disp) return;
   395         bigWin=false;
   396         }
   397       else {
   398         int bt, bp;
   399         fw=font->Width(' ')*2;
   400         fh=font->Height();
   401         if(bigWin) {
   402           bw=Setup.OSDWidth;
   403           bh=Setup.OSDHeight;
   404           bt=0;
   405           bp=2*fh;
   406           rows=(bh-bp-fh/3)/fh;
   407           }
   408         else {
   409           bw=Setup.OSDWidth;
   410           bh=bp=2*fh;
   411           bt=Setup.OSDHeight-bh;
   412           rows=0;
   413           }
   414         bwc=bw/fw+1;
   415         //d(printf("mp3: bw=%d bh=%d bt=%d bp=%d bwc=%d rows=%d fw=%d fh=%d\n",
   416         //  bw,bh,bt,bp,bwc,rows,fw,fh))
   417         osd=cOsdProvider::NewOsd(Setup.OSDLeft,Setup.OSDTop+bt);
   418         if(!osd) return;
   419         if(bigWin) {
   420           tArea Areas[] = { { 0,0,bw-1,bh-bp-1,2 }, { 0,bh-bp,bw-1,bh-1,4 } };
   421           osd->SetAreas(Areas,sizeof(Areas)/sizeof(tArea));
   422           }
   423         else {
   424           tArea Areas[] = { { 0,0,bw-1,bh-1,4 } };
   425           osd->SetAreas(Areas,sizeof(Areas)/sizeof(tArea));
   426           }
   427         osd->DrawRectangle(0,0,bw-1,bh-1,clrGray50);
   428         osd->Flush();
   429         }
   430       ShowStatus(true);
   431       bigwin=bigWin;
   432       visible=true;
   433 #if APIVERSNUM >= 10500
   434       SetNeedsFastResponse(true);
   435 #else
   436       needsFastResponse=true;
   437 #endif
   438       fliptime=listtime=0; flipint=0; flip=-1; top=lastTop=-1; lastIndex=lastTotal=-1;
   439       delete lastMode; lastMode=0;
   440       }
   441 
   442     cMP3PlayInfo *mode=new cMP3PlayInfo;
   443     bool valid=mgr->Info(-1,mode);
   444     bool changed=(!lastMode || mode->Hash!=lastMode->Hash);
   445     if(changed) { d(printf("mp3-ctrl: mode change detected\n")) }
   446 
   447     if(valid) { // send progress to status monitor
   448       if(changed || mode->Loop!=lastMode->Loop || mode->Shuffle!=lastMode->Shuffle)
   449         cStatus::MsgReplaying(this,cString::sprintf("[%c%c] (%d/%d) %s",mode->Loop?'L':'.',mode->Shuffle?'S':'.',mode->Num,mode->MaxNum,*TitleArtist(mode->Title,mode->Artist)),mode->Filename[0]?mode->Filename:0,true);
   450       }
   451 
   452     if(visible) { // refresh the OSD progress display
   453       bool flush=false;
   454 
   455       if(MP3Setup.ReplayDisplay) {
   456         if(!statusActive) {
   457           if(total>0) disp->SetProgress(index,total);
   458           disp->SetCurrent(IndexToHMSF(index));
   459           disp->SetTotal(IndexToHMSF(total));
   460           bool Play, Forward;
   461           int Speed;
   462           if(GetReplayMode(Play,Forward,Speed)) 
   463             disp->SetMode(Play, Forward, Speed);
   464           flush=true;
   465           }
   466         }
   467       else {
   468         if(!selecting && changed && !statusActive) {
   469           Write(0,-2,CTAB,cString::sprintf("(%d/%d)",mode->Num,mode->MaxNum));
   470           flush=true;
   471           }
   472 
   473         if(!lastMode || mode->Loop!=lastMode->Loop) {
   474           if(mode->Loop) Write(-4,-1,0,"L",clrBlack,clrYellow);
   475           else Fill(-4,-1,2,1,clrGray50);
   476           flush=true;
   477           }
   478         if(!lastMode || mode->Shuffle!=lastMode->Shuffle) {
   479           if(mode->Shuffle) Write(-2,-1,0,"S",clrWhite,clrRed);
   480           else Fill(-2,-1,2,1,clrGray50);
   481           flush=true;
   482           }
   483 
   484         index/=framesPerSecond; total/=framesPerSecond;
   485         if(index!=lastIndex || total!=lastTotal) {
   486           if(total>0) {
   487             cProgressBar ProgressBar(bw-(CTAB+CTAB2)*fw,fh,index,total);
   488             osd->DrawBitmap(CTAB*fw,bh-fh,ProgressBar);
   489             }
   490           Write(0,-1,11,cString::sprintf(total?"%02d:%02d/%02d:%02d":"%02d:%02d",index/60,index%60,total/60,total%60));
   491           flush=true;
   492           }
   493         }
   494 
   495       if(!jumpactive) {
   496         bool doflip=false;
   497         if(MP3Setup.ReplayDisplay && (!lastMode || mode->Loop!=lastMode->Loop || mode->Shuffle!=lastMode->Shuffle))
   498           doflip=true;
   499         if(!valid || changed) {
   500           fliptime=time(0); flip=0;
   501 	  doflip=true;
   502 	  }
   503         else if(time(0)>fliptime+flipint) {
   504 	  fliptime=time(0);
   505 	  flip++; if(flip>=MP3Setup.DisplayMode) flip=0;
   506           doflip=true;
   507 	  }
   508         if(doflip) {
   509           cString buff;
   510           switch(flip) {
   511 	    default:
   512 	      flip=0;
   513 	      // fall through
   514 	    case 0:
   515 	      buff=TitleArtist(mode->Title,mode->Artist);
   516 	      flipint=6;
   517 	      break;
   518 	    case 1:
   519               if(mode->Album[0]) {
   520       	        buff=cString::sprintf(mode->Year>0?"from: %s (%d)":"from: %s",mode->Album,mode->Year);
   521 	        flipint=4;
   522 	        break;
   523 	        }
   524               flip++;
   525               // fall through
   526 	    case 2:
   527               if(mode->MaxBitrate>0)
   528                 buff=cString::sprintf("%.1f kHz, %d-%d kbps, %s",mode->SampleFreq/1000.0,mode->Bitrate/1000,mode->MaxBitrate/1000,mode->SMode);
   529               else
   530                 buff=cString::sprintf("%.1f kHz, %d kbps, %s",mode->SampleFreq/1000.0,mode->Bitrate/1000,mode->SMode);
   531 	      flipint=3;
   532 	      break;
   533 	    }
   534           if(MP3Setup.ReplayDisplay) {
   535             disp->SetTitle(cString::sprintf("[%c%c] (%d/%d) %s",mode->Loop?'L':'.',mode->Shuffle?'S':'.',mode->Num,mode->MaxNum,*buff));
   536             flush=true;
   537             }
   538           else {
   539             if(!statusActive) {
   540               DisplayInfo(buff);
   541               flush=true;
   542               }
   543             else { d(printf("mp3-ctrl: display info skip due to status active\n")) }
   544             }
   545           }
   546         }
   547 
   548       if(bigwin) {
   549         bool all=(top!=lastTop || changed);
   550         if(all || time(0)>listtime+2) {
   551           int num=(top>0 && mode->Num==lastMode->Num) ? top : mode->Num - rows/2;
   552           if(num+rows>mode->MaxNum) num=mode->MaxNum-rows+1;
   553           if(num<1) num=1;
   554           top=num;
   555           for(int i=0 ; i<rows && i<MAXROWS && num<=mode->MaxNum ; i++,num++) {
   556             cMP3PlayInfo pi;
   557             mgr->Info(num,&pi); if(!pi.Title[0]) break;
   558             cString buff=cString::sprintf("%d.\t%s",num,*TitleArtist(pi.Title,pi.Artist));
   559             int fg=clrWhite, bg=clrGray50;
   560             int hash=MakeHash(buff);
   561             if(num==mode->Num) { fg=clrBlack; bg=clrCyan; hash=(hash^77) + 23; }
   562             if(all || hash!=hashlist[i]) {
   563               char *s=rindex(buff,'\t');
   564               if(s) {
   565                 *s++=0;
   566                 Write(0,i,5,buff,fg,bg);
   567                 Write(5,i,bwc-5,s,fg,bg);
   568                 }
   569               else
   570                 Write(0,i,bwc,buff,fg,bg);
   571               flush=true;
   572               hashlist[i]=hash;
   573               }
   574             }
   575           listtime=time(0); lastTop=top;
   576           }
   577         }
   578 
   579       if(flush) Flush();
   580       }
   581 
   582     lastIndex=index; lastTotal=total;
   583     delete lastMode; lastMode=mode;
   584     }
   585 }
   586 
   587 void cMP3Control::DisplayInfo(const char *s)
   588 {
   589   if(s) Write(CTAB,-2,bwc-CTAB,s);
   590   else Fill(CTAB,-2,bwc-CTAB,1,clrGray50);
   591 }
   592 
   593 void cMP3Control::JumpDisplay(void)
   594 {
   595   char buf[64];
   596   const char *j=trVDR("Jump: "), u=jumpsecs?'s':'m';
   597   if(!jumpmm) sprintf(buf,"%s- %c",  j,u);
   598   else        sprintf(buf,"%s%d- %c",j,jumpmm,u);
   599   if(MP3Setup.ReplayDisplay) {
   600     disp->SetJump(buf);
   601     }
   602   else {
   603     DisplayInfo(buf);
   604     }
   605 }
   606 
   607 void cMP3Control::JumpProcess(eKeys Key)
   608 {
   609  int n=Key-k0, d=jumpsecs?1:60;
   610   switch (Key) {
   611     case k0 ... k9:
   612       if(jumpmm*10+n <= lastTotal/d) jumpmm=jumpmm*10+n;
   613       JumpDisplay();
   614       break;
   615     case kBlue:
   616       jumpsecs=!jumpsecs;
   617       JumpDisplay();
   618       break;
   619     case kPlay:
   620     case kUp:
   621       jumpmm-=lastIndex/d;
   622       // fall through
   623     case kFastRew:
   624     case kFastFwd:
   625     case kLeft:
   626     case kRight:
   627       player->SkipSeconds(jumpmm*d * ((Key==kLeft || Key==kFastRew) ? -1:1));
   628       // fall through
   629     default:
   630       jumpactive=false;
   631       break;
   632     }
   633 
   634   if(!jumpactive) {
   635     if(jumphide) Hide();
   636     else if(MP3Setup.ReplayDisplay) disp->SetJump(0);
   637     }
   638 }
   639 
   640 void cMP3Control::Jump(void)
   641 {
   642   jumpmm=0; jumphide=jumpsecs=false;
   643   if(!visible) {
   644     ShowTimed(); if(!visible) return;
   645     jumphide=true;
   646     }
   647   JumpDisplay();
   648   jumpactive=true; fliptime=0; flip=-1;
   649 }
   650 
   651 eOSState cMP3Control::ProcessKey(eKeys Key)
   652 {
   653   if(!player->Active()) return osEnd;
   654 
   655   if(timeoutShow && time(0)>timeoutShow) Hide();
   656   ShowProgress();
   657   ShowStatus(Key==kNone && !Skins.IsOpen());
   658 
   659   if(jumpactive && Key!=kNone) { JumpProcess(Key); return osContinue; }
   660 
   661   switch(Key) {
   662     case kUp:
   663     case kUp|k_Repeat:
   664     case kNext:
   665     case kNext|k_Repeat:    
   666       mgr->Next(); player->Play();
   667       break;
   668     case kDown:
   669     case kDown|k_Repeat:
   670     case kPrev:
   671     case kPrev|k_Repeat:
   672       if(!player->PrevCheck()) mgr->Prev();
   673       player->Play();
   674       break;
   675     case kLeft:
   676     case kLeft|k_Repeat:
   677       if(bigwin) {
   678         if(top>0) { top-=rows; if(top<1) top=1; }
   679         break;
   680         }
   681       // fall through
   682     case kFastRew:
   683     case kFastRew|k_Repeat:
   684       if(!player->IsStream()) player->SkipSeconds(-JUMPSIZE);
   685       break;
   686     case kRight:
   687     case kRight|k_Repeat:
   688       if(bigwin) {
   689         if(top>0) top+=rows;
   690         break;
   691         }
   692       // fall through
   693     case kFastFwd:
   694     case kFastFwd|k_Repeat:
   695       if(!player->IsStream()) player->SkipSeconds(JUMPSIZE);
   696       break;
   697     case kRed:
   698       if(!player->IsStream()) Jump();
   699       break;
   700     case kGreen:
   701       if(lastMode) {
   702         if(time(0)>greentime) {
   703           if(lastMode->Loop || (!lastMode->Loop && !lastMode->Shuffle)) mgr->ToggleLoop();
   704           if(lastMode->Shuffle) mgr->ToggleShuffle();
   705           }
   706         else {
   707           if(!lastMode->Loop) mgr->ToggleLoop();
   708           else if(!lastMode->Shuffle) mgr->ToggleShuffle();
   709           else mgr->ToggleLoop();
   710           }
   711         greentime=time(0)+MULTI_TIMEOUT;
   712         }
   713       break;
   714     case kPlay:
   715       player->Play();
   716       break;
   717     case kPause:
   718     case kYellow:
   719       if(!player->IsStream()) player->Pause();
   720       break;
   721     case kStop:
   722     case kBlue:
   723       Hide();
   724       Stop();
   725       return osEnd;
   726     case kBack:
   727       Hide();
   728       cRemote::CallPlugin(plugin_name);
   729       return osBack;
   730 
   731     case k0 ... k9:
   732       number=number*10+Key-k0;
   733       if(lastMode && number>0 && number<=lastMode->MaxNum) {
   734         if(!visible) ShowTimed(SELECTHIDE_TIMEOUT);
   735         else if(timeoutShow>0) timeoutShow=time(0)+SELECTHIDE_TIMEOUT;
   736         selecting=true; lastkeytime.Set(SELECT_TIMEOUT);
   737         char buf[32];
   738         if(MP3Setup.ReplayDisplay) {
   739           snprintf(buf,sizeof(buf),"%s%d-/%d",trVDR("Jump: "),number,lastMode->MaxNum);
   740           disp->SetJump(buf);
   741           }
   742         else {
   743           snprintf(buf,sizeof(buf),"(%d-/%d)",number,lastMode->MaxNum);
   744           Write(0,-2,CTAB,buf);
   745           }
   746         Flush();
   747         break;
   748         }
   749       number=0; lastkeytime.Set();
   750       // fall through
   751     case kNone:
   752       if(selecting && lastkeytime.TimedOut()) {
   753         if(number>0) { mgr->Goto(number); player->Play();  }
   754         if(lastMode) lastMode->Hash=-1;
   755         number=0; selecting=false;
   756         if(MP3Setup.ReplayDisplay && disp) disp->SetJump(0);
   757         }
   758       break;
   759     case kOk:
   760       if(time(0)>oktime || MP3Setup.ReplayDisplay) {
   761         visible ? Hide() : ShowTimed();
   762         }
   763       else {
   764         if(visible && !bigwin) { Hide(); ShowProgress(true,true); }
   765         else { Hide(); ShowTimed(); }
   766         }
   767       oktime=time(0)+MULTI_TIMEOUT;
   768       ShowStatus(true);
   769       break;
   770     default:
   771       return osUnknown;
   772     }
   773   return osContinue;
   774 }
   775 
   776 // --- cMenuID3Info ------------------------------------------------------------
   777 
   778 class cMenuID3Info : public cOsdMenu {
   779 private:
   780   cOsdItem *Item(const char *name, const char *text);
   781   cOsdItem *Item(const char *name, const char *format, const float num);
   782   void Build(cSongInfo *info, const char *name);
   783 public:
   784   cMenuID3Info(cSong *song);
   785   cMenuID3Info(cSongInfo *si, const char *name);
   786   virtual eOSState ProcessKey(eKeys Key);
   787   };
   788 
   789 cMenuID3Info::cMenuID3Info(cSong *song)
   790 :cOsdMenu(tr("ID3 information"),12)
   791 {
   792   Build(song->Info(),song->Name());
   793 }
   794 
   795 cMenuID3Info::cMenuID3Info(cSongInfo *si, const char *name)
   796 :cOsdMenu(tr("ID3 information"),12)
   797 {
   798   Build(si,name);
   799 }
   800 
   801 void cMenuID3Info::Build(cSongInfo *si, const char *name)
   802 {
   803   if(si) {
   804     Item(tr("Filename"),name);
   805     if(si->HasInfo() && si->Total>0) {
   806       char *buf=0;
   807       asprintf(&buf,"%02d:%02d",si->Total/60,si->Total%60);
   808       Item(tr("Length"),buf);
   809       free(buf);
   810       Item(tr("Title"),si->Title);
   811       Item(tr("Artist"),si->Artist);
   812       Item(tr("Album"),si->Album);
   813       Item(tr("Year"),0,(float)si->Year);
   814       Item(tr("Samplerate"),"%.1f kHz",si->SampleFreq/1000.0);
   815       Item(tr("Bitrate"),"%.f kbit/s",si->Bitrate/1000.0);
   816       Item(trVDR("Channels"),0,(float)si->Channels);
   817       }
   818     Display();
   819     }
   820 }
   821 
   822 cOsdItem *cMenuID3Info::Item(const char *name, const char *format, const float num)
   823 {
   824   cOsdItem *item;
   825   if(num>=0.0) {
   826     char *buf=0;
   827     asprintf(&buf,format?format:"%.f",num);
   828     item=Item(name,buf);
   829     free(buf);
   830     }
   831   else item=Item(name,"");
   832   return item;
   833 }
   834 
   835 cOsdItem *cMenuID3Info::Item(const char *name, const char *text)
   836 {
   837   char *buf=0;
   838   asprintf(&buf,"%s:\t%s",name,text?text:"");
   839   cOsdItem *item = new cOsdItem(buf,osBack);
   840   item->SetSelectable(false);
   841   free(buf);
   842   Add(item); return item;
   843 }
   844 
   845 eOSState cMenuID3Info::ProcessKey(eKeys Key)
   846 {
   847   eOSState state = cOsdMenu::ProcessKey(Key);
   848 
   849   if(state==osUnknown) {
   850      switch(Key) {
   851        case kRed:
   852        case kGreen:
   853        case kYellow:
   854        case kBlue:   return osContinue;
   855        case kMenu:   return osEnd;
   856        default: break;
   857        }
   858      }
   859   return state;
   860 }
   861 
   862 // --- cMenuInstantBrowse -------------------------------------------------------
   863 
   864 class cMenuInstantBrowse : public cMenuBrowse {
   865 private:
   866   const char *selecttext, *alltext;
   867   virtual void SetButtons(void);
   868   virtual eOSState ID3Info(void);
   869 public:
   870   cMenuInstantBrowse(cFileSource *Source, const char *Selecttext, const char *Alltext);
   871   virtual eOSState ProcessKey(eKeys Key);
   872   };
   873 
   874 cMenuInstantBrowse::cMenuInstantBrowse(cFileSource *Source, const char *Selecttext, const char *Alltext)
   875 :cMenuBrowse(Source,true,true,tr("Directory browser"),excl_br)
   876 {
   877   selecttext=Selecttext; alltext=Alltext;
   878   SetButtons();
   879 }
   880 
   881 void cMenuInstantBrowse::SetButtons(void)
   882 {
   883   SetHelp(selecttext, currentdir?tr("Parent"):0, currentdir?0:alltext, tr("ID3 info"));
   884   Display();
   885 }
   886 
   887 eOSState cMenuInstantBrowse::ID3Info(void)
   888 {
   889   cFileObj *item=CurrentItem();
   890   if(item && item->Type()==otFile) {
   891     cSong *song=new cSong(item);
   892     cSongInfo *si;
   893     if(song && (si=song->Info())) {
   894       AddSubMenu(new cMenuID3Info(si,item->Path()));
   895       }
   896     delete song;
   897     }
   898   return osContinue;
   899 }
   900 
   901 eOSState cMenuInstantBrowse::ProcessKey(eKeys Key)
   902 {
   903   eOSState state=cOsdMenu::ProcessKey(Key);
   904   if(state==osUnknown) {
   905      switch (Key) {
   906        case kYellow: lastselect=new cFileObj(source,0,0,otBase);
   907                      return osBack;
   908        default: break;
   909        }
   910      }
   911   if(state==osUnknown) state=cMenuBrowse::ProcessStdKey(Key,state);
   912   return state;
   913 }
   914 
   915 // --- cMenuPlayListItem -------------------------------------------------------
   916 
   917 class cMenuPlayListItem : public cOsdItem {
   918   private:
   919   bool showID3;
   920   cSong *song;
   921 public:
   922   cMenuPlayListItem(cSong *Song, bool showid3);
   923   cSong *Song(void) { return song; }
   924   virtual void Set(void);
   925   void Set(bool showid3);
   926   };
   927 
   928 cMenuPlayListItem::cMenuPlayListItem(cSong *Song, bool showid3)
   929 {
   930   song=Song;
   931   Set(showid3);
   932 }
   933 
   934 void cMenuPlayListItem::Set(bool showid3)
   935 {
   936   showID3=showid3;
   937   Set();
   938 }
   939 
   940 void cMenuPlayListItem::Set(void)
   941 {
   942   char *buffer=0;
   943   cSongInfo *si=song->Info(false);
   944   if(showID3 && !si) si=song->Info();
   945   if(showID3 && si && si->Title)
   946     asprintf(&buffer, "%d.\t%s",song->Index()+1,*TitleArtist(si->Title,si->Artist));
   947   else
   948     asprintf(&buffer, "%d.\t<%s>",song->Index()+1,song->Name());
   949   SetText(buffer,false);
   950 }
   951 
   952 // --- cMenuPlayList ------------------------------------------------------
   953 
   954 class cMenuPlayList : public cOsdMenu {
   955 private:
   956   cPlayList *playlist;
   957   bool browsing, showid3;
   958   void Buttons(void);
   959   void Refresh(bool all = false);
   960   void Add(void);
   961   virtual void Move(int From, int To);
   962   eOSState Remove(void);
   963   eOSState ShowID3(void);
   964   eOSState ID3Info(void);
   965 public:
   966   cMenuPlayList(cPlayList *Playlist);
   967   virtual eOSState ProcessKey(eKeys Key);
   968   };
   969 
   970 cMenuPlayList::cMenuPlayList(cPlayList *Playlist)
   971 :cOsdMenu(tr("Playlist editor"),4)
   972 {
   973   browsing=showid3=false;
   974   playlist=Playlist;
   975   if(MP3Setup.EditorMode) showid3=true;
   976 
   977   cSong *mp3 = playlist->First();
   978   while(mp3) {
   979     cOsdMenu::Add(new cMenuPlayListItem(mp3,showid3));
   980     mp3 = playlist->cList<cSong>::Next(mp3);
   981     }
   982   Buttons(); Display();
   983 }
   984 
   985 void cMenuPlayList::Buttons(void)
   986 {
   987   SetHelp(tr("Add"), showid3?tr("Filenames"):tr("ID3 names"), tr("Remove"), trVDR("Button$Mark"));
   988 }
   989 
   990 void cMenuPlayList::Refresh(bool all)
   991 {
   992   cMenuPlayListItem *cur=(cMenuPlayListItem *)((all || Count()<2) ? First() : Get(Current()));
   993   while(cur) {
   994     cur->Set(showid3);
   995     cur=(cMenuPlayListItem *)Next(cur);
   996     }
   997 }
   998 
   999 void cMenuPlayList::Add(void)
  1000 {
  1001   cFileObj *item=cMenuInstantBrowse::GetSelected();
  1002   if(item) {
  1003     Status(tr("Scanning directory..."));
  1004     cInstantPlayList *newpl=new cInstantPlayList(item);
  1005     if(newpl->Load()) {
  1006       if(newpl->Count()) {
  1007         if(newpl->Count()==1 || Interface->Confirm(tr("Add recursivly?"))) {
  1008           cSong *mp3=newpl->First();
  1009           while(mp3) {
  1010             cSong *n=new cSong(mp3);
  1011             if(Count()>0) {
  1012               cMenuPlayListItem *current=(cMenuPlayListItem *)Get(Current());
  1013               playlist->Add(n,current->Song());
  1014               cOsdMenu::Add(new cMenuPlayListItem(n,showid3),true,current);
  1015               }
  1016             else {
  1017               playlist->Add(n);
  1018               cOsdMenu::Add(new cMenuPlayListItem(n,showid3),true);
  1019               }
  1020             mp3=newpl->cList<cSong>::Next(mp3);
  1021             }
  1022           playlist->Save();
  1023           Refresh(); Display();
  1024           }
  1025         }
  1026       else Error(tr("Empty directory!"));
  1027       }
  1028     else Error(tr("Error scanning directory!"));
  1029     delete newpl;
  1030     Status(0);
  1031     }
  1032 }
  1033 
  1034 void cMenuPlayList::Move(int From, int To)
  1035 {
  1036   playlist->Move(From,To); playlist->Save();
  1037   cOsdMenu::Move(From,To);
  1038   Refresh(true); Display();
  1039 }
  1040 
  1041 eOSState cMenuPlayList::ShowID3(void)
  1042 {
  1043   showid3=!showid3;
  1044   Buttons(); Refresh(true); Display();
  1045   return osContinue;
  1046 }
  1047 
  1048 eOSState cMenuPlayList::ID3Info(void)
  1049 {
  1050   if(Count()>0) {
  1051     cMenuPlayListItem *current = (cMenuPlayListItem *)Get(Current());
  1052     AddSubMenu(new cMenuID3Info(current->Song()));
  1053     }
  1054   return osContinue;
  1055 }
  1056 
  1057 eOSState cMenuPlayList::Remove(void)
  1058 {
  1059   if(Count()>0) {
  1060     cMenuPlayListItem *current = (cMenuPlayListItem *)Get(Current());
  1061     if(Interface->Confirm(tr("Remove entry?"))) {
  1062       playlist->Del(current->Song()); playlist->Save();
  1063       cOsdMenu::Del(Current());
  1064       Refresh(); Display();
  1065       }
  1066     }
  1067   return osContinue;
  1068 }
  1069 
  1070 eOSState cMenuPlayList::ProcessKey(eKeys Key)
  1071 {
  1072   eOSState state = cOsdMenu::ProcessKey(Key);
  1073 
  1074   if(browsing && !HasSubMenu() && state==osContinue) { Add(); browsing=false; }
  1075 
  1076   if(state==osUnknown) {
  1077      switch(Key) {
  1078        case kOk:     return ID3Info();
  1079        case kRed:    browsing=true;
  1080                      return AddSubMenu(new cMenuInstantBrowse(MP3Sources.GetSource(),tr("Add"),tr("Add all")));
  1081        case kGreen:  return ShowID3();
  1082        case kYellow: return Remove();
  1083        case kBlue:   Mark(); return osContinue;
  1084        case kMenu:   return osEnd;
  1085        default: break;
  1086        }
  1087      }
  1088   return state;
  1089 }
  1090 
  1091 // --- cPlaylistRename --------------------------------------------------------
  1092 
  1093 class cPlaylistRename : public cOsdMenu {
  1094 private:
  1095   static char *newname;
  1096   const char *oldname;
  1097   char data[64];
  1098 public:
  1099   cPlaylistRename(const char *Oldname);
  1100   virtual eOSState ProcessKey(eKeys Key);
  1101   static const char *GetNewname(void) { return newname; }
  1102   };
  1103 
  1104 char *cPlaylistRename::newname = NULL;
  1105 
  1106 cPlaylistRename::cPlaylistRename(const char *Oldname)
  1107 :cOsdMenu(tr("Rename playlist"), 15)
  1108 {
  1109   free(newname); newname=0;
  1110 
  1111   oldname=Oldname;
  1112   char *buf=NULL;
  1113   asprintf(&buf,"%s\t%s",tr("Old name:"),oldname);
  1114   cOsdItem *old = new cOsdItem(buf,osContinue);
  1115   old->SetSelectable(false);
  1116   Add(old);
  1117   free(buf);
  1118 
  1119   data[0]=0;
  1120   Add(new cMenuEditStrItem( tr("New name"), data, sizeof(data)-1, tr(FileNameChars)),true);
  1121 }
  1122 
  1123 eOSState cPlaylistRename::ProcessKey(eKeys Key)
  1124 {
  1125   eOSState state = cOsdMenu::ProcessKey(Key);
  1126 
  1127   if (state == osUnknown) {
  1128      switch (Key) {
  1129        case kOk:     if(data[0] && strcmp(data,oldname)) newname=strdup(data);
  1130                      return osBack;
  1131        case kRed:
  1132        case kGreen:
  1133        case kYellow:
  1134        case kBlue:   return osContinue;
  1135        default: break;
  1136        }
  1137      }
  1138   return state;
  1139 }
  1140 
  1141 // --- cMenuMP3Item -----------------------------------------------------
  1142 
  1143 class cMenuMP3Item : public cOsdItem {
  1144   private:
  1145   cPlayList *playlist;
  1146   virtual void Set(void);
  1147 public:
  1148   cMenuMP3Item(cPlayList *PlayList);
  1149   cPlayList *List(void) { return playlist; }
  1150   };
  1151 
  1152 cMenuMP3Item::cMenuMP3Item(cPlayList *PlayList)
  1153 {
  1154   playlist=PlayList;
  1155   Set();
  1156 }
  1157 
  1158 void cMenuMP3Item::Set(void)
  1159 {
  1160   char *buffer=0;
  1161   asprintf(&buffer," %s",playlist->BaseName());
  1162   SetText(buffer,false);
  1163 }
  1164 
  1165 // --- cMenuMP3 --------------------------------------------------------
  1166 
  1167 class cMenuMP3 : public cOsdMenu {
  1168 private:
  1169   cPlayLists *lists;
  1170   bool renaming, sourcing, instanting;
  1171   int buttonnum;
  1172   eOSState Play(void);
  1173   eOSState Edit(void);
  1174   eOSState New(void);
  1175   eOSState Delete(void);
  1176   eOSState Rename(bool second);
  1177   eOSState Source(bool second);
  1178   eOSState Instant(bool second);
  1179   void ScanLists(void);
  1180   eOSState SetButtons(int num);
  1181 public:
  1182   cMenuMP3(void);
  1183   ~cMenuMP3(void);
  1184   virtual eOSState ProcessKey(eKeys Key);
  1185   };
  1186 
  1187 cMenuMP3::cMenuMP3(void)
  1188 :cOsdMenu(tr("MP3"))
  1189 {
  1190   renaming=sourcing=instanting=false;
  1191   lists=new cPlayLists;
  1192   ScanLists(); SetButtons(1);
  1193   if(MP3Setup.MenuMode) Instant(false);
  1194 }
  1195 
  1196 cMenuMP3::~cMenuMP3(void)
  1197 {
  1198   delete lists;
  1199 }
  1200 
  1201 eOSState cMenuMP3::SetButtons(int num)
  1202 {
  1203   switch(num) {
  1204     case 1:
  1205       SetHelp(trVDR("Button$Edit"), tr("Source"), tr("Browse"), ">>");
  1206       break;
  1207     case 2:
  1208       SetHelp("<<", trVDR("Button$New"), trVDR("Button$Delete"), tr("Rename"));
  1209       break;
  1210     }
  1211   buttonnum=num; Display();
  1212   return osContinue;
  1213 }
  1214 
  1215 void cMenuMP3::ScanLists(void)
  1216 {
  1217   Clear();
  1218   Status(tr("Scanning playlists..."));
  1219   bool res=lists->Load(MP3Sources.GetSource());
  1220   Status(0);
  1221   if(res) {
  1222     cPlayList *plist=lists->First();
  1223     while(plist) {
  1224       Add(new cMenuMP3Item(plist));
  1225       plist=lists->Next(plist);
  1226       }
  1227     }
  1228   else Error(tr("Error scanning playlists!"));
  1229 }
  1230 
  1231 eOSState cMenuMP3::Delete(void)
  1232 {
  1233   if(Count()>0) {
  1234     if(Interface->Confirm(tr("Delete playlist?")) &&
  1235        Interface->Confirm(tr("Are you sure?")) ) {
  1236       cPlayList *plist = ((cMenuMP3Item *)Get(Current()))->List();
  1237       if(plist->Delete()) {
  1238         lists->Del(plist);
  1239         cOsdMenu::Del(Current());
  1240         Display();
  1241         }
  1242       else Error(tr("Error deleting playlist!"));
  1243       }
  1244     }
  1245   return osContinue;
  1246 }
  1247 
  1248 eOSState cMenuMP3::New(void)
  1249 {
  1250   cPlayList *plist=new cPlayList(MP3Sources.GetSource(),0,0);
  1251   char name[32];
  1252   int i=0;
  1253   do {
  1254     if(i) sprintf(name,"%s%d",tr("unnamed"),i++);
  1255     else { strcpy(name,tr("unnamed")); i++; }
  1256     } while(plist->TestName(name));
  1257 
  1258   if(plist->Create(name)) {
  1259     lists->Add(plist);
  1260     Add(new cMenuMP3Item(plist), true);
  1261 
  1262     isyslog("MP3: playlist %s added", plist->Name());
  1263     return AddSubMenu(new cMenuPlayList(plist));
  1264     }
  1265   Error(tr("Error creating playlist!"));
  1266   delete plist;
  1267   return osContinue;
  1268 }
  1269 
  1270 eOSState cMenuMP3::Rename(bool second)
  1271 {
  1272   if(HasSubMenu() || Count() == 0) return osContinue;
  1273 
  1274   cPlayList *plist = ((cMenuMP3Item *)Get(Current()))->List();
  1275   if(!second) {
  1276     renaming=true;
  1277     return AddSubMenu(new cPlaylistRename(plist->BaseName()));
  1278     }
  1279   renaming=false;
  1280   const char *newname=cPlaylistRename::GetNewname();
  1281   if(newname) {
  1282     if(plist->Rename(newname)) {
  1283       RefreshCurrent();
  1284       DisplayCurrent(true);
  1285       }
  1286     else Error(tr("Error renaming playlist!"));
  1287     }
  1288   return osContinue;
  1289 }
  1290 
  1291 eOSState cMenuMP3::Edit(void)
  1292 {
  1293   if(HasSubMenu() || Count() == 0) return osContinue;
  1294 
  1295   cPlayList *plist = ((cMenuMP3Item *)Get(Current()))->List();
  1296   if(!plist->Load()) Error(tr("Error loading playlist!"));
  1297   else if(!plist->IsWinAmp()) {
  1298     isyslog("MP3: editing playlist %s", plist->Name());
  1299     return AddSubMenu(new cMenuPlayList(plist));
  1300     }
  1301   else Error(tr("Can't edit a WinAmp playlist!"));
  1302   return osContinue;
  1303 }
  1304 
  1305 eOSState cMenuMP3::Play(void)
  1306 {
  1307   if(HasSubMenu() || Count() == 0) return osContinue;
  1308 
  1309   Status(tr("Loading playlist..."));
  1310   cPlayList *newpl=new cPlayList(((cMenuMP3Item *)Get(Current()))->List());
  1311   if(newpl->Load() && newpl->Count()) {
  1312     isyslog("mp3: playback started with playlist %s", newpl->Name());
  1313     cMP3Control::SetPlayList(newpl);
  1314     if(MP3Setup.KeepSelect) { Status(0); return osContinue; }
  1315     return osEnd;
  1316     }
  1317   Status(0);
  1318   delete newpl;
  1319   Error(tr("Error loading playlist!"));
  1320   return osContinue;
  1321 }
  1322 
  1323 eOSState cMenuMP3::Source(bool second)
  1324 {
  1325   if(HasSubMenu()) return osContinue;
  1326 
  1327   if(!second) {
  1328     sourcing=true;
  1329     return AddSubMenu(new cMenuSource(&MP3Sources,tr("MP3 source")));
  1330     }
  1331   sourcing=false;
  1332   cFileSource *src=cMenuSource::GetSelected();
  1333   if(src) {
  1334     MP3Sources.SetSource(src);
  1335     ScanLists();
  1336     Display();
  1337     }
  1338   return osContinue;
  1339 }
  1340 
  1341 eOSState cMenuMP3::Instant(bool second)
  1342 {
  1343   if(HasSubMenu()) return osContinue;
  1344 
  1345   if(!second) {
  1346     instanting=true;
  1347     return AddSubMenu(new cMenuInstantBrowse(MP3Sources.GetSource(),trVDR("Button$Play"),tr("Play all")));
  1348     }
  1349   instanting=false;
  1350   cFileObj *item=cMenuInstantBrowse::GetSelected();
  1351   if(item) {
  1352     Status(tr("Building playlist..."));
  1353     cInstantPlayList *newpl = new cInstantPlayList(item);
  1354     if(newpl->Load() && newpl->Count()) {
  1355       isyslog("mp3: playback started with instant playlist %s", newpl->Name());
  1356       cMP3Control::SetPlayList(newpl);
  1357       if(MP3Setup.KeepSelect) { Status(0); return Instant(false); }
  1358       return osEnd;
  1359       }
  1360     Status(0);
  1361     delete newpl;
  1362     Error(tr("Error building playlist!"));
  1363     }
  1364   return osContinue;
  1365 }
  1366 
  1367 eOSState cMenuMP3::ProcessKey(eKeys Key)
  1368 {
  1369   eOSState state = cOsdMenu::ProcessKey(Key);
  1370 
  1371   if(!HasSubMenu() && state==osContinue) { // eval the return value from submenus
  1372     if(renaming) return Rename(true);
  1373     if(sourcing) return Source(true);
  1374     if(instanting) return Instant(true);
  1375     }
  1376 
  1377   if(state == osUnknown) {
  1378     switch(Key) {
  1379       case kOk:     return Play();
  1380       case kRed:    return (buttonnum==1 ? Edit() : SetButtons(1)); 
  1381       case kGreen:  return (buttonnum==1 ? Source(false) : New());
  1382       case kYellow: return (buttonnum==1 ? Instant(false) : Delete());
  1383       case kBlue:   return (buttonnum==1 ? SetButtons(2) : Rename(false));
  1384       case kMenu:   return osEnd;
  1385       default:      break;
  1386       }
  1387     }
  1388   return state;
  1389 }
  1390 
  1391 // --- PropagateImage ----------------------------------------------------------
  1392 
  1393 void PropagateImage(const char *image)
  1394 {
  1395   cPlugin *graphtft=cPluginManager::GetPlugin("graphtft");
  1396   if(graphtft) graphtft->SetupParse("CoverImage",image ? image:"");
  1397 }
  1398 
  1399 // --- cPluginMP3 --------------------------------------------------------------
  1400 
  1401 static const char *DESCRIPTION    = trNOOP("A versatile audio player");
  1402 static const char *MAINMENUENTRY  = "MP3";
  1403 
  1404 class cPluginMp3 : public cPlugin {
  1405 private:
  1406   bool ExternalPlay(const char *path, bool test);
  1407 public:
  1408   cPluginMp3(void);
  1409   virtual ~cPluginMp3();
  1410   virtual const char *Version(void) { return PluginVersion; }
  1411   virtual const char *Description(void) { return tr(DESCRIPTION); }
  1412   virtual const char *CommandLineHelp(void);
  1413   virtual bool ProcessArgs(int argc, char *argv[]);
  1414   virtual bool Initialize(void);
  1415   virtual void Housekeeping(void);
  1416   virtual const char *MainMenuEntry(void);
  1417   virtual cOsdObject *MainMenuAction(void);
  1418   virtual cMenuSetupPage *SetupMenu(void);
  1419   virtual bool SetupParse(const char *Name, const char *Value);
  1420   virtual bool Service(const char *Id, void *Data);
  1421   virtual const char **SVDRPHelpPages(void);
  1422   virtual cString SVDRPCommand(const char *Command, const char *Option, int &ReplyCode);
  1423   };
  1424 
  1425 cPluginMp3::cPluginMp3(void)
  1426 {
  1427   // Initialize any member varaiables here.
  1428   // DON'T DO ANYTHING ELSE THAT MAY HAVE SIDE EFFECTS, REQUIRE GLOBAL
  1429   // VDR OBJECTS TO EXIST OR PRODUCE ANY OUTPUT!
  1430 }
  1431 
  1432 cPluginMp3::~cPluginMp3()
  1433 {
  1434   InfoCache.Shutdown();
  1435   delete mgr;
  1436 }
  1437 
  1438 const char *cPluginMp3::CommandLineHelp(void)
  1439 {
  1440   static char *help_str=0;
  1441   
  1442   free(help_str);    //                                     for easier orientation, this is column 80|
  1443   asprintf(&help_str,"  -m CMD,   --mount=CMD    use CMD to mount/unmount/eject mp3 sources\n"
  1444                      "                           (default: %s)\n"
  1445                      "  -n CMD,   --network=CMD  execute CMD before & after network access\n"
  1446                      "                           (default: %s)\n"
  1447                      "  -C DIR,   --cache=DIR    store ID3 cache file in DIR\n"
  1448                      "                           (default: %s)\n"
  1449                      "  -B DIR,   --cddb=DIR     search CDDB files in DIR\n"
  1450                      "                           (default: %s)\n"
  1451                      "  -D DEV,   --dsp=DEV      device for OSS output\n"
  1452                      "                           (default: %s)\n"
  1453                      "  -i CMD,   --iconv=CMD    use CMD to convert background images\n"
  1454                      "                           (default: %s)\n"
  1455                      "  -I IMG,   --defimage=IMG use IMG as default background image\n"
  1456                      "                           (default: none)\n"
  1457                      "  -c DIR,   --icache=DIR   cache converted images in DIR\n"
  1458                      "                           (default: %s)\n"
  1459                      "  -S SUB,   --sources=SUB  search sources config in SUB subdirectory\n"
  1460                      "                           (default: %s)\n",
  1461                      
  1462                      mountscript,
  1463                      netscript ? netscript:"none",
  1464                      cachedir ? cachedir:"video dir",
  1465 #ifdef HAVE_SNDFILE
  1466                      cddbpath,
  1467 #else
  1468                      "none",
  1469 #endif
  1470 #ifdef WITH_OSS
  1471                      dspdevice,
  1472 #else
  1473                      "none",
  1474 #endif
  1475                      imageconv,
  1476                      imagecache,
  1477                      sourcesSub ? sourcesSub:"empty"
  1478                      );
  1479   return help_str;
  1480 }
  1481 
  1482 bool cPluginMp3::ProcessArgs(int argc, char *argv[])
  1483 {
  1484   static struct option long_options[] = {
  1485       { "mount",    required_argument, NULL, 'm' },
  1486       { "network",  required_argument, NULL, 'n' },
  1487       { "cddb",     required_argument, NULL, 'B' },
  1488       { "dsp",      required_argument, NULL, 'D' },
  1489       { "cache",    required_argument, NULL, 'C' },
  1490       { "icache",   required_argument, NULL, 'c' },
  1491       { "iconv",    required_argument, NULL, 'i' },
  1492       { "defimage", required_argument, NULL, 'I' },
  1493       { "sources",  required_argument, NULL, 'S' },
  1494       { NULL }
  1495     };
  1496 
  1497   int c, option_index = 0;
  1498   while((c=getopt_long(argc,argv,"c:i:m:n:B:C:D:S:",long_options,&option_index))!=-1) {
  1499     switch (c) {
  1500       case 'i': imageconv=optarg; break;
  1501       case 'c': imagecache=optarg; break;
  1502       case 'm': mountscript=optarg; break;
  1503       case 'n': netscript=optarg; break;
  1504       case 'C': cachedir=optarg; break;
  1505       case 'I': def_usr_img=optarg; break;
  1506       case 'S': sourcesSub=optarg; break;
  1507       case 'B':
  1508 #ifdef HAVE_SNDFILE
  1509                 cddbpath=optarg; break;
  1510 #else
  1511                 fprintf(stderr, "mp3: libsndfile support has not been compiled in!\n"); return false;
  1512 #endif
  1513       case 'D':
  1514 #ifdef WITH_OSS
  1515                 dspdevice=optarg; break;
  1516 #else
  1517                 fprintf(stderr, "mp3: OSS output has not been compiled in!\n"); return false;
  1518 #endif
  1519       default:  return false;
  1520       }
  1521     }
  1522   return true;
  1523 }
  1524 
  1525 bool cPluginMp3::Initialize(void)
  1526 {
  1527   if(!CheckVDRVersion(1,4,5,"mp3")) return false;
  1528   plugin_name="mp3";
  1529 #if APIVERSNUM < 10507
  1530   i18n_name="mp3";
  1531 #else
  1532   i18n_name="vdr-mp3";
  1533 #endif
  1534   MP3Sources.Load(AddDirectory(ConfigDirectory(sourcesSub),"mp3sources.conf"));
  1535   if(MP3Sources.Count()<1) {
  1536      esyslog("ERROR: you should have defined at least one source in mp3sources.conf");
  1537      fprintf(stderr,"No source(s) defined in mp3sources.conf\n");
  1538      return false;
  1539      }
  1540   InfoCache.Load();
  1541 #if APIVERSNUM < 10507
  1542   RegisterI18n(Phrases);
  1543 #endif
  1544   mgr=new cPlayManager;
  1545   if(!mgr) {
  1546     esyslog("ERROR: creating playmanager failed");
  1547     fprintf(stderr,"Creating playmanager failed\n");
  1548     return false;
  1549     }
  1550   d(printf("mp3: using %s\n",mad_version))
  1551   d(printf("mp3: compiled with %s\n",MAD_VERSION))
  1552   return true;
  1553 }
  1554 
  1555 void cPluginMp3::Housekeeping(void)
  1556 {
  1557   InfoCache.Save();
  1558 }
  1559 
  1560 const char *cPluginMp3::MainMenuEntry(void)
  1561 {
  1562   return MP3Setup.HideMainMenu ? 0 : tr(MAINMENUENTRY);
  1563 }
  1564 
  1565 cOsdObject *cPluginMp3::MainMenuAction(void)
  1566 {
  1567   return new cMenuMP3;
  1568 }
  1569 
  1570 cMenuSetupPage *cPluginMp3::SetupMenu(void)
  1571 {
  1572   return new cMenuSetupMP3;
  1573 }
  1574 
  1575 bool cPluginMp3::SetupParse(const char *Name, const char *Value)
  1576 {
  1577   if      (!strcasecmp(Name, "InitLoopMode"))     MP3Setup.InitLoopMode    = atoi(Value);
  1578   else if (!strcasecmp(Name, "InitShuffleMode"))  MP3Setup.InitShuffleMode = atoi(Value);
  1579   else if (!strcasecmp(Name, "AudioMode"))        MP3Setup.AudioMode       = atoi(Value);
  1580   else if (!strcasecmp(Name, "BgrScan"))          MP3Setup.BgrScan         = atoi(Value);
  1581   else if (!strcasecmp(Name, "EditorMode"))       MP3Setup.EditorMode      = atoi(Value);
  1582   else if (!strcasecmp(Name, "DisplayMode"))      MP3Setup.DisplayMode     = atoi(Value);
  1583   else if (!strcasecmp(Name, "BackgrMode"))       MP3Setup.BackgrMode      = atoi(Value);
  1584   else if (!strcasecmp(Name, "MenuMode"))         MP3Setup.MenuMode        = atoi(Value);
  1585   else if (!strcasecmp(Name, "TargetLevel"))      MP3Setup.TargetLevel     = atoi(Value);
  1586   else if (!strcasecmp(Name, "LimiterLevel"))     MP3Setup.LimiterLevel    = atoi(Value);
  1587   else if (!strcasecmp(Name, "Only48kHz"))        MP3Setup.Only48kHz       = atoi(Value);
  1588   else if (!strcasecmp(Name, "UseProxy"))         MP3Setup.UseProxy        = atoi(Value);
  1589   else if (!strcasecmp(Name, "ProxyHost"))        strn0cpy(MP3Setup.ProxyHost,Value,MAX_HOSTNAME);
  1590   else if (!strcasecmp(Name, "ProxyPort"))        MP3Setup.ProxyPort       = atoi(Value);
  1591   else if (!strcasecmp(Name, "UseCddb"))          MP3Setup.UseCddb         = atoi(Value);
  1592   else if (!strcasecmp(Name, "CddbHost"))         strn0cpy(MP3Setup.CddbHost,Value,MAX_HOSTNAME);
  1593   else if (!strcasecmp(Name, "CddbPort"))         MP3Setup.CddbPort        = atoi(Value);
  1594   else if (!strcasecmp(Name, "AbortAtEOL"))       MP3Setup.AbortAtEOL      = atoi(Value);
  1595   else if (!strcasecmp(Name, "AudioOutMode")) {
  1596     MP3Setup.AudioOutMode = atoi(Value);
  1597 #ifndef WITH_OSS
  1598     if(MP3Setup.AudioOutMode==AUDIOOUTMODE_OSS) {
  1599       esyslog("WARNING: AudioOutMode OSS not supported, falling back to DVB");
  1600       MP3Setup.AudioOutMode=AUDIOOUTMODE_DVB;
  1601       }
  1602 #endif
  1603     }
  1604   else if (!strcasecmp(Name, "ReplayDisplay"))      MP3Setup.ReplayDisplay = atoi(Value);
  1605   else if (!strcasecmp(Name, "HideMainMenu"))       MP3Setup.HideMainMenu  = atoi(Value);
  1606   else if (!strcasecmp(Name, "KeepSelect"))         MP3Setup.KeepSelect    = atoi(Value);
  1607   else if (!strcasecmp(Name, "TitleArtistOrder"))   MP3Setup.TitleArtistOrder = atoi(Value);
  1608   else return false;
  1609   return true;
  1610 }
  1611 
  1612 bool cPluginMp3::ExternalPlay(const char *path, bool test)
  1613 {
  1614   char real[PATH_MAX+1];
  1615   if(realpath(path,real)) {
  1616     cFileSource *src=MP3Sources.FindSource(real);
  1617     if(src) {
  1618       cFileObj *item=new cFileObj(src,0,0,otFile);
  1619       if(item) {
  1620         item->SplitAndSet(real);
  1621         if(item->GuessType()) {
  1622           if(item->Exists()) {
  1623             cInstantPlayList *pl=new cInstantPlayList(item);
  1624             if(pl && pl->Load() && pl->Count()) {
  1625               if(!test) cMP3Control::SetPlayList(pl);
  1626               else delete pl;
  1627               delete item;
  1628               return true;
  1629               }
  1630             else dsyslog("MP3 service: error building playlist");
  1631             delete pl;
  1632             }
  1633           else dsyslog("MP3 service: cannot play '%s'",path);
  1634           }
  1635         else dsyslog("MP3 service: GuessType() failed for '%s'",path);
  1636         delete item;
  1637         }
  1638       }
  1639     else dsyslog("MP3 service: cannot find source for '%s', real '%s'",path,real);
  1640     }
  1641   else if(errno!=ENOENT && errno!=ENOTDIR)
  1642     esyslog("ERROR: realpath: %s: %s",path,strerror(errno));
  1643   return false;
  1644 }
  1645 
  1646 bool cPluginMp3::Service(const char *Id, void *Data)
  1647 {
  1648   if(!strcasecmp(Id,"MP3-Play-v1")) {
  1649     if(Data) {
  1650       struct MPlayerServiceData *msd=(struct MPlayerServiceData *)Data;
  1651       msd->result=ExternalPlay(msd->data.filename,false);
  1652       }
  1653     return true;
  1654     }
  1655   else if(!strcasecmp(Id,"MP3-Test-v1")) {
  1656     if(Data) {
  1657       struct MPlayerServiceData *msd=(struct MPlayerServiceData *)Data;
  1658       msd->result=ExternalPlay(msd->data.filename,true);
  1659       }
  1660     return true;
  1661     }
  1662   return false;
  1663 }
  1664 
  1665 const char **cPluginMp3::SVDRPHelpPages(void)
  1666 {
  1667   static const char *HelpPages[] = {
  1668     "PLAY <filename>\n"
  1669     "    Triggers playback of file 'filename'.",
  1670     "TEST <filename>\n"
  1671     "    Tests is playback of file 'filename' is possible.",
  1672     "CURR\n"
  1673     "    Returns filename of song currently being replayed.",
  1674     NULL
  1675     };
  1676   return HelpPages;
  1677 }
  1678 
  1679 cString cPluginMp3::SVDRPCommand(const char *Command, const char *Option, int &ReplyCode)
  1680 {
  1681   if(!strcasecmp(Command,"PLAY")) {
  1682     if(*Option) {
  1683       if(ExternalPlay(Option,false)) return "Playback triggered";
  1684       else { ReplyCode=550; return "Playback failed"; }
  1685       }
  1686     else { ReplyCode=501; return "Missing filename"; }
  1687     }
  1688   else if(!strcasecmp(Command,"TEST")) {
  1689     if(*Option) {
  1690       if(ExternalPlay(Option,true)) return "Playback possible";
  1691       else { ReplyCode=550; return "Playback not possible"; }
  1692       }
  1693     else { ReplyCode=501; return "Missing filename"; }
  1694     }
  1695   else if(!strcasecmp(Command,"CURR")) {
  1696     cControl *control=cControl::Control();
  1697     if(control && typeid(*control)==typeid(cMP3Control)) {
  1698       cMP3PlayInfo mode;
  1699       if(mgr->Info(-1,&mode)) return mode.Filename;
  1700       else return "<unknown>";
  1701       }
  1702     else { ReplyCode=550; return "No running playback"; }
  1703     }
  1704   return NULL;
  1705 }
  1706 
  1707 VDRPLUGINCREATOR(cPluginMp3); // Don't touch this!