summaryrefslogtreecommitdiff
path: root/vdr_player.c
blob: 6161dd9579b26aab1af701b2c7df117eee49e3c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
/*!
 * \file vdr_player.c
 * \brief A generic PCM player for a VDR media plugin (muggle)
 *
 * \version $Revision: 1.7 $
 * \date    $Date$
 * \author  Ralf Klueber, Lars von Wedel, Andreas Kellner
 * \author  Responsible author: $Author$
 *
 * $Id$
 *
 * Adapted from 
 * MP3/MPlayer plugin to VDR (C++)
 * (C) 2001,2002 Stefan Huelswitt <huels@iname.com>
 */

#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <math.h>

#include <string>
#include <iostream>

#include <mad.h>
#include <id3tag.h>

#include <player.h>
#include <device.h>
#include <thread.h>
#include <ringbuffer.h>
#include <tools.h>
#include <recording.h>

#include "vdr_player.h"
#include "vdr_decoder.h"
#include "vdr_config.h"
#include "vdr_setup.h"

#include "mg_tools.h"
#include "mg_playlist.h"
#include "mg_content_interface.h"

using namespace std;

// ----------------------------------------------------------------

// TODO: check for use of constants
#define OUT_BITS 16                                          // output 16 bit samples to DVB driver
#define OUT_FACT (OUT_BITS/8*2)                              // output factor is 16 bit & 2 channels -> 4 bytes

// cResample
#define MAX_NSAMPLES (1152*7)                                // max. buffer for resampled frame

// cNormalize
#define MAX_GAIN   3.0                                       // max. allowed gain
#define LIM_ACC    12                                        // bit, accuracy for lookup table
#define F_LIM_MAX  (mad_fixed_t)((1<<(MAD_F_FRACBITS+2))-1)  // max. value covered by lookup table
#define LIM_SHIFT  (MAD_F_FRACBITS-LIM_ACC)                  // shift value for table lookup
#define F_LIM_JMP  (mad_fixed_t)(1<<LIM_SHIFT)               // lookup table jump between values

// cLevel
#define POW_WIN 100                                          // window width for smoothing power values
#define EPSILON 0.00000000001                                // anything less than EPSILON is considered zero

// cMP3Player
#define MAX_FRAMESIZE   2048                                 // max. frame size allowed for DVB driver
#define HDR_SIZE        9
#define LPCM_SIZE       7
#define LEN_CORR        3
#define SPEEDCHECKSTART ((MP3BUFSIZE*1000/32000/2/2)+1000)   // play time to fill buffers before speed check starts (ms)
#define SPEEDCHECKTIME  3000                                 // play time for speed check (ms)

/*
struct LPCMHeader { int id:8;              // id
                    int frame_count:8;     // number of frames
                    int access_ptr:16;     // first acces unit pointer, i.e. start of audio frame
                    bool emphasis:1;       // audio emphasis on-off
                    bool mute:1;           // audio mute on-off
                    bool reserved:1;       // reserved
                    int frame_number:5;    // audio frame number
                    int quant_wlen:2;      // quantization word length
                    int sample_freq:2;     // audio sampling frequency (48khz=0, 96khz=1, 44,1khz=2, 32khz=3)
                    bool reserved2:1;      // reserved
                    int chan_count:3;      // number of audio channels - 1 (e.g. stereo = 1)
                    int dyn_range_ctrl:8;  // dynamic range control (0x80 if off)
                    };
*/

struct LPCMFrame
{
  unsigned char PES[HDR_SIZE];
  unsigned char LPCM[LPCM_SIZE];
  unsigned char Data[MAX_FRAMESIZE-HDR_SIZE-LPCM_SIZE];
};

#include "vdr_sound.c"


// --- mgPCMPlayer ----------------------------------------------------------

/*!
 * \brief a generic PCM player class
 *
 * this class implements a state machine that obtains decoded data from a generic data
 * and moves it to the DVB device. It inherits from cPlayer in order to be hooked into
 * VDR as a player and inherits from cThread in order to implement a separate thread
 * for the decoding process.
 */
