#include <stdlib.h>
#include "rcontroller.h"
#include <stdio.h>
#define PRIVATE_STREAM_1 0xBD
#define PES_EXTENSION_MASK 0x01
#define PES_EXTENSION2_MASK 0x81
namespace RecordingPatch {

  cRecordingController RecordingController;

  // Returns the Data Identifier or 0 if not enough data
  unsigned char GetDataIdentifier( unsigned char* Data, int Length )
  {
    if ( Length < 9 )
      return 0;
    int hlength = Data[8];
    if ( Length < 9 + hlength )
      return 0;
    return Data[ 9 + hlength - 1 ];
  }

  cRecordingController::cRecordingController()
  {
    listeners = (iRecordingPlugin**)malloc( sizeof(iRecordingPlugin*)*256 );
    for (int i=0; i < 256; i++)
      listeners[i] = 0;
  }
  
  cRecordingController::~cRecordingController()
  {
    free (listeners);
  }
  void cRecordingController::Subscribe(unsigned char DataIdentifier, iRecordingPlugin* plugin)
  {
    if ( listeners[ DataIdentifier ] == 0 )
      listeners[ DataIdentifier ] = plugin;
  }
  void cRecordingController::Unsubscribe(unsigned char DataIdentifier, iRecordingPlugin* plugin)
  {
    
    if ( listeners[ DataIdentifier ] != 0 && listeners[ DataIdentifier ] == plugin )
      listeners[ DataIdentifier ] = 0;
    
  }

  bool cRecordingController::isExtendedPacket(unsigned char* Data, int Length)
  {
    if ( Length < 9 )
      return false;
    if ( Data[0] != 0x00 || Data[1] != 0x00 || Data[2] != 0x01 )
      return false;
    if ( Data[3] != PRIVATE_STREAM_1 )
      return false;
    
    if ( !(Data[7] & PES_EXTENSION_MASK) )
      return false;

    int hlength = Data[8];
    
    if ( ( Data[ 9 + hlength - 3 ] & PES_EXTENSION2_MASK ) == 1 
	 && Data[ 9 + hlength - 2 ] == 0x81)
      return true;

    return false;

  }


  void cRecordingController::Receive(unsigned char* Data, int Length)
  {
    if ( isExtendedPacket( Data, Length ) )
    {
      unsigned char DataIdentifier = GetDataIdentifier( Data, Length );
      if ( listeners[ DataIdentifier ] != 0 )
	listeners[ DataIdentifier ] -> Receive( DataIdentifier, Data, Length );
    }
    else
    {
    }
  }

} // namespace