class mgPCMPlayer : public cPlayer, cThread
{
private:

  //! \brief indicates, whether the player is currently active
  bool m_active;

  //! \brief indicates, whether the player has been started
  bool m_started;

  //! \brief a buffer for decoded sound
  cRingBufferFrame *m_ringbuffer;

  //! \brief a mutex for the playmode
  cMutex m_playmode_mutex;

  //! \brief a condition to signal playmode changes
  cCondVar m_playmode_cond;

  //! \brief the current playlist
  mgPlaylist *m_playlist;

  //! \brief the currently played or to be played item
  mgContentItem *m_current;

  //! \brief the currently playing item
  mgContentItem *m_playing;
  
  //! \brief the decoder responsible for the currently playing item
  mgDecoder *m_decoder;

  cFrame *m_rframe, *m_pframe;

  enum ePlayMode 
    { 
      pmPlay, 
      pmStopped, 
      pmPaused, 
      pmStartup 
    };
  ePlayMode m_playmode;

  enum eState 
    { 
      msStart, msStop, 
      msDecode, msNormalize, 
      msResample, msOutput, 
      msError, msEof, msWait 
    };
  eState m_state;

  bool levelgood;
  unsigned int dvbSampleRate;

  //
  int m_index;

  void Empty(void);
  bool NextFile(void);
  bool PrevFile(void);
  void StopPlay(void);

  void SetPlayMode(ePlayMode mode);
  void WaitPlayMode(ePlayMode mode, bool inv);

protected:
  virtual void Activate(bool On);
  virtual void Action(void);

public:
  mgPCMPlayer(mgPlaylist *plist);
  virtual ~mgPCMPlayer();

  bool Active(void) { return m_active; }
  void Pause(void);
  void Play(void);
  void Forward(void);
  void Backward(void);
  void Goto(int Index, bool Still=false);
  void SkipSeconds(int secs);
  void ToggleShuffle(void);
  void ToggleLoop(void);
  virtual bool GetIndex(int &Current, int &Total, bool SnapToIFrame=false);
  //  bool GetPlayInfo(cMP3PlayInfo *rm); // LVW
  void NewPlaylist(mgPlaylist *plist);
  mgContentItem *GetCurrent () { return m_current; }
  };

mgPCMPlayer::mgPCMPlayer(mgPlaylist *plist)
  : cPlayer( the_setup.BackgrMode? pmAudioOnly: pmAudioOnlyBlack )
{
  m_playlist = plist;

  m_active   = true; 
  m_started  = false; 

  m_ringbuffer = new cRingBufferFrame( MP3BUFSIZE );

  m_rframe  = 0; 
  m_pframe  = 0; 
  m_decoder = 0;

  m_playmode = pmStartup; 
  m_state = msStop;

  m_index = 0; 
  m_playing = 0; 
}

mgPCMPlayer::~mgPCMPlayer()
{
  Detach();

  delete m_ringbuffer;
}

void mgPCMPlayer::Activate(bool on)
{
  MGLOG( "mgPCMPlayer::Activate" );
  if( on ) 
    {
      if( m_playlist && !m_started )
	{
	  m_playmode = pmStartup; 
	  Start();

	  m_started = true;
	  m_current = 0;

	  m_playmode_mutex.Lock();
	  WaitPlayMode( pmStartup, true ); // wait for the decoder to become ready
	  m_playmode_mutex.Unlock();

	  Lock();

	  m_playlist->initialize();
	  m_current = m_playlist->getCurrent();
	  Play();

	  Unlock();
	}
    }
  else if( m_started && m_active ) 
    {
      Lock(); 
      StopPlay(); 
      Unlock();

      m_active = false;
      SetPlayMode( pmStartup );

      Cancel(2);
    }
}

void mgPCMPlayer::NewPlaylist( mgPlaylist *plist )
{
  MGLOG( "mgPCMPlayer::NewPlaylist" );

  Lock(); 
  StopPlay(); 
  Unlock();

  // memory management of playlists should happen elsewhere (menu, content)
  m_playlist = plist;
  m_current = 0;
  
  if( NextFile() ) 
    {
      Play();
    }
}

void mgPCMPlayer::SetPlayMode(ePlayMode mode)
{
  m_playmode_mutex.Lock();
  if( mode != m_playmode ) 
    {
      m_playmode = mode;
      m_playmode_cond.Broadcast();
    }
  m_playmode_mutex.Unlock();
}

void mgPCMPlayer::WaitPlayMode(ePlayMode mode, bool inv)
{
  // must be called with m_playmode_mutex LOCKED !!!

  while( m_active && ( (!inv && mode != m_playmode) || (inv && mode == m_playmode) ) ) 
    {
      m_playmode_cond.Wait(m_playmode_mutex);
    }
}

void mgPCMPlayer::Action(void)
{
  MGLOG( "mgPCMPlayer::Action" );

  struct mgDecode *ds=0;
  struct mad_pcm *pcm=0;
  cResample resample[2];
  unsigned int nsamples[2];
  const mad_fixed_t *data[2];
  cScale scale;
  cLevel level;
  cNormalize norm;
  bool haslevel=false;
  struct LPCMFrame lpcmFrame;
  const unsigned char *p=0;
  int pc = 0, only48khz = the_setup.Only48kHz;
  cPoller poll;
#ifdef DEBUG
  int beat=0;
#endif

  dsyslog( "muggle: player thread started (pid=%d)", getpid() );

  memset( &lpcmFrame, 0, sizeof(lpcmFrame) );
  lpcmFrame.PES[2]=0x01;
  lpcmFrame.PES[3]=0xbd;
  lpcmFrame.PES[6]=0x87;
  lpcmFrame.LPCM[0]=0xa0; // substream ID
  lpcmFrame.LPCM[1]=0xff;
  lpcmFrame.LPCM[5]=0x01;
  lpcmFrame.LPCM[6]=0x80;

  dvbSampleRate = 48000;
  m_state = msStop;
  SetPlayMode( pmStopped );
 
  while( m_active ) 
    {
#ifdef DEBUG
      if(time(0)>=beat+30) 
	{
	  cout << "mgPCMPlayer::Action: heartbeat buffer=" << m_ringbuffer->Available() << endl << flush;
	  scale.Stats(); if(haslevel) norm.Stats();
	  beat=time(0);
	}
#endif

      Lock();
      
      if( !m_rframe && m_playmode == pmPlay ) 
	{
	  switch( m_state ) 
	    {
	    case msStart:
	      {
		m_index = 0; 
		m_playing = m_current;

		string filename = m_playing->getSourceFile();
		mgDebug( 1, "mgPCMPlayer::Action: music file is %s", filename.c_str() );

		if( ( m_decoder = mgDecoders::findDecoder( m_playing ) ) && m_decoder->start() )
		  {
		    levelgood = true; 
		    haslevel = false;
		    
		    scale.Init();
		    level.Init();
		    
		    m_state = msDecode;
		    
		    break;
		  }

		m_state = msEof;
	      } break;
	    case msDecode:
	      {
		ds = m_decoder->decode();
		switch( ds->status ) 
		  {
		  case dsPlay:
		    {
		      pcm   = ds->pcm;
		      m_index = ds->index/1000;
		      m_state = msNormalize;
		    } break;
		  case dsSkip:
		  case dsSoftError:
		    {
		      // skipping, state unchanged, next decode
		    } break;
		  case dsEof:
		    {
		      m_state = msEof;
		    } break;
		  case dsOK:
		  case dsError:
		    {
		      m_state = msError;
		    } break;
		  }
	      } break;
	    case msNormalize:
	      {
		if(!haslevel) 
		  { 
		    if( levelgood ) 
		      {
			level.GetPower( pcm ); 
		      }
		  }
		else 
		  {
		    norm.AddGain( pcm );
		  }
		m_state = msResample;
	      } break;
	    case msResample:
	      {
#ifdef DEBUG
		{
		  static unsigned int oldrate=0;
		  if(oldrate!=pcm->samplerate) 
		    {
		      cout << "mgPCMPlayer::Action: new input sample rate " << pcm->samplerate << endl << flush;
		      oldrate = pcm->samplerate;
		    }
		}
#endif
		nsamples[0] = nsamples[1] = pcm->length;
		data[0] = pcm->samples[0];
		data[1] = pcm->channels > 1 ? pcm->samples[1]: 0;
		
		lpcmFrame.LPCM[5]&=0xcf;
		dvbSampleRate=48000;
		if(!only48khz) 
		  {
		    switch(pcm->samplerate) 
		      {    // If one of the supported frequencies, do it without resampling.
		      case 96000:
			{ // Select a "even" upsampling frequency if possible, too.
			  lpcmFrame.LPCM[5] |= 1 << 4;
			  dvbSampleRate = 96000;
			} break;

			//case 48000: // this is already the default ...
			//  lpcmFrame.LPCM[5]|=0<<4;
			//  dvbSampleRate=48000;
			//  break;
		      case 11025:
		      case 22050:
		      case 44100:
			{
			  lpcmFrame.LPCM[5]|=2<<4;
			  dvbSampleRate = 44100;
			} break;
		      case 8000:
		      case 16000:
		      case 32000:
			{ 
			  lpcmFrame.LPCM[5]|=3<<4;
			  dvbSampleRate = 32000;
			} break;
		      }
		  }
		
		if( dvbSampleRate != pcm->samplerate ) 
		  {
		    if( resample[0].SetInputRate( pcm->samplerate, dvbSampleRate ) ) 
		      {
			nsamples[0] = resample[0].ResampleBlock( nsamples[0], data[0] );
			data[0]     = resample[0].Resampled();
		      }
		    if(data[1] && resample[1].SetInputRate( pcm->samplerate, dvbSampleRate ) ) 
		      {
			nsamples[1] = resample[1].ResampleBlock( nsamples[1], data[1] );
			data[1]     = resample[1].Resampled();
		      }
		  }
		m_state=msOutput;
	      } break;
	    case msOutput:
	      {
		if( nsamples[0] > 0 ) 
		  {
		    unsigned int outlen = scale.ScaleBlock( lpcmFrame.Data,
							    sizeof(lpcmFrame.Data),
							    nsamples[0], data[0],
							    data[1], 
							    the_setup.AudioMode? amDither: amRound );
		    if( outlen ) 
		      { 
			outlen += sizeof(lpcmFrame.LPCM)+LEN_CORR;
			lpcmFrame.PES[4] = outlen >> 8;
			lpcmFrame.PES[5] = outlen;
			m_rframe = new cFrame( (unsigned char *)&lpcmFrame,
					     outlen + sizeof( lpcmFrame.PES ) - LEN_CORR );
		      }
		  }
		else 
		  {
		    m_state=msDecode;
		  }
	      } break;
	    case msError:
	    case msEof:
	      {
		if( NextFile() ) 
		  {
		    m_state = msStart;
		  }
		else 
		  {
		    m_state = msWait;
		  }
	      } // fall through
	    case msStop:
	      {
		m_playing = 0;
		if( m_decoder ) 
		  { // who deletes decoder?
		    m_decoder->stop(); 
		    m_decoder = 0; 
		  }

		levelgood = false;

		scale.Stats(); 
		if( haslevel )
		  {
		    norm.Stats();
		  }
		if( m_state == msStop ) 
		  { // might be unequal in case of fall through from eof/error
		    SetPlayMode( pmStopped );
		  }
	      } break;
	    case msWait:
	      {
		if( m_ringbuffer->Available() == 0 ) 
		  {
		    m_active = false;
		    SetPlayMode(pmStopped);
		  }
	      } break;
	    }
	}
      
      if( m_rframe && m_ringbuffer->Put( m_rframe ) )
	{
	  m_rframe = 0;
	}
      
      if( !m_pframe && m_playmode == pmPlay ) 
	{
	  m_pframe = m_ringbuffer->Get();
	  if( m_pframe )
	    {
	      p = m_pframe->Data();
	      pc = m_pframe->Count();
	    }
	}
      
      if( m_pframe ) 
	{
	  int w = PlayVideo( p, pc );
	  if( w > 0 ) 
	    {
	      p += w; 
	      pc -= w;

	      if( pc <= 0 ) 
		{
		  m_ringbuffer->Drop(m_pframe);
		  m_pframe=0;
		}
	    }
	  else if( w < 0 && FATALERRNO ) 
	    {
	      LOG_ERROR;
	      break;
	    }
	}
      
      Unlock();
      
      if( (m_rframe || m_state == msWait) && m_pframe ) 
	{
	  // Wait for output to become ready
	  DevicePoll( poll, 500 );
	}
      else 
	{
	  if( m_playmode != pmPlay ) 
	    {
	      m_playmode_mutex.Lock();

	      if( m_playmode != pmPlay ) 
		{
		  WaitPlayMode( m_playmode, true );  // Wait on playMode change
		}
	      m_playmode_mutex.Unlock();
	    }
	}
    }
  
  Lock();

  if( m_rframe )
    {
      delete m_rframe; 
      m_rframe=0;
    }

  if( m_decoder ) 
    { // who deletes decoder?
      m_decoder->stop(); 
      m_decoder = 0; 
    }
  
  m_playing = 0;

  SetPlayMode(pmStopped);

  Unlock();

  m_active = false;
  
  dsyslog( "muggle: player thread ended (pid=%d)", getpid() );
}

void mgPCMPlayer::Empty(void)
{
  MGLOG( "mgPCMPlayer::Empty" );

  Lock();

  m_ringbuffer->Clear();
  DeviceClear();

  delete m_rframe; 
  m_rframe = 0; 
  m_pframe = 0;

  Unlock();
}

void mgPCMPlayer::StopPlay() 
{ // StopPlay() must be called in locked state!!!
  MGLOG( "mgPCMPlayer::StopPlay" );
  if( m_playmode != pmStopped ) 
    {
      Empty();
      m_state = msStop;
      SetPlayMode( pmPlay );
      Unlock();                 // let the decode thread process the stop signal

      m_playmode_mutex.Lock();
      WaitPlayMode( pmStopped, false );
      m_playmode_mutex.Unlock();

      Lock();
    }
}

bool mgPCMPlayer::NextFile()
{
  bool res = false;
    
  m_playlist->skipFwd();
  mgContentItem *newcurr = m_playlist->getCurrent();

  if( newcurr && newcurr != &(mgContentItem::UNDEFINED) ) 
    {
      m_current = newcurr; 
      res = true;
    }

  return res;
}

bool mgPCMPlayer::PrevFile(void)
{
  bool res = false;
    
  m_playlist->skipBack();
  mgContentItem *newcurr = m_playlist->getCurrent();

  if( newcurr && newcurr != &(mgContentItem::UNDEFINED) ) 
    {
      m_current = newcurr; 
      res = true;
    }

  return res;
}

void mgPCMPlayer::ToggleShuffle()
{
  m_playlist->toggleShuffle();
}

void mgPCMPlayer::ToggleLoop(void)
{
  m_playlist->toggleLoop();
}

void mgPCMPlayer::Pause(void)
{
  if( m_playmode == pmPaused ) 
    {
      Play();
    }
  else
    {
      if( m_playmode == pmPlay ) 
	{
	  //    DeviceFreeze();
	  SetPlayMode( pmPaused );
      }
    }
}

void mgPCMPlayer::Play(void)
{
  MGLOG( "mgPCMPlayer::Play" );

  Lock();

  if( m_playmode != pmPlay && m_current ) 
    {
      if( m_playmode == pmStopped ) 
	{
	  m_state = msStart;
	}
      //    DevicePlay(); // TODO? Commented out in original code, too
      SetPlayMode( pmPlay );
    }
  Unlock();
}

void mgPCMPlayer::Forward(void)
{
  MGLOG( "mgPCMPlayer::Forward" );

  Lock();
  if( NextFile() ) 
    { 
      StopPlay(); 
      Play(); 
    }
  Unlock();
}

void mgPCMPlayer::Backward(void)
{
  Lock();
  if( PrevFile() ) 
    { 
      StopPlay(); 
      Play(); 
    }
  Unlock();
}

void mgPCMPlayer::Goto( int index, bool still )
{
  m_playlist->gotoPosition( index-1 );
  mgContentItem *next = m_playlist->getCurrent();

  if( next && next != &(mgContentItem::UNDEFINED) ) //invalid
    {
      Lock();
      StopPlay();
      m_current = next;
      Play();
      Unlock();
    }
}

void mgPCMPlayer::SkipSeconds(int secs)
{
  if( m_playmode != pmStopped ) 
    {
      Lock();
      if( m_playmode == pmPaused ) 
	{
	  SetPlayMode( pmPlay );
	}
      if( m_decoder && m_decoder->skip( secs, m_ringbuffer->Available(), dvbSampleRate ) )
	{
	  levelgood=false;
	}
      Empty();
      Unlock();
    }
}

bool mgPCMPlayer::GetIndex( int &current, int &total, bool snaptoiframe )
{
  bool res = false;
  current = SecondsToFrames(m_index); 
  total = -1;

  return res;
}

// --- mgPlayerControl -------------------------------------------------------

mgPlayerControl::mgPlayerControl( mgPlaylist *plist )
  : cControl( m_player = new mgPCMPlayer(plist) )
{
  MGLOG( "mgPlayerControl::mgPlayerControl" );

  m_visible = false;
  m_has_osd = false;
}

mgPlayerControl::~mgPlayerControl()
{
  Hide();
  Stop();
}

bool mgPlayerControl::Active(void)
{
  MGLOG( "mgPlayerControl::Active" );

  return m_player && m_player->Active();
}

void mgPlayerControl::Stop(void)
{
  if( m_player )
    {
      delete m_player; 
      m_player = 0;
    }
}

void mgPlayerControl::Pause(void)
{
  if( m_player )
    {
      m_player->Pause();
    }
}

void mgPlayerControl::Play(void)
{
  if( m_player ) 
    {
      m_player->Play();
    }
}

void mgPlayerControl::Forward(void)
{
  if( m_player ) 
    {
      m_player->Forward();
    }
}

void mgPlayerControl::Backward(void)
{
  if( m_player ) 
    {
      m_player->Backward();
    }
}

void mgPlayerControl::SkipSeconds(int Seconds)
{
  if( m_player ) 
    {
      m_player->SkipSeconds(Seconds);
    }
}

void mgPlayerControl::Goto(int Position, bool Still)
{
  if( m_player )
    {
      m_player->Goto(Position, Still);
    }
}

void mgPlayerControl::ToggleShuffle(void)
{
  if( m_player )
    {
      m_player->ToggleShuffle();
    }
}

void mgPlayerControl::ToggleLoop(void)
{
  if( m_player ) 
    {
      m_player->ToggleLoop();
    }
}

void mgPlayerControl::NewPlaylist(mgPlaylist *plist)
{
  if( m_player ) 
    {
      m_player->NewPlaylist(plist);
    }
}

void mgPlayerControl::ShowProgress()
{
  if( m_visible )
    {
      if( !m_has_osd )
	{
	  // open the osd if its not already there...
#if VDRVERSNUM >= 10307
    osd = cOsdProvider::NewOsd (Setup.OSDLeft, Setup.OSDTop);
    tArea Areas[] = { { 0, 0, Setup.OSDWidth, Setup.OSDHeight, 2 } };
    osd->SetAreas(Areas,sizeof(Areas)/sizeof(tArea));
    font = cFont::GetFont (fontOsd);
#else
	  Interface->Open();
#endif
	  m_has_osd = true;
	}
      
      // now an osd is open, go on
      
#if VDRVERSNUM >= 10307
      int w = Setup.OSDWidth;
      int h = Setup.OSDHeight;
      osd->DrawRectangle (0, 0, w - 1, h - 1, clrGray50);
      mgContentItem *item = m_player->GetCurrent ();
      string msg = item->getGenre () + " " + item->getTitle ();
      osd->DrawText (0, h - font->Height () - 2, msg.c_str (), clrBlack, clrCyan,
                     cFont::GetFont (fontOsd), w, font->Height () + 2, taCenter);
      osd->Flush();
#else
      int w = Interface->Width();
      int h = Interface->Height();
      
      Interface->WriteText( w/2, h/2, "Muggle is active!" );
      
      // Add: song info (name, artist, pos in playlist, time, ...)
      // Add: progress bar
      
      Interface->Flush();
#endif
    }
  else
    {
      Hide();
    }
}

void mgPlayerControl::Hide()
{
  if( m_has_osd )
    {
#if VDRVERSNUM >= 10307
      osd->Flush();
      delete osd;
#else
      Interface->Close();
#endif
      m_has_osd = false;
    }
}

eOSState mgPlayerControl::ProcessKey(eKeys key)
{
  if( !Active() )
    {
      return osEnd;
    }

  ShowProgress();

  eOSState state = cControl::ProcessKey(key);

  if( state == osUnknown )
    {
      switch( key )
	{
	case kUp:
	  {
	    Forward();
	  } break;
	case kDown:
	  {
	    Backward();
	  } break;
	case kPause:
	case kYellow:
	  {
	    Pause();
	  } break;
	case kStop:
	case kBlue:
	  {
	    Hide();
	    Stop();
	    
	    return osEnd;
	  } break;
	case kOk:
	  {
	    m_visible = !m_visible;
	    ShowProgress();

	    return osContinue;
	  } break;
	case kBack:
	  {
	    Hide();
	    Stop();

	    return osEnd;
	  } break;
	default:
	  {
	    return osUnknown;
	  }
	}
    }
  return osContinue;
}

/************************************************************
 *
 * $Log: vdr_player.c,v $
 * Revision 1.7  2004/07/27 20:50:54  lvw
 * Playlist indexing now working
 *
 * Revision 1.6  2004/07/26 22:20:55  lvw
 * Reworked playlist indexing
 *
 * Revision 1.5  2004/07/26 20:03:00  lvw
 * Bug in initalizing playlist removed
 *
 * Revision 1.4  2004/07/25 21:33:35  lvw
 * Removed bugs in finding track files and playlist indexing.
 *
 * Revision 1.3  2004/07/12 11:06:23  LarsAC
 * No longer skip first file on playlist when starting replay.
 *
 * Revision 1.2  2004/05/28 15:29:19  lvw
 * Merged player branch back on HEAD branch.
 *
 * Revision 1.1.2.19  2004/05/26 14:30:27  lvw
 * Removed bug in finding correct mp3 file in GD mode
 *
 * Revision 1.1.2.18  2004/05/25 06:48:24  lvw
 * Documentation and code polishing.
 *
 * Revision 1.1.2.17  2004/05/25 00:10:45  lvw
 * Code cleanup and added use of real database source files
 *
 * Revision 1.1.2.16  2004/05/24 11:48:52  lvw
 * Debugging info added to find deadlock
 *
 * Revision 1.1.2.15  2004/05/12 22:38:37  lvw
 * Some cleanup
 *
 * Revision 1.1.2.14  2004/05/11 06:35:16  lvw
 * Added debugging while hunting stop bug.
 *
 * Revision 1.1.2.13  2004/05/07 06:46:41  lvw
 * Removed a bug in playlist deallocation. Added infrastructure to display information while playing.
 *
 *
 ***********************************************************/