vdr/vdr-plugin-subtitles COPYING DVBsubs.patch HISTORY Makefile README clut.c clut.h configuration.c configuration.h dec.c dec.h genclut.c i18n.c i18n.h menu.c menu.h object.c object.h page.c page.h receiver.c receiver.h region.c region.h renderer.c renderer.h replay.c replay.h subfilter.c subfilter.h subtitle.c subtitle.h subtitles.c sync.c sync.h viewer.c viewer.h

Darren Salt pkg-vdr-dvb-changes@lists.alioth.debian.org
Mon, 04 Apr 2005 22:53:38 +0000


Update of /cvsroot/pkg-vdr-dvb/vdr/vdr-plugin-subtitles
In directory haydn:/tmp/cvs-serv14519

Added Files:
	COPYING DVBsubs.patch HISTORY Makefile README clut.c clut.h 
	configuration.c configuration.h dec.c dec.h genclut.c i18n.c 
	i18n.h menu.c menu.h object.c object.h page.c page.h 
	receiver.c receiver.h region.c region.h renderer.c renderer.h 
	replay.c replay.h subfilter.c subfilter.h subtitle.c 
	subtitle.h subtitles.c sync.c sync.h viewer.c viewer.h 
Log Message:
Initial import

--- NEW FILE: dec.h ---
#ifndef __DVB_SUBTITLES_DECODER2_H
#define __DVB_SUBTITLES_DECODER2_H
#include <map>
#include <list>
#include <set>
#include <stdint.h>

// forward declarations
struct subtitling_segment;
class Region;
class Object;
class Clut;
class cSubtitlesPage;

typedef std::map<int, Region*> RegionMap;
typedef std::map<int, Object*> ObjectMap;
typedef std::map<int, Clut*> ClutMap;
typedef std::list<Region*> RegionList;
typedef std::list<cSubtitlesPage*> PageList;
typedef std::set<Object*> ObjectSet;

class cDecoder
{
public:
  cDecoder();
  virtual ~cDecoder();
  void addPesData(const unsigned char* Data, int Length, bool StartsNewPacket);
  bool PageAvailable();
  cSubtitlesPage* GetPage();
  void restart();

private:

  void reset();
  unsigned int available();


  void processSegment(subtitling_segment* Segment);
  void pageComposition(subtitling_segment* Segment);
  void regionComposition(subtitling_segment* Segment);
  void clutDefinition(subtitling_segment* Segment);
  void objectData(subtitling_segment* Segment);


  virtual void modeChange();
  virtual void acqPoint();
  virtual void normalCase();
  
  bool pageCompleted();
  
  Region* RegionById(int aId);
  Object* ObjectById(int aId);
  Clut*   ClutById(int aId);


  unsigned char* segmentBuffer;
  int readIndex, writeIndex,skip;
  bool pesFound;
  ObjectMap         iObjects;
  ClutMap           iCluts;
  RegionMap         iRegions;
  RegionList        iVisibleRegions;
  PageList          iPages;

  bool              iPageDecoded;
  int               iNumRegions;
  ObjectSet         iAvailableObjects;
  ObjectSet         iRequiredObjects;
  
  int               iDecodedTimeout;
  int64_t           iPagePts;

};


#endif

--- NEW FILE: subfilter.c ---
/*
 * SI section filter to gather subtitles information. 
 * cSubFilter has been derived from VDR's cPatFilter
 *
 * $Id: subfilter.c,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $
 */

#include "receiver.h"
#include "subfilter.h"
#include "replay.h"
#include "configuration.h"
#include <libsi/section.h>
#include <libsi/descriptor.h>
#include <vdr/device.h>
#include <vdr/thread.h>
#include <vdr/status.h>
#include <vdr/i18n.h>
#include <vdr/dvbsub.h>
#include <vdr/rcontroller.h>
#include <vdr/channels.h>
#include <vdr/tools.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include "menu.h"


class cOsdObject;

#define PMT_SCAN_TIMEOUT  10 // seconds

#define NO_SUBTITLES 0xFFFF 
#define USE_PREFERRED_LANGUAGES -1

class tSubtitleStream : public cListObject
{
 public:
    int languageIndex;
    int  type;
    int  pid;
    int  compositionPage;
    int  ancillaryPage;
    tSubtitleStream(int LanguageIndex, int Type, int Pid, int CompositionPage, int AncillaryPage);
    tSubtitleStream() { languageIndex = -1;}

    static tSubtitleStream FromString(const char *s);
    const char* ToString(void);

    bool operator==(const tSubtitleStream& right) const; 
};

tSubtitleStream::tSubtitleStream(int LanguageIndex, int Pid, int Type, int CompositionPage, int AncillaryPage)
    :languageIndex(LanguageIndex),type(Type), pid(Pid), compositionPage(CompositionPage), ancillaryPage(AncillaryPage)
{
}


tSubtitleStream tSubtitleStream::FromString(const char *s)
{
    char* langbuf = NULL;

    int pid;
    int type;
    int compositionPage;
    int ancillaryPage;

    int fields = sscanf(s, "%a[^=]=%d+%d+%d+%d", &langbuf, &pid, &compositionPage, &ancillaryPage, &type);

    int languageIndex = -1;
    if (langbuf)
	languageIndex = I18nLanguageIndex(langbuf);
    free(langbuf);

    if (fields == 5)
    {
	return tSubtitleStream(languageIndex, pid, type, compositionPage, ancillaryPage);
    }
    else
    {
	return tSubtitleStream();
    }
}

const char* tSubtitleStream::ToString(void)
{
    static char buffer[256];
    
    const char* langCode = I18nLanguageCode(languageIndex);
    
    if (!langCode)
	return NULL;

    char lang[4];
    lang[0] =  langCode[0];
    lang[1] =  langCode[1];
    lang[2] =  langCode[2];
    lang[3] = 0;


    snprintf(buffer, sizeof(buffer), "%s=%d+%d+%d+%d", lang, pid, compositionPage, ancillaryPage, type);

    return buffer;

}

bool tSubtitleStream::operator==(const tSubtitleStream& right) const
{
    return languageIndex==right.languageIndex && pid == right.pid &&
	type == right.type && compositionPage == right.compositionPage &&
	ancillaryPage == right.ancillaryPage;
}



// ---- cSubtitleChannel

class cSubtitleChannel : public cListObject
{
 private:
    tChannelID channelId;
    cList<tSubtitleStream> streams;
    int userLanguage;
    static char* buffer;
 public:
    cSubtitleChannel(){channelId = tChannelID::InvalidID;}
    cSubtitleChannel(tChannelID ChannelId);

    // Parse from String
    bool Parse(const char *s);
    const char* ToText();

    bool Save(FILE* file);

    // Adds a subtitle stream
    void AddStream(tSubtitleStream* Stream);

    //Returns true if Primary Language was available
    const tSubtitleStream* GetPrimary() const;

    //Returns true if Secondary Language was available
    const tSubtitleStream* GetSecondary() const;

    //Returns true if User selected language was available
    const tSubtitleStream* GetUser(void) const;

    // Returns true if requested language was available
    const tSubtitleStream* GetByLanguage(int Language) const;

    tChannelID GetId() const {return channelId;} 

    int GetUserLanguage() const {return userLanguage;} 
    void SetUserLanguage(int Language){userLanguage = Language;}

};

char* cSubtitleChannel::buffer = NULL;

cSubtitleChannel::cSubtitleChannel(tChannelID ChannelId)
{
    channelId = ChannelId;
    userLanguage = USE_PREFERRED_LANGUAGES;
}

const char* cSubtitleChannel::ToText()
{
    if (!channelId.Valid() || streams.Count() == 0)
	return NULL;
    
    free(buffer);

    asprintf(&buffer, "%s:%d:", *channelId.ToString(), userLanguage);
    bool first = true;
    for (tSubtitleStream* stream = streams.First(); stream; stream = streams.Next(stream))
    {
	if (stream->languageIndex != -1)
	{
	    char* buffer2 = NULL;
	    asprintf(&buffer2, first?"%s%s":"%s,%s",buffer,stream->ToString());
	    free(buffer);
	    buffer = buffer2;
	    first = false;
	}
    }
    return buffer;
}

bool cSubtitleChannel::Save(FILE* file)
{
    const char* string = ToText();
    if (string)
	fprintf(file, "%s\n", string);
    return true;
}


bool cSubtitleChannel::Parse(const char *s)
{
    char* cidbuf = NULL;
    char* streamsbuf = NULL;

    int fields = sscanf(s, "%a[^:]:%d:%a[^\n]", &cidbuf, &userLanguage, &streamsbuf);

    bool ret = false;

    if (fields == 3)
    {
	channelId = tChannelID::FromString(cidbuf);
	if (!channelId.Valid())
	{
	    ret = false;
	}
	else
	{
	    char *streamstr, *tok;
	    char *p = streamsbuf;
	    while ((streamstr = strtok_r(p, ",", &tok)) != NULL)
	    {
		tSubtitleStream stream = tSubtitleStream::FromString(streamstr);
		if (stream.languageIndex != -1)
		{
		    tSubtitleStream* newStream = new tSubtitleStream(stream);
		    AddStream(newStream);
		}
		p = NULL;
	    }
	    ret = (streams.Count() > 0);
	}
    }
    else
    {
	ret = false;
    }

    free(cidbuf);
    free(streamsbuf);

    return ret;
}

void cSubtitleChannel::AddStream(tSubtitleStream* Stream)
{

    streams.Add(Stream);
}

const tSubtitleStream* cSubtitleChannel::GetPrimary() const
{
    return GetByLanguage(gSubtitlesConfiguration.language);
}

const tSubtitleStream* cSubtitleChannel::GetSecondary() const
{
    return GetByLanguage(gSubtitlesConfiguration.language2);
}

const tSubtitleStream* cSubtitleChannel::GetUser() const
{
    return GetByLanguage(userLanguage);
}


const tSubtitleStream* cSubtitleChannel::GetByLanguage(int Language) const
{

    if (Language < 0 || Language > I18nNumLanguages)
	return false;

    for (tSubtitleStream* stream = streams.First(); stream; stream = streams.Next(stream))
    {

	if (Language == stream->languageIndex)
	{ 
	    return stream;
	}
    }
    return NULL;
}


using namespace RecordingPatch;

// ---- cSubtitlesChangedHandler
class cSubtitlesChangedHandler : public cStatus
{
 private:
    tChannelID currentChannelId;

    cSubtitlesReceiver *selectedReceiver;
    cSubtitlesReceiver *primaryReceiver;
    cSubtitlesReceiver *secondaryReceiver;
    cDvbSubtitlesReplay *primaryReplay;
    cDvbSubtitlesReplay *secondaryReplay;
    tSubtitleStream currentPrimary;
    tSubtitleStream currentSecondary;
    tSubtitleStream currentSelected;
    cDevice *device;
    cMutex mutex;
    void HandleReceiver(cSubtitlesReceiver*& Receiver, int Priority, 
			const cSubtitleChannel* newChannel, 
			int Language, tSubtitleStream& currentStream);
 protected:
    virtual void Replaying(const cControl *Control, const char *Name);

 public:
    cSubtitlesChangedHandler(cDevice* device=NULL);
    ~cSubtitlesChangedHandler();
    void SubtitlingUpdate(const cSubtitleChannel* newChannel);
    void ChannelChange(cDevice* device, const cSubtitleChannel* newChannel);

};

cSubtitlesChangedHandler::cSubtitlesChangedHandler(cDevice* Device)
{
    selectedReceiver = NULL;
    primaryReceiver = NULL;
    secondaryReceiver = NULL;
    primaryReplay = NULL;
    secondaryReplay = NULL;
    device = Device;
}

cSubtitlesChangedHandler::~cSubtitlesChangedHandler()
{
    delete primaryReceiver;
    delete secondaryReceiver;
    delete selectedReceiver;
    delete primaryReplay;
    delete secondaryReplay;
}

void cSubtitlesChangedHandler::Replaying(const cControl *Control, const char *Name)
{
    cMutexLock lock(&mutex);
    if (Name)
    {
	// replaying starts
	DELETENULL(primaryReceiver);
	DELETENULL(secondaryReceiver);
	DELETENULL(selectedReceiver);

	DELETENULL(primaryReplay);
	DELETENULL(secondaryReplay);
	currentPrimary = tSubtitleStream();
	currentSecondary = tSubtitleStream();

	primaryReplay = new cDvbSubtitlesReplay(1000,0x28);
	secondaryReplay = new cDvbSubtitlesReplay(900,0x29);
    }
    else
    {
	// replaying stops
	DELETENULL(primaryReplay);
	DELETENULL(secondaryReplay);
    }

}

void cSubtitlesChangedHandler::HandleReceiver(cSubtitlesReceiver*& Receiver, int Priority, const cSubtitleChannel* newChannel, int Language, tSubtitleStream& currentStream)
{
    const tSubtitleStream* newStream;
    if ((newStream=newChannel->GetByLanguage(Language)) != NULL)
    {
	if (!(*newStream == currentStream))
	{
	    if (Receiver != NULL)
	    {
		DELETENULL(Receiver);
		
	    }
	    Receiver = new cSubtitlesReceiver( newStream->pid, Priority );
	    Receiver->Start();
	    device->AttachReceiver(Receiver);
	    currentStream = *newStream;
	}
    }
    else
    {
	if (Receiver != NULL)
	{
	    DELETENULL(Receiver);
	    currentStream = tSubtitleStream();
	}
    }
}


void cSubtitlesChangedHandler::SubtitlingUpdate(const cSubtitleChannel* newChannel)
{    

    if (!newChannel || primaryReplay || secondaryReplay)
	return;

    cMutexLock lock(&mutex);

    if (device != NULL && newChannel->GetId()==currentChannelId)
    {
	if (newChannel->GetUserLanguage() == USE_PREFERRED_LANGUAGES)
	{
	    HandleReceiver(primaryReceiver, 1000, newChannel, gSubtitlesConfiguration.language,
			   currentPrimary);
	    HandleReceiver(secondaryReceiver,900, newChannel,gSubtitlesConfiguration.language2,
			   currentSecondary);
	    DELETENULL(selectedReceiver);currentSelected = tSubtitleStream();
	}
	else if (newChannel->GetUserLanguage() == NO_SUBTITLES)
	{
	    DELETENULL(primaryReceiver);currentPrimary = tSubtitleStream();
	    DELETENULL(secondaryReceiver);currentSecondary = tSubtitleStream();
	    DELETENULL(selectedReceiver);currentSelected = tSubtitleStream();
	}
	else
	{
	    DELETENULL(primaryReceiver);currentPrimary = tSubtitleStream();
	    DELETENULL(secondaryReceiver);currentSecondary = tSubtitleStream();
	    HandleReceiver(selectedReceiver, 1100, newChannel, newChannel->GetUserLanguage(), currentSelected);
	}
    }
}

void cSubtitlesChangedHandler::ChannelChange(cDevice* Device, const cSubtitleChannel* newChannel)
{

    cMutexLock lock(&mutex);


    // if we're replaying
    if (primaryReplay || secondaryReplay)
	return;

    DELETENULL(selectedReceiver);
    DELETENULL(primaryReceiver);
    DELETENULL(secondaryReceiver);
    currentPrimary = tSubtitleStream();
    currentSecondary = tSubtitleStream();
    currentSelected = tSubtitleStream();

    if (!newChannel || !Device)
    {
      currentChannelId = tChannelID::InvalidID;
      return;
    }

    currentChannelId = newChannel->GetId();
    device = Device;
    SubtitlingUpdate(newChannel);

}

static cSubtitlesChangedHandler SubHandler;

// cSubtitleChannels
class cSubtitleChannels : public cConfig<cSubtitleChannel>,
			  public cRwLock, 
			  public iPidQuery
{
 private:
    
 public:
    cSubtitleChannels();
    virtual ~cSubtitleChannels() {};
    void AddUpdate(cSubtitleChannel* Channel);
    const cSubtitleChannel* GetById(tChannelID ChannelId) const;
    bool Has(tChannelID ChannelId) const;
    void SetUserLanguage(tChannelID ChannelId, int Language);


    // iPidQuery
    virtual int GetPidByChannel( int DevNr, const cChannel* Channel, int Language );
};

int cSubtitleChannels::GetPidByChannel( int DevNr, const cChannel* Channel, int Language )
{

    if (  !gSubtitlesConfiguration.recording || Channel == NULL)
	return 0;

    time_t start = time(NULL);

    // wait max. 2 seconds for the SI information
    while (!Has(Channel->GetChannelID()) && (time(NULL)-start)<2)
    {
	usleep(10000);
    }

    const cSubtitleChannel* channel = GetById(Channel->GetChannelID());

    if (!channel)
    {  
        return 0;
    }

    const tSubtitleStream* stream;

    if ((Language == 1 && ((stream=channel->GetPrimary())!=NULL)) || 
 	(Language == 2 && ((stream=channel->GetSecondary())!=NULL)))
    {
	return stream->pid;
    }
    else
    {
	return 0;
    }
}


cSubtitleChannels::cSubtitleChannels()
{
    DvbSubtitlesRecording.Subscribe( this );
}


void cSubtitleChannels::AddUpdate(cSubtitleChannel* Channel)
{

    for (cSubtitleChannel* channel = First(); channel; channel = Next(channel))
    {
	if (channel->GetId() == Channel->GetId())
	{
	    int userLanguage = channel->GetUserLanguage();
	    Del(channel);
	    Channel->SetUserLanguage(userLanguage);
	    Add(Channel);
	    SubHandler.SubtitlingUpdate(Channel);
	    return;
	}
    }
    
    Add(Channel);
    SubHandler.SubtitlingUpdate(Channel);
}

const cSubtitleChannel* cSubtitleChannels::GetById(tChannelID ChannelId) const
{

    for (cSubtitleChannel* channel = First(); channel; channel = Next(channel))
    {
	if (channel->GetId() == ChannelId)
	{
	    return channel;
	}
    };
    return NULL;
}

bool cSubtitleChannels::Has(tChannelID ChannelId) const
{
    return (GetById(ChannelId) != 0);
}


void cSubtitleChannels::SetUserLanguage(tChannelID ChannelId, int Language)
{
    for (cSubtitleChannel* channel = First(); channel; channel = Next(channel))
    {
	if (channel->GetId() == ChannelId)
	{
	    if (channel->GetUserLanguage() != Language)
	    {
		channel->SetUserLanguage(Language);
		SubHandler.SubtitlingUpdate(channel);
	    }
	    return;
	}
    };

    cSubtitleChannel* channel= new cSubtitleChannel(ChannelId);
    channel->SetUserLanguage(Language);
    Add(channel);
}

static cSubtitleChannels SubChannels;

void LoadChannels(const char* FileName)
{
    SubChannels.Load(FileName);
}

void SaveChannels(void)
{
    SubChannels.Save();
}


// cSubtitlesStatus

class cSubtitlesStatus : public cStatus
{
 protected:
    virtual void ChannelSwitch(const cDevice *Device, int ChannelNumber);
};
void cSubtitlesStatus::ChannelSwitch(const cDevice *Device, int ChannelNumber)
{
    if (Device->IsPrimaryDevice() && ChannelNumber && 
	cDevice::PrimaryDevice()->CurrentChannel()==ChannelNumber)
    {
	cChannel *Channel = Channels.GetByNumber(ChannelNumber);
	cDevice* device = cDevice::PrimaryDevice()->ActualDevice();
	SubHandler.ChannelChange(device,SubChannels.GetById(Channel->GetChannelID()));
    }
}
static cSubtitlesStatus SubStatus;


// cLanguageItem

class cLanguageItem : public cOsdItem
{
 private:
    int language;
 public:
    cLanguageItem(const char *Text, int Language);
    int GetLanguage(){return language;}
};

cLanguageItem::cLanguageItem(const char *Text, int Language)
    :cOsdItem(Text), language(Language)
{
}


// cLanguageSelectionMenu

class cLanguageSelectionMenu : public cOsdMenu
{

 private:
    bool showAll;
    tChannelID channelId;

    void Setup(void);
    eOSState Select(void);
 public:
    cLanguageSelectionMenu();
    virtual eOSState ProcessKey(eKeys Key);
};

cLanguageSelectionMenu::cLanguageSelectionMenu()
    :cOsdMenu("")
{
    showAll = false;


    int currentChannel = cDevice::PrimaryDevice()->CurrentChannel();

    cChannel* channel = Channels.GetByNumber(currentChannel);

    char* titlebuf = NULL;
    asprintf(&titlebuf, "%s - %s", channel->Name(), tr("Choose Language"));
    cOsdMenu::SetTitle(titlebuf);
    free(titlebuf);
    channelId = channel->GetChannelID();

    Setup();
}

void cLanguageSelectionMenu::Setup(void)
{

    const cSubtitleChannel* schannel = SubChannels.GetById(channelId);
    
    if (!schannel) 
    {
	cSubtitleChannel* nchannel = new cSubtitleChannel(channelId);
	SubChannels.Add(nchannel);
	schannel = nchannel;
    }

    const char * const * languages = I18nLanguages();


    int userLanguage = schannel->GetUserLanguage();

    Clear();

    Add(new cLanguageItem(tr("No Subtitles"), NO_SUBTITLES), userLanguage == NO_SUBTITLES);

    Add(new cLanguageItem(tr("Automatic"), USE_PREFERRED_LANGUAGES), userLanguage == USE_PREFERRED_LANGUAGES);


    for (int i = 0; i < I18nNumLanguages; i++)
    {
	const tSubtitleStream* stream;
	stream = schannel->GetByLanguage(i);
	
	if (stream != NULL || showAll)
	{
	    Add(new cLanguageItem(languages[i],i), userLanguage == i);
	}
    
    }

    SetHelp(showAll?tr("Available"):tr("All"), NULL, NULL, NULL);
    Display();
}

eOSState cLanguageSelectionMenu::Select(void)
{

    cLanguageItem* item = (cLanguageItem*)Get(Current());
    if (item)
    {
	SubChannels.SetUserLanguage(channelId, item->GetLanguage());
    }

    return osEnd;

}

eOSState cLanguageSelectionMenu::ProcessKey(eKeys Key)
{

    eOSState state = cOsdMenu::ProcessKey(Key);

    if (state == osUnknown)
    {

	if (Key == kOk)
	{
	    state = Select();
	}
	else if (Key == kRed)
	{
	    showAll = !showAll;
	    Setup();
	}
    }

    return state;

};


cOsdObject* GetLanguageSelector()
{
    return new cLanguageSelectionMenu();
}




// ---- cSubFilter

cSubFilter::cSubFilter()
{
    pmtIndex = 0;
    pmtPid = 0;
    lastPmtScan = 0;
    numPmtEntries = 0;
    Set(0x00, 0x00);  // PAT
}

cSubFilter::~cSubFilter()
{
}


void cSubFilter::SetStatus(bool On)
{
    cFilter::SetStatus(On);
    pmtIndex = 0;
    pmtPid = 0;
    lastPmtScan = 0;
    numPmtEntries = 0;
    
}

void cSubFilter::Trigger(void)
{
    numPmtEntries = 0;
}

bool cSubFilter::PmtVersionChanged(int PmtPid, int Sid, int Version)
{
    uint64_t v = Version;
    v <<= 32;
    uint64_t id = (PmtPid | (Sid << 16)) & 0x00000000FFFFFFFFLL;
    for (int i = 0; i < numPmtEntries; i++) 
    {
	if ((pmtVersion[i] & 0x00000000FFFFFFFFLL) == id) {
	    bool Changed = (pmtVersion[i] & 0x000000FF00000000LL) != v;
	    if (Changed)
		pmtVersion[i] = id | v;
	    return Changed;
	}
    }
    if (numPmtEntries < MAXPMTENTRIES)
	pmtVersion[numPmtEntries++] = id | v;
    return true;
}
    
void cSubFilter::Process(u_short Pid, u_char Tid, const u_char *Data, int Length)
{

    if (Pid == 0x00) 
    {
	if (Tid == 0x00) 
	{
	    if (pmtPid && time(NULL) - lastPmtScan > PMT_SCAN_TIMEOUT) 
	    {
		Del(pmtPid, 0x02);
		pmtPid = 0;
		pmtIndex++;
		lastPmtScan = time(NULL);
	    }
	    if (!pmtPid) 
	    {
		SI::PAT pat(Data, false);
		if (!pat.CheckCRCAndParse())
		    return;
		SI::PAT::Association assoc;
		int Index = 0;
		for (SI::Loop::Iterator it; pat.associationLoop.getNext(assoc, it); ) 
		{
		    if (!assoc.isNITPid()) 
		    {
			if (Index++ == pmtIndex) 
			{
			    pmtPid = assoc.getPid();
			    Add(pmtPid, 0x02);
			    break;
			}
		    }
		}
		if (!pmtPid)
		    pmtIndex = 0;
	    }
	}
    }
    else if (Pid == pmtPid && Tid == SI::TableIdPMT && Source() && Transponder()) 
    {


	SI::PMT pmt(Data, false);
	if (!pmt.CheckCRCAndParse())
	    return;
	if (!PmtVersionChanged(pmtPid, pmt.getTableIdExtension(), pmt.getVersionNumber())) 
	{
	    lastPmtScan = 0; // this triggers the next scan
	    return;
	}

	cChannel *Channel = Channels.GetByServiceID(Source(), Transponder(), pmt.getServiceId());
	
	if (Channel == NULL)
	    return;
	else
	{
	    SI::PMT::Stream stream;
	    cSubtitleChannel* schannel = new cSubtitleChannel(Channel->GetChannelID());
	    bool gotSubtitles = false;
	    for (SI::Loop::Iterator it; pmt.streamLoop.getNext(stream, it); ) 
	    {
	      //		stream = pmt.streamLoop.getNext(it);
		switch (stream.getStreamType()) 
		{
		    case 5: // STREAMTYPE_13818_PRIVATE
		    case 6: // STREAMTYPE_13818_PES_PRIVATE
		    {
			SI::Descriptor *d;
			for (SI::Loop::Iterator it; (d = stream.streamDescriptors.getNext(it)); ) 
			{
			    switch (d->getDescriptorTag()) {
				case SI::SubtitlingDescriptorTag:
				{
				    gotSubtitles = true;
				    SI::SubtitlingDescriptor *sd = (SI::SubtitlingDescriptor *)d;
				    SI::Loop::Iterator sit;
				    
				    SI::SubtitlingDescriptor::Subtitling sss;
				    while (sd->subtitlingLoop.getNext(sss, sit))
				    {
					if (sss.languageCode[0] == 0)
					    continue; // otherwise we get incomplete streams without language code
					tSubtitleStream *subStream = new tSubtitleStream(I18nLanguageIndex(sss.languageCode),stream.getPid(), sss.getSubtitlingType(),   sss.getCompositionPageId(), sss.getAncillaryPageId());
					schannel->AddStream(subStream);
				    }
				}
				break;
				default: ;
			    }
			    delete d;
			}
		    }
		    break;
		}
	    }
	    if (gotSubtitles && SubChannels.Lock(true,10)) 
	    {
		SubChannels.AddUpdate(schannel);
		SubChannels.Unlock();
	    }
	    else
	    {
		delete schannel;
	    }
	}
	lastPmtScan = 0; // this triggers the next scan
    }
}



--- NEW FILE: subtitle.h ---
#ifndef __DVB_SUBTITLES_SUBTITLE__
#define __DVB_SUBTITLES_SUBTITLE__

class cBitmap;
class Region;
// One subtitle
class cSubtitle
{
public:
    cSubtitle(Region* region);
    ~cSubtitle();
    cBitmap* GetBitmap(){return bitmap;}
    int X(){return x;}
    int Y(){return y;}
private:
    int x;
    int y;
    cBitmap* bitmap;

};

#endif

--- NEW FILE: object.h ---
#ifndef __DVB_SUBTITLES_OBJECT_H
#define __DVB_SUBTITLES_OBJECT_H


class Renderer;
class Region;

class Object {
 
public:

  Object( int aId );
  ~Object();
  void Decode(unsigned char* PixelData, int Size, int TopLength, int BottomLength);
  // Add this object to region aRegion to position x,y
  void AddToRegion( Region* aRegion, int x, int y );
  int Id();

private:

  void SubBlock( unsigned char* Buffer, int& Index, int Size, int &x, int& y );
  void Draw( int aX, int aY, int aPixelCode, int rl = 1 );
  bool decode4BppCodeString(unsigned char* Buffer, int& Index, bool& Low, int &x, int& y);
  // attributes
  int          iId;
  Renderer*    iRenderer;

};

#endif //__DVB_SUBTITLES_OBJECT_H

--- NEW FILE: sync.c ---
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <vdr/device.h>
#include <vdr/thread.h>
#include "sync.h"
#include "configuration.h"


#define MAX_WAIT_IN_SECS 40

class cStcSynchronizer : public cSynchronizer
{
public:
    cStcSynchronizer(){};
    virtual ~cStcSynchronizer(){};
    virtual void sync(int64_t pts);
 private:
    int64_t GetSTC(bool fix);
};



int64_t cStcSynchronizer::GetSTC(bool fix)
{

  int64_t stc =  cDevice::PrimaryDevice()->GetSTC();

  // add the 33rd bit if required
  if (fix)
  {
#if DEBUG
    fprintf(stderr, "cStcSynchronizer::sync - stc bugfix\n");
    fprintf(stderr, "cStcSynchronizer::sync - original stc=%lld\n",stc);
#endif
    stc |= (int64_t)1<<32;
  }
  return stc;
}

void cStcSynchronizer::sync(int64_t pts)
{
    active = true;

    
    bool fix = pts & (int64_t)1<<32;
    int64_t stc = GetSTC(fix);
    // no stc
    if (stc < 0)
	return;


    int64_t timeDiff = (pts-stc);
    if (pts<stc)
    {
	timeDiff += (int64_t)1<<33;
    }
    timeDiff /= 90;
 

#ifdef DEBUG
    fprintf(stderr, "cStcSynchronizer::sync\n");
    fprintf(stderr, "pts = %lld, stc = %lld\n",pts,stc);
    fprintf(stderr, "Wait time ~ %lld ms\n", timeDiff);
#endif

    

    // Sanity check so we don't wait too long 
    // sometimes FF cards alter PTS (and STC) so timeDiff can be huge
    if (timeDiff < MAX_WAIT_IN_SECS*1000)
	while (active && stc > 0 && stc < pts)
	{
	    usleep(100000);
	    int64_t newstc = GetSTC(fix);
	    //  backward jump in replay
	    if (newstc < stc)
		break;
	    stc = newstc;
	}
#ifdef DEBUG
    fprintf(stderr, "<-cStcSynchronizer::sync\n");
#endif
}

class cPtsSynchronizer : public cSynchronizer
{
public:
    cPtsSynchronizer():lastPts(0),lastTime(0),firstTime(0),firstPts(0){};
    virtual ~cPtsSynchronizer(){};
    virtual void sync(int64_t pts);
private:
    int64_t lastPts;
    int64_t lastTime;
    int64_t firstTime;
    int64_t firstPts;
};


void cPtsSynchronizer::sync(int64_t pts)
{
    int64_t now = msectime();

    if (firstPts == 0)
    {
	firstPts = pts;
	firstTime = now;
    }

    if (lastPts != 0)
    {
	// handle wrap
	if (pts<lastPts)
	{
	    firstPts = pts;
	    firstTime = now;
	}

	int64_t ptsDiff = pts-firstPts;
	int64_t showTime = firstTime + ptsDiff/90;
	int64_t diff = showTime-now;

#ifdef DEBUG
	fprintf(stderr, "->cPtsSynchronizer::sync\n");
	fprintf(stderr, "now-firstTime=%lld\n",(now-firstTime));
	fprintf(stderr, "pts-firstPts=%lld\n",(pts-firstPts));
	fprintf(stderr, "diff between time and pts = %lld\n",(pts-firstPts)/90-(now-firstTime));
	fprintf(stderr, "pts = %lld, lastPts = %lld\n",pts,lastPts);
        fprintf(stderr, "pts-lastPts in ms = %lld\n",(pts-lastPts)/90);
	fprintf(stderr, "now-lastTime = %lld\n", now-lastTime);
	fprintf(stderr, "configured delay = %d\n", gSubtitlesConfiguration.delay);
	fprintf(stderr, "old wait time=%lld\n", (pts-lastPts)/90-now+lastTime);
	fprintf(stderr, "Wait time ~ %lld ms\n", diff);
#endif
	showTime += gSubtitlesConfiguration.delay*1000;
	// sanity check
	if (diff < (MAX_WAIT_IN_SECS*1000))
	    while (active  && (now < showTime) )
	    {
		usleep(100000);
		now = msectime();
	    }
	else
	{
	    // probably a forward jump
	    firstPts = pts;
	    firstTime = now;
	}
    }
    lastPts = pts;
    lastTime = now;
#ifdef DEBUG
    fprintf(stderr, "<-cPtsSynchronizer::sync\n\n");
#endif
}

cSynchronizer* GetSynchronizer()
{
    if (gSubtitlesConfiguration.sync)
	return new cStcSynchronizer();
    else
	return new cPtsSynchronizer();
}


uint64_t msectime()
{

    struct timeval tv = {0,0};

    gettimeofday(&tv,0);
    
    uint64_t msec = ((int64_t)tv.tv_sec)*1000;
    msec += tv.tv_usec/1000;
    
    return msec;

}



--- NEW FILE: README ---
This is a "plugin" for the Video Disk Recorder (VDR).

Written by:                  Pekka Virtanen <pekka.virtanen@sci.fi>

Project's homepage:          http://virtanen.org/vdr/subtitles

Latest version available at: -""-

See the file COPYING for license information.

Contributors:
Ragnar Sundblad
 - The "old" SI scanner
 - Idea and partial implementation for OSD and recording patches

Rolf Ahrenberg
 - Fix for the "gray osd" bug.
 - I18n
 - Fix for recording patch memory leak

Teemu Rantanen
 - Support for multiple DVB cards
 - Bug fixes

Description:
DVB subtitles decoder. Records and displays DVB subtitles. Requires the
included patch to be applied to VDR.

Installation:
Note: Works only with VDR versions >=1.3.7

cd /path/to/vdr/PLUGINS/src
tar xvfmz /path/to/vdr-subtitles-x.y.z.tgz
ln -s subtitles-x.y.z subtitles
cd subtitles
cp DVBsubs.patch /path/to/vdr
cd /path/to/vdr
patch -p0 < DVBsubs.patch
make <YOUR VDR BUILD OPTIONS>
make plugins
./vdr -Psubtitles

--- NEW FILE: subtitle.c ---
#include "subtitle.h"
#include "region.h"
#include "configuration.h"
#include <vdr/osdbase.h>

cSubtitle::cSubtitle(Region* region)
    : x(0), y(0),bitmap(0)
{
    if (region != 0 && region->Canvas() != 0)
    {
	x = region->X();
	y = region->Y();
	bitmap = new cBitmap(region->Width(), region->Height(), gSubtitlesConfiguration.dxr3comp?2:4);
	bitmap->DrawBitmap(0,0,*region->Canvas());
    }
}
cSubtitle::~cSubtitle()
{
    delete bitmap;
}

--- NEW FILE: subfilter.h ---
/*
 * SI section filter to gather subtitles information. 
 * cSubFilter has been derived from VDR's cPatFilter
 *
 * $Id: subfilter.h,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $
 */

#ifndef __SUBTITLES_FILTER_H
#define __SUBTITLES_FILTER_H

#include <vdr/filter.h>
#include <stdint.h>

#define MAXPMTENTRIES 64

class cSubtitleChannel;
class cSubtitlesReceiver;
class sLanguageInfo;
class cDevice;
class cSubtitlesChangedHandler;

class cSubFilter : public cFilter {
private:
  time_t lastPmtScan;
  int pmtIndex;
  int pmtPid;
  uint64_t pmtVersion[MAXPMTENTRIES];
  int numPmtEntries;

  bool PmtVersionChanged(int PmtPid, int Sid, int Version);
protected:
  virtual void Process(u_short Pid, u_char Tid, const u_char *Data, int Length);
public:
  cSubFilter();
  ~cSubFilter();
  virtual void SetStatus(bool On);
  void Trigger(void);
  };
#endif // __SUBTITLES_FILTER_H

--- NEW FILE: dec.c ---
#include "dec.h"
#include "page.h"
#include <stdlib.h>
#include <stdint.h>
#include <netinet/in.h>
#include "clut.h"
#include "object.h"
#include "region.h"
#define SEGMENT_BUFFER_SIZE 100*1024
#define SEGMENT_SYNC_BYTE 0x0F
#define PRIVATE_STREAM_1 0xBD

enum {
  PAGE_COMPOSITION_SEGMENT = 0x10,
  REGION_COMPOSITION_SEGMENT= 0x11,
  CLUT_DEFINITION_SEGMENT = 0x12,
  OBJECT_DATA_SEGMENT = 0x13,
  END_OF_DISPLAY_SEGMENT = 0x80
};

// Page states
enum {
  NORMAL_CASE = 0,
  ACQUISITION_POINT,
  MODE_CHANGE,
  RESERVED
};


// Segment definitions

#define PACK  __attribute__((packed))

struct pes_data_field
{
  uint8_t data_identifier;
  uint8_t stream_identifier;
  uint8_t cont_byte;
} PACK;


struct subtitling_segment
{
  uint8_t  sync_byte ;
  uint8_t  segment_type ;
  uint16_t page_id ;
  uint16_t segment_length ;
} PACK;

struct page_composition_segment_part
{
    uint8_t  id;
    uint8_t  reserved;
    uint16_t horizontal_address;
    uint16_t vertical_address;
} PACK;

struct page_composition_segment
{
  uint8_t  sync_byte;
  uint8_t  segment_type;
  uint16_t page_id;
  uint16_t segment_length;
  uint8_t  timeout;
  uint8_t  version_state; // version(4), state(2), reserved(2);
  struct page_composition_segment_part region[1];
} PACK;

struct objects_to_regions
{
  uint16_t id;
  uint8_t  comp1; //type(2), provider flag 2, horiz. pos. high(4)
  uint8_t  horizontal_position_low;
  uint8_t  vertical_position_high; // reserved(4), vertical pos. high (4)
  uint8_t  vertical_position_low;
} PACK;


// XXX doesn't support textual objects
struct region_composition_segment
{
  uint8_t  sync_byte;
  uint8_t  segment_type;
  uint16_t page_id;
  uint16_t segment_length;
  uint8_t  id;
  uint8_t  version_fill_flag; // version (4), fill_flag(1), reserved (3)
  uint16_t width;
  uint16_t height;
  uint8_t  loc_depth;
  uint8_t  CLUT_id;
  uint8_t  _8bpc;
  uint8_t  _4_2bpc; // 4 bit pixel code (4), 2bpc(2), reserved(2)
  objects_to_regions object[1];
} PACK;

struct clut_definition_segment
{
  uint8_t  sync_byte;
  uint8_t  segment_type;
  uint16_t page_id;
  uint16_t segment_length;
  uint8_t  id;
  uint8_t  version_number; //version(4), reserved(4)
  // XXX
} PACK;

struct graphical_object_data_segment {
  uint8_t  sync_byte;
  uint8_t  segment_type;
  uint16_t page_id;
  uint16_t segment_length;
  uint16_t id;
  uint8_t  comp1; // version(4),coding_method(2),non_modif_clr_flg(1),rsvd(1)
  uint16_t top_field_data_block_length;
  uint16_t bottom_field_data_block_length;
} PACK;

struct textual_object_data_segment_part
{
   uint16_t character_code;
} PACK;

struct textual_object_data_segment {
  uint8_t  sync_byte;
  uint8_t  segment_type;
  uint16_t page_id;
  uint16_t segment_length;
  uint16_t id;
  uint8_t  comp1; // version(4),coding_method(2),non_modif_clr_flg(1),rsvd(1)
  uint8_t  number_of_codes;
  struct textual_object_data_segment_part codes[1];
} PACK;

typedef subtitling_segment end_of_display_set_segment;



cDecoder::cDecoder()
{

  reset();
  // XXX handle out of memory
  segmentBuffer = (unsigned char*)malloc(SEGMENT_BUFFER_SIZE);
}


cDecoder::~cDecoder()
{
  free( segmentBuffer );
  restart(); // FIXME
}


void cDecoder::addPesData(const unsigned char* Data, int Length, bool newPacket)
{

  if ( pesFound && newPacket )
  {
    //    if (writeIndex && readIndex != (writeIndex-1) )
    //    fprintf(stderr, "New PES packet but the old one isn't processed fully, readIndex=%i,writeIndex=%i\n",readIndex,writeIndex);
    reset();
  }

  if ( newPacket && Length > 8)
  {
    // pes header
    if ( Data[0] == 0x00 && Data[1] == 0x00 && Data[2] == 0x01 )
    {
      if ( Data[3] != PRIVATE_STREAM_1 )
	return; // reset?

      iPagePts  = (int64_t) (Data[ 9] & 0x0E) << 29 ;
      iPagePts |= (int64_t)  Data[ 10]         << 22 ;
      iPagePts |= (int64_t) (Data[ 11] & 0xFE) << 14 ;
      iPagePts |= (int64_t)  Data[ 12]         <<  7 ;
      iPagePts |= (int64_t) (Data[ 13] & 0xFE) >>  1 ;
#ifdef DEBUG
      fprintf(stderr, "sub pts = %20lld\n",iPagePts);
#endif
      // extract pes
      pesFound = true;
      int hlength = Data[8];
      skip=hlength+9;
    }
    else
    {
      reset();
      return;
    }
  }
  if ( !pesFound )
    return;

  if ( ( skip > 0 ) && ( Length <= skip ) )
  {
    skip-=Length;
    return;
  }


  if ( (writeIndex +Length-skip) > SEGMENT_BUFFER_SIZE)
  {
    //  fprintf(stderr, "overflow\n");
    reset();
    return;
  }

  // Copy pes payload to buffer
  memcpy( segmentBuffer + writeIndex,  Data + skip, Length-skip );
  writeIndex += Length-skip;
  skip=0;

  // Check PES packet for data identfiefier and subtitling stream id
  if ( readIndex==0 && writeIndex>=3 )
  {
    pes_data_field* pdf = (pes_data_field*)segmentBuffer;
    if ( pdf->data_identifier==0x20 && pdf->stream_identifier==0x00 )
    {
      readIndex=2;
    }
    else
    {
      //    fprintf(stderr, "Not a subtitling packet\n");
      reset();
      return;
    }
  }

  // process available segments
  while ( readIndex < writeIndex && segmentBuffer[readIndex] == SEGMENT_SYNC_BYTE )
  {
    if ( available() >= sizeof( subtitling_segment ) )
    {
      subtitling_segment* segment = (subtitling_segment*)(segmentBuffer+readIndex);
      unsigned int required_size = ntohs(segment->segment_length) + sizeof(subtitling_segment);

      if ( available() >= required_size )
      {
	processSegment( segment );
	readIndex += required_size;

	if ( pageCompleted() )
	{
	  iPages.push_back( new cSubtitlesPage( iVisibleRegions, iPagePts, iDecodedTimeout) );
	  iPageDecoded = false;
	}
      }
      else {
	/*fprintf(stderr, " not enough for actual segment\n");*/return;} // not enough data
    }
    else
      {/*fprintf(stderr, " not enough for segment header\n");*/return;} // not enough data
  }
  //  if ( segmentBuffer[readIndex] != 0xFF)
  //    fprintf(stderr, "Unaligned subtitling data\n");

}


void cDecoder::processSegment(subtitling_segment* Segment)
{

  Segment->page_id = ntohs(Segment->page_id);
  Segment->segment_length = ntohs(Segment->segment_length);

  switch ( Segment->segment_type )
  {
  case PAGE_COMPOSITION_SEGMENT:
    {
      pageComposition( Segment );
      break;
    }
  case REGION_COMPOSITION_SEGMENT:
    {
      regionComposition( Segment );
      break;
    }
  case CLUT_DEFINITION_SEGMENT:
    {
      clutDefinition( Segment );
      break;
    }
  case OBJECT_DATA_SEGMENT:
    {
      objectData( Segment );
    }
  case END_OF_DISPLAY_SEGMENT:
    {
      //
      break;
    }
  default:
    {
      //fprintf(stderr, "Unknown segment type (%02X)\n", Segment->segment_type );
      break;
    }
  }
}

void cDecoder::reset()
{
  writeIndex=0;
  readIndex=0;
  pesFound=false;
  iPageDecoded = false;
  iNumRegions = 0;
  iRequiredObjects.clear();
  iAvailableObjects.clear();
  iDecodedTimeout = 0;
  modeChange(); // reset != modeChange but for now it's the same
}



inline unsigned int cDecoder::available()
{
  int i = writeIndex-readIndex;
  if ( i < 0 )
    return 0;
  else
    return i;
}



void cDecoder::pageComposition(subtitling_segment* Segment)
{
  page_composition_segment* page = (page_composition_segment*)Segment;
  iPageDecoded = true;
  iVisibleRegions.clear();
#ifdef DEBUG
  fprintf(stderr, "Page composition: PageId = %i\n", page->page_id);
#endif
  int page_state = ( page->version_state & 0x0C ) >> 2;

  switch ( page_state )
  {
  case NORMAL_CASE:
    {
      normalCase();
      break;
    }
  case ACQUISITION_POINT:
    {
      acqPoint();
      break;
    }
  case MODE_CHANGE:
    {
      modeChange();
      break;
    }
  default:
    {
      // Reserved
      break;
    }
  }

  iDecodedTimeout = page->timeout;
  iNumRegions = (page->segment_length - 2) / sizeof(page_composition_segment_part);
  for (int i = 0; i < iNumRegions; i++)
  {
    Region* region = RegionById( page->region[i].id );
#ifdef DEBUG
    fprintf(stderr, "  Visible region id = %i\n",page->region[i].id);
#endif
    region->SetPosition( ntohs( page->region[i].horizontal_address ),
			 ntohs( page->region[i].vertical_address ) );
    iVisibleRegions.push_back( region );
  }


}
void cDecoder::regionComposition(subtitling_segment* Segment)
{
  region_composition_segment* rcs = (region_composition_segment*)Segment;
#ifdef DEBUG
  fprintf(stderr,"Region Composition: PageId = %i, RegionId=%i\n",
    	  rcs->page_id,rcs->id);
#endif
  Region* region = RegionById( rcs->id );
  bool fill_flag = ( rcs->version_fill_flag & 0x08 ) != 0;


  // Should't call SetSize if region already exists!
  region->SetSize( ntohs( rcs->width ), ntohs( rcs->height ) );
  region->SetClut( ClutById( rcs->CLUT_id ) );
  //  0001 1100
  static int depths[] = {2,4,8};



  int bpp = 2;
  int tmp = (rcs->loc_depth&0x1C)>>2;

  if (tmp>0 && tmp < 4)
  {
      bpp = depths[tmp-1];
  }

  tmp = (rcs->loc_depth & 0xE0)>>5;
  int loc = 0;
  if (tmp>0 && tmp < 4)
  {
      loc = depths[tmp-1];
  }

  region->SetBpp(bpp, loc);

  if ( fill_flag )
  {
      // clear region. Need to decode region_[842]bit_pixel_code
  }

  // object 2 region mapping

  int pl = sizeof (region_composition_segment) - sizeof( subtitling_segment ) - sizeof( objects_to_regions );
  int num_objects = (rcs->segment_length - pl) / sizeof(objects_to_regions);
  for ( int i = 0; i < num_objects; i++ )
  {
    if ( (rcs->object[i].comp1 & 0xC0) )
    {
      //      fprintf(stderr, "Textual objects not supported\n");
      return;
    }

    Object* object = ObjectById( ntohs(rcs->object[i].id) );
    int x = ((rcs->object[i].comp1 & 0x0F ) << 8) + rcs->object[i].horizontal_position_low;
    int y = ((rcs->object[i].vertical_position_high & 0x0F ) << 8) + rcs->object[i].vertical_position_low;
    object->AddToRegion( region, x, y );
    iRequiredObjects.insert( object );
    --iNumRegions;
  }
}
void cDecoder::clutDefinition(subtitling_segment* Segment)
{

  clut_definition_segment* cd = (clut_definition_segment*)Segment;
#ifdef DEBUG
  fprintf(stderr, "Clut definition: PageId = %i, CLUT id =%i\n", cd->page_id,
  	  cd->id);
#endif

  Clut* clut = ClutById(cd->id);

  unsigned char* data = (unsigned char*)Segment +
      sizeof(clut_definition_segment);

  int size = cd->segment_length -
      (sizeof(clut_definition_segment)-2);

  clut->Decode(data,size);

}
void cDecoder::objectData(subtitling_segment* Segment)
{
  graphical_object_data_segment* ods = (graphical_object_data_segment*)Segment;

  if ( ods->comp1 & 0x0C )
  {
    //  fprintf(stderr, "Textual objects not supported\n");
    return;
  }

  // convert 16bit values
  ods->id = ntohs(ods->id);
  ods->top_field_data_block_length = ntohs(ods->top_field_data_block_length);
  ods->bottom_field_data_block_length = ntohs(ods->bottom_field_data_block_length);
#ifdef DEBUG
  fprintf(stderr, "Object data: PageId = %i, ObjectId = %i\n", ods->page_id,
  	  ods->id);
#endif

  Object* object = ObjectById( ods->id );
#ifdef DEBUG
  //fprintf( stderr, "Segment-length = %i\n", ods->segment_length );
#endif

  // ugh
  unsigned char* pixel_data =  (unsigned char*)(Segment);
  pixel_data += sizeof(graphical_object_data_segment);

  int pixel_data_size = ods->segment_length- ( sizeof(graphical_object_data_segment) - sizeof(subtitling_segment));

  object->Decode(pixel_data,
		 pixel_data_size,
		 ods->top_field_data_block_length,
		 ods->bottom_field_data_block_length
		 );
  iAvailableObjects.insert( object );
}




Region* cDecoder::RegionById(int aId)
{

  RegionMap::iterator i = iRegions.find( aId );

  if ( i != iRegions.end() )
    return i->second;

  // No region found -> create one
  Region* region = new Region( aId );
  iRegions[ aId ] =  region;
  return region;

}

Object* cDecoder::ObjectById(int aId)
{

  ObjectMap::iterator i = iObjects.find( aId );

  if ( i != iObjects.end() )
    return i->second;

  // No object found -> create one
  Object* object = new Object( aId );
  iObjects[ aId ] = object;
  return object;


}

Clut*  cDecoder::ClutById(int aId)
{

  ClutMap::iterator i = iCluts.find( aId );

  if ( i != iCluts.end() )
    return i->second;


  // No clut found -> create one
  Clut* clut = new Clut( aId );
  iCluts[ aId ] =  clut;
  return clut;

}


bool cDecoder::pageCompleted()
{
  return ( iPageDecoded && ( iNumRegions == 0 ) && ( iRequiredObjects == iAvailableObjects ) );
}


void cDecoder::modeChange()
{
  iVisibleRegions.clear();
  iRequiredObjects.clear();
  iAvailableObjects.clear();

  for (RegionMap::iterator i = iRegions.begin();
       i != iRegions.end();
       ++i)
  {
    Region* region = i->second;
    delete region;
  }
  iRegions.clear();

  for (ObjectMap::iterator i = iObjects.begin();
       i != iObjects.end();
       ++i)
  {
    Object* object = i->second;
    delete object;
  }
  iObjects.clear();

  for (ClutMap::iterator i = iCluts.begin();
       i != iCluts.end();
       ++i)
  {
    Clut* clut = i->second;
    delete clut;
  }
  iCluts.clear();
}

void cDecoder::acqPoint()
{

}
void cDecoder::normalCase()
{
}

bool cDecoder::PageAvailable()
{
  return (iPages.begin() != iPages.end());

}

cSubtitlesPage* cDecoder::GetPage()
{
  if (iPages.begin() == iPages.end())
    return 0;


  cSubtitlesPage* page = iPages.front();
  iPages.pop_front();
  return page;

}

void cDecoder::restart()
{
  while (!iPages.empty())
  {
    cSubtitlesPage* page = iPages.front();
    delete page;
    iPages.pop_front();
  }
  reset();
}


--- NEW FILE: sync.h ---
#include <sys/types.h>
#include "configuration.h"

class cSynchronizer
{
public:
    cSynchronizer(){};
    virtual ~cSynchronizer(){active=false;}
    virtual void sync(int64_t pts) = 0;
    virtual void stop(){active=false;}
protected:
    bool active;
};

uint64_t msectime();
cSynchronizer* GetSynchronizer();

--- NEW FILE: object.c ---
#include <stdio.h>
#include "object.h"
#include "renderer.h"
#include "clut.h"

Object::Object( int aId ) : iId(aId)
{
  iRenderer = NULL;

}

Object::~Object()
{
  delete iRenderer;
}

int Object::Id()
{

  return iId;

}


void Object::AddToRegion( Region* aRegion, int x, int y )
{

  // Make this to be a list of <region,position> pairs to which to draw to
  // XXX Only support for object to be draw to a one region/position
  // Works for finnish dtv
  
  if ( iRenderer )
    delete iRenderer;
  iRenderer = new Renderer( aRegion, x, y );

}



inline void Object::Draw( int aX, int aY, int aPixelCode, int rl )
{
  
  // for each renderer
  if (iRenderer)
    iRenderer->Draw( aX, aY, aPixelCode, rl );

}


void Object::Decode(unsigned char* PixelData, int Size, int TopLength, int BottomLength)
{
  int x = 0;
  int y = 0;
  //  fprintf(stderr, "Size=%i, TopLength=%i, BottomLength=%i, s-t-b=%i\n",Size, TopLength, BottomLength, Size-TopLength-BottomLength );
 
  
  if (Size < TopLength )
  {
    //    fprintf(stderr, "Too little data for decoding Top(and bottom) field\n");
    return;
  }
  int index = 0;
  while ( index < TopLength )
  {
    SubBlock( PixelData, index, TopLength, x, y );
  }
  //  fprintf(stderr, "Index = %i, TopLength=%i \n",index, TopLength );
  unsigned char* bottom = PixelData+TopLength;
  if (Size < TopLength+BottomLength)
  {
    //    fprintf(stderr, "Too little data for decoding Bottom field\n");
    return;
  }
  
  index = 0;
  x = 0;
  y =1;
  while ( index < BottomLength )
  {
    SubBlock( bottom, index, BottomLength, x, y );
  }
}


inline unsigned char nibbleIterator( unsigned char* Buffer, int& Index, bool& Low )
{
  unsigned char ret = Buffer[ Index ];
  if ( Low )
  {
    ret &= 0x0F;
    Index++;
  }
  else
    ret >>= 4;
  
  Low = !Low;
  return ret;

}


void Object::SubBlock( unsigned char* Buffer, int& Index, int Size, int &x, int& y )
{
  
  unsigned char data_type = Buffer[Index++];
  switch ( data_type )
  {
  case 0x10:
    {
      //      fprintf(stderr, "2 bit per pixel objects not supported\n");
      break;
    }
  case 0x11:
    {
      if (iRenderer)
      {
	// If there's a fully transparent colour, plot one pixel using it.
	// This is to cause it to be included in the bitmap's palette (which
	// is extended as entries in this object's palette are used).
	const Clut *clut = iRenderer->GetClut ();
	const cSubtitlesPalette *palette = clut ? clut->GetPalette (4) : 0;
	if (palette)
	{
	  int entries = palette->GetNumColors ();
	  const uint32_t *colours = palette->GetColors ();
	  int index = -1;
	  while (++index < entries && (colours[index] & 0xFF000000))
	    ;
	  if (index < entries)
	    Draw (x, y, index);
	}
      }
      bool low = false;
      while ( Index < Size && decode4BppCodeString( Buffer, Index, low, x, y ) );
      //byte align
      if (low)
	Index++;
      break;
    }
  case 0x12:
    {
      //      fprintf(stderr, "8 bit per pixel objects not supported\n");
      break;
    }
  case 0x20:
    {
      break;
    }
  case 0x21:
    {

      break;
    }
  case 0x22:
    {

      break;
    }
  case 0xF0:
    {
      y += 2;
      x = 0;
      break;
    }
  default:
    {
      //fprintf(stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!unknow data_type %02X\n", data_type );
    }
  }
  

}


inline bool Object::decode4BppCodeString(unsigned char* Buffer, int& Index, bool& Low,  int&x, int& y) 
{
  int code = nibbleIterator( Buffer, Index, Low );
  if ( code != 0 )
  {
    // Code=CCCC
    Draw( x++, y, code );
  }
  else
  {
    // code == 0000 XXXX
    code = nibbleIterator( Buffer, Index, Low );
    bool switch_1 = (code & 0x8) != 0;
    if ( !switch_1 )
    {
      // Code 0000 0XXX
      if ( code == 0x0 )
	return false; // end of string signal ( Code == 0000 0000 )
      // Code 0000 0RRR
      // rl RRR + 2
      Draw( x, y, 0, code + 2 );
      x += code + 2;
    }
    else
    {
      // CODE 0000 1XXX
      bool switch_2 = ( code & 0x04 ) != 0;
      if ( !switch_2 )
      {
	// CODE 0000 10XX
	int rl = ( code & 0x3 ) + 4;
	int code = nibbleIterator( Buffer, Index, Low );
	Draw( x, y, code, rl );
	x += rl;
      }
      else
      {
	// CODE 0000 11XX
	int switch_3 = code & 0x3;
	switch ( switch_3 )
	{
	case 0x0:
	  {
	    Draw( x++, y, 0);
	    break;
	  }
	case 0x1:
	  {
	    Draw( x, y, 0, 2);
	    x += 2;
	    break;
	  }
	case 0x2:
	  {
	    // Code 0000 1110 RRRR CCCC
	    int rl = nibbleIterator( Buffer,  Index, Low ) + 9;
	    code = nibbleIterator( Buffer, Index, Low );
	    Draw( x, y, code, rl );
	    x += rl;
	    break;
	  }
	case 0x3:
	  {
	    // Code 0000 1111 RRRR RRRR CCCC
	    int rl = ( nibbleIterator( Buffer, Index, Low ) << 4 ) +
	      nibbleIterator( Buffer, Index, Low ) + 25;
	    int code = nibbleIterator( Buffer, Index, Low );
	    Draw( x, y, code, rl );
	    x += rl;
	    break;
	  }
	}
	
      }
      
    }
  }
  return true;
}



--- NEW FILE: menu.h ---
/*
 * menu.h: Interface for getting Configuration menus
 *
 * $Id: menu.h,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $
 */
#ifndef __SUBTITLES_MENU_H
#define __SUBTITLES_MENU_H
class cOsdObject;
class cMenuSetupPage;
cOsdObject *GetLanguageSelector();
cMenuSetupPage *GetSetup();
#endif //__SUBTITLES_MENU_H



--- NEW FILE: viewer.h ---
#ifndef __DVB_SUBTITLES_VIEWER_H
#define __DVB_SUBTITLES_VIEWER_H

#include <vdr/osdcontroller.h>

class cOsd;
class cSubtitlesPage;
class cMutex;
class cSubtitlesPage;


using namespace NonInteractiveOsdPatch;

class SubtitlesViewer : public cOsdListener
{

public:
  
  SubtitlesViewer( );
  virtual ~SubtitlesViewer();
  void Show();
  void Hide();
  void SetPage( cSubtitlesPage* page );
  void Clear();
  void Flush();

private:

  void DrawPage();
  cOsd*  iOsd;
  cMutex*    iMutex;
  int iWinHandle;
  bool iShowing;
  cSubtitlesPage* iCurrentPage;

};

#endif

--- NEW FILE: page.c ---
#include "page.h"
#include "region.h"
#include <stdio.h>
#include "subtitle.h"

uint64_t cSubtitlesPage::debug = 0;

cSubtitlesPage::cSubtitlesPage( RegionList regions, int64_t pts, int timeout )
  :iPts( pts ), object_id(++debug),iTimeout(timeout)
{

  for (RegionList::iterator i = regions.begin(); 
       i != regions.end(); 
       i++ )
    {
	iSubtitles.push_back( new cSubtitle(*i) );
    }
}
cSubtitlesPage::~cSubtitlesPage()
{
  while(!iSubtitles.empty())
    {
	cSubtitle* sub = iSubtitles.front();
	iSubtitles.pop_front();
	delete sub;
    }
}


--- NEW FILE: subtitles.c ---
/*
 * subtitles.c: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id: subtitles.c,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $
 */

#include <map>
#include <vdr/plugin.h>
#include <vdr/device.h>
#include <vdr/i18n.h>
#include <vdr/tools.h>
#include <vdr/config.h> // VDRVERSION
#include "subfilter.h"
#include "configuration.h"
#include "i18n.h"
#include "menu.h"

static const char *VERSION        = "0.3.7";
static const char *DESCRIPTION    = "DVB subtitles decoder";

static const char *MAINMENUENTRY  = "Choose Language (DVB Subtitles)";

#if VDRVERSNUM && VDRVERSNUM < 10319
#error "This version of DVB subtitles only works with vdr  version >= 1.3.19"
#endif

class cOsdObject;
class cMenuSetupPage;

class cPluginSubtitles : public cPlugin
{
private:
  // Add any member variables or functions you may need here.

  cSubFilter* iFilters[MAXDEVICES];

public:
  cPluginSubtitles(void);
  virtual ~cPluginSubtitles();
  virtual const char *Version(void) { return VERSION; }
  virtual const char *Description(void) { return tr(DESCRIPTION); }
  virtual const char *CommandLineHelp(void);
  virtual bool ProcessArgs(int argc, char *argv[]);
  virtual bool Start(void);
  virtual void Housekeeping(void);
  virtual const char *MainMenuEntry(void) { return (gSubtitlesConfiguration.mainmenu>0?tr(MAINMENUENTRY):NULL); }
  virtual cOsdObject *MainMenuAction(void);
  virtual cMenuSetupPage *SetupMenu(void);
  virtual bool SetupParse(const char *Name, const char *Value);

  };

cPluginSubtitles::cPluginSubtitles(void)
{

    for (int i = 0; i < MAXDEVICES; i++)
    {
	iFilters[i] = NULL;
    }
  // Initialize any member variables here.
  // DON'T DO ANYTHING ELSE THAT MAY HAVE SIDE EFFECTS, REQUIRE GLOBAL
  // VDR OBJECTS TO EXIST OR PRODUCE ANY OUTPUT!
}

cPluginSubtitles::~cPluginSubtitles()
{
  // Clean up after yourself!ss

    SaveChannels();

    for (int i=0; i < MAXDEVICES; i++)
    {
	DELETENULL(iFilters[i]);
    }
  
}

const char *cPluginSubtitles::CommandLineHelp(void)
{
  // Return a string that describes all known command line options.
  return NULL;
}

bool cPluginSubtitles::ProcessArgs(int argc, char *argv[])
{
  // Implement command line argument processing here if applicable.
  return true;
}

bool cPluginSubtitles::Start(void)
{

  RegisterI18n(Phrases);

  

  LoadChannels(AddDirectory(ConfigDirectory(),"subchannels.conf"));
  
  // Start any background activities the plugin shall perform.

  for (int i= 0; i < cDevice::NumDevices();i++)
  {
      iFilters[i] = new cSubFilter();
      cDevice *device = cDevice::GetDevice(i);
      device->AttachFilter(iFilters[i]);
  }
  return true;

}

void cPluginSubtitles::Housekeeping(void)
{
  // Perform any cleanup or other regular tasks.
}

cOsdObject *cPluginSubtitles::MainMenuAction(void)
{
  // Perform the action when selected from the main VDR menu.
  return GetLanguageSelector();

}

cMenuSetupPage *cPluginSubtitles::SetupMenu(void)
{
  // Return a setup menu in case the plugin supports one.
  return GetSetup();
}

bool cPluginSubtitles::SetupParse(const char *Name, const char *Value)
{
    return gSubtitlesConfiguration.Parse(Name,Value);
}
VDRPLUGINCREATOR(cPluginSubtitles); // Don't touch this!

--- NEW FILE: configuration.c ---
#include "configuration.h"
#include <strings.h>
#include <stdlib.h>
cSubtitlesConfiguration gSubtitlesConfiguration;

cSubtitlesConfiguration::cSubtitlesConfiguration()
{
    language = -1;
    language2 = -1;
    hearingImpaired = 0;
    widescreen = 0;
    recording = 1;
    enabled = 1;
    offset = 0;
    sync = 1;
    delay = 0;
    mainmenu = 0;
    dxr3comp = 0;
    bgTransparency = 0;
    fgTransparency = 0;
}

bool cSubtitlesConfiguration::Parse(const char *Name, const char *Value)
{

    // Parse your own setup parameters and store their values.
    if(!strcasecmp(Name, "Language")) language = atoi(Value);
    else if(!strcasecmp(Name, "HearingImpaired")) hearingImpaired = atoi(Value);
    else if(!strcasecmp(Name, "Record")) recording = atoi(Value);
    else if(!strcasecmp(Name, "VideoFormat")) widescreen = atoi(Value);
    else if(!strcasecmp(Name, "Enabled")) enabled = atoi(Value);
    else if(!strcasecmp(Name, "Offset")) offset = atoi(Value);
    else if(!strcasecmp(Name, "Sync")) sync = atoi(Value);  
    else if(!strcasecmp(Name, "Delay")) delay = atoi(Value);
    else if(!strcasecmp(Name, "Language2")) language2 = atoi(Value);
    else if(!strcasecmp(Name, "Mainmenu")) mainmenu = atoi(Value);
    else if(!strcasecmp(Name, "Dxr3comp")) dxr3comp = atoi(Value);
    else if(!strcasecmp(Name, "Transparency") ||
	    !strcasecmp(Name, "BackgroundTransparency")) bgTransparency = atoi(Value);
    else if(!strcasecmp(Name, "ForegroundTransparency")) fgTransparency = atoi(Value);
    else
	return false;
    return true;
}

--- NEW FILE: viewer.c ---
#include "region.h"
#include "page.h"
#include <vdr/osd.h>
#include <vdr/thread.h>
#include "viewer.h"
#include "configuration.h"
#include "subtitle.h"


SubtitlesViewer::SubtitlesViewer(  )
    :iOsd( NULL ), iShowing( false ),iCurrentPage(0)
{

  iMutex = new cMutex();

}
SubtitlesViewer::~SubtitlesViewer()
{
  cMutexLock lock(iMutex);
  iShowing = false;
  if (iCurrentPage)
      delete iCurrentPage;
  cOsd* tmp = iOsd;
  iOsd = NULL;
  delete tmp;
  
}

void SubtitlesViewer::Show()
{
 
  cMutexLock lock(iMutex);
#if DEBUG
  fprintf(stderr, "viewer::show\n");
#endif
  iShowing = true;
  DrawPage();
}

void SubtitlesViewer::Hide()
{
  cMutexLock lock(iMutex);
#if DEBUG
  fprintf(stderr, "viewer::hide\n");
#endif
  iShowing = false;
  if ( iOsd ){
//    iOsd->Hide( iWinHandle );
      cOsd* tmp = iOsd;
      iOsd = NULL;
    delete tmp;
  }
  iOsd = NULL;

}

void SubtitlesViewer::Flush()
{
  cMutexLock lock(iMutex);
  if (iOsd)
    iOsd->Flush();
}

void SubtitlesViewer::Clear()
{
  cMutexLock lock(iMutex);
  if (iCurrentPage != NULL)
  {
      delete iCurrentPage;
      iCurrentPage = 0;
  }
  if (iOsd)
  {
      cOsd* tmp = iOsd;
      iOsd = NULL;
    delete tmp;
    iOsd = NULL;
  }
  if ( !iShowing )
    return;
  iOsd = cOsdProvider::NewOsd( 0, gSubtitlesConfiguration.offset, true );

}

void enforceRange(int& value, int min, int max)
{
    if (value < min)
	value=min;

    if (value >max)
	value=max;
}
void SubtitlesViewer::SetPage( cSubtitlesPage* page )
{

  cMutexLock lock(iMutex);
  Clear();
  iCurrentPage = page;
  DrawPage();

}

void SubtitlesViewer::DrawPage()
{

  cMutexLock lock(iMutex);

  if (!gSubtitlesConfiguration.enabled)
      return;

  if (!iCurrentPage || !iShowing)
      return;

  if (!iOsd)
      iOsd = cOsdProvider::NewOsd( 0, gSubtitlesConfiguration.offset, true );
      

  if (!iOsd)
    return;

  SubtitleList subtitles = iCurrentPage->GetSubtitles();
 
  int numAreas = 0;
  tArea areas[MAXOSDAREAS];

  for (SubtitleList::iterator i = subtitles.begin(); 
       i != subtitles.end(); 
       i++ )
  {

      cSubtitle* subtitle = *i;
      cBitmap* bitmap = subtitle->GetBitmap();
      if (bitmap == NULL)
         continue; // zero-sized area?

      int x = subtitle->X();
      int y = subtitle->Y();
      int w = bitmap->Width();
      int h = bitmap->Height();


      w += w%4; // osd must be multiples of 4, works for 2 and 4 bpp

      // sanity checks
      enforceRange(w, 0, 720);
      enforceRange(h, 0, 576);

      enforceRange(x, 0, 720);
      enforceRange(y, 0, 576);

      tArea area = {x,y,x+w-1, y+h-1, gSubtitlesConfiguration.dxr3comp?2:4};
      areas[numAreas++] = area;
  }

  if (iOsd->CanHandleAreas(areas, numAreas) != oeOk)
  {
      dsyslog("DVB Subs: OSD can't handle areas - subtitles not shown\n");
      return;
  }
  
  iOsd->SetAreas(areas, numAreas);

  for (SubtitleList::iterator i = subtitles.begin(); 
       i != subtitles.end(); 
       i++ )
  {
      cSubtitle* subtitle = *i;
      cBitmap* bitmap = subtitle->GetBitmap();
      if (bitmap == NULL)
         continue; // zero-sized area?

      int x = subtitle->X();
      int y = subtitle->Y();
      
      enforceRange(x, 0, 720);
      enforceRange(y, 0, 576);

      iOsd->DrawBitmap( x, y , *bitmap );
  }
  Flush();

}



--- NEW FILE: configuration.h ---
#ifndef __DVB_SUBTITLES_CONFIGURATION__
#define __DVB_SUBTITLES_CONFIGURATION__

struct cSubtitlesConfiguration
{
  cSubtitlesConfiguration();
  bool Parse(const char *Name, const char *Value);
  int  language;
  int  secondaryLanguage;
  int  language2;
  int  hearingImpaired;
  int  widescreen;
  int  recording;
  int  enabled;
  int  offset;
  int  sync;
  int  delay;
  int  mainmenu;
  int  bpp;
  int  dxr3comp;
  int  bgTransparency, fgTransparency;
};

extern cSubtitlesConfiguration gSubtitlesConfiguration;

void LoadChannels(const char* FileName);
void SaveChannels(void);

#endif

--- NEW FILE: page.h ---
#ifndef __DVB_SUBTITLES_PAGE_H
#define __DVB_SUBTITLES_PAGE_H
#include "dec.h"
#include <list>

class cSubtitle;
typedef std::list<cSubtitle*> SubtitleList;

class cSubtitlesPage 
{
public:
  cSubtitlesPage( RegionList regions, int64_t pts, int timeout );
  ~cSubtitlesPage();
  int64_t GetPts() { return iPts; }
  SubtitleList GetSubtitles() { return iSubtitles; }
  int GetTimeout() { return iTimeout; }
private:
  SubtitleList iSubtitles;
  int64_t   iPts;
  static uint64_t debug;
  uint64_t object_id;
  int        iTimeout;
};

#endif //__DVB_SUBTITLES_PAGE_H

--- NEW FILE: HISTORY ---
VDR Plugin 'subtitles' Revision History
---------------------------------------
2005-02-15: Version 0.3.7
-New patch and bugfixes (Provided by Rolf Ahrenberg)

2004-11-23: Version 0.3.6
-Optimized palette generation (Thanks to Darren Salt)
-Fix for clearing a region with a proper color (Thanks to Darrent Salt)
-Configurable subtitles' transparency (Thanks to Darren Salt)
-Rendering optimization (Thanks to Darren Salt)

2004-10-25: Version 0.3.5
- Updated Makefile for better compiler/platform compability 
  (Thanks to Darren Salt and Rolf Ahrenberg)
- Finnish language update (Thanks to Rolf Ahrenberg)

2004-09-26: Version 0.3.4
-Fixed subfilter which broke after a change in libsi
-Bug fixes (Thanks to Sieme Teuling and Rolf Ahrenberg)

2004-06-16: Version 0.3.3
-Configurable background transparency (Thanks to Darren Salt)
-Swedish translations (Thanks to Håkan Lennestal)
-Bug fixes (Thanks to Darren Salt)

2004-05-30: Version 0.3.2
-Fixed the memory leak in the patch (thanks to Rolf Ahrenberg)
-Fixed the bug where the subtitles from the live channel where shown while
watching a recording (Thanks to Rolf Ahrenberg and Jouni Karvo)

2004-05-27: Version 0.3.1
-VDR 1.3.7 compability
-Fixed a bug where a recorded subtitles where shown while watching a recording
(Thanks to Rolf Ahrenberg for reporting this)

2004-05-06: Version 0.3.0
-New and improved, asynchronic, SI scanner for you zapping pleasure
-Per Channel Language Setting
 -Main menu language selector (can be disabled in the setup)
-Implemented Color Look-Up Table decoding and 4bit graphics
 -Setup option for "DXR compability" aka 2bit graphics and fixed palette.

2004-03-13: Version 0.1.4
-Fixed a core dump when VDR shuts down (Thanks to Teemu Rantanen)
-Subtitles are re-shown after user OSD activity

2004-01-06: Version 0.1.3
-Fix for systems with multiple cards (Thanks to Teemu Rantanen)
-Fixed a problem where recorded subtitles were shown if recording
 started while replaying
-Fixed a compilation problem with some distributions

2003-12-17: Version 0.1.2
-Fixed synchronization with ff cards (Thanks to Werner Fink)

2003-12-01: Version 0.1.1
-Secondary language (live, recording, replay)
-Configuration menu enhancements (Thanks to Klaus Schmidinger)

2003-11-18: Version 0.1.0
- Synchronization
   * STC syncronization
   * Fixed synchronization with configurable delay
- I18N. Thanks to Rolf Ahrenberg.
- No limitations on the positions of the subtitles

2003-09-13: Version 0.0.4
- Fixed the "gray osd" bug. Thanks to Rolf Ahrenberg.
- Fixed the problem with plugins that use OSD. Thanks to Ragnar Sundblad.

2003-07-21: Version 0.0.3
- Subtitles offset. Move subtitles up/down
- Possibility to disable subtitles viewing
  (requires channel switch to take effect)
- Fixed a high load problem with replay.c

2003-06-07: Version 0.0.2b
- Gcc 3.* compatibility
- Changed OSD colors for better quality graphics

2003-05-31: Version 0.0.2
- Recording & Replaying
- Non-interactive OSD
- Configuration
- Runtime cache for Service Information (SI)

2003-05-08: Version 0.0.1

- Initial revision.

--- NEW FILE: region.h ---
#ifndef __DVB_SUBTITLES_REGION_H
#define __DVB_SUBTITLES_REGION_H

// forward declarations
class Object;
class Position;
class Clut;
class cBitmap;

class Region {
  
public:
  
  Region( int aId );
  ~Region();
  //  void AddObject( Object* object, Position aPosition );
  void SetSize( int aWidth, int aHeight );
  void SetBpp(int Bpp, int Loc);
  void SetPosition( int aX, int aY );
  int X();
  int Y();
  int Width();
  int Height();
  void SetClut( Clut* aClut );
  const Clut *GetClut () { return iClut; }
  void Draw( int aX, int aY, int aPixelCode, int rl = 1);
  void Create( void );
  cBitmap* Canvas( void );
  int Id();


private:
  
  // methods
  void Reset();

  // attributes
  int           iId;
  Clut*         iClut;
  int           iWidth;
  int           iHeight;
  int           iX;
  int           iY;
  cBitmap*      iCanvas;
  int           bpp,loc;

};

#endif //__DVB_SUBTITLES_REGION_H

--- NEW FILE: DVBsubs.patch ---
diff -Nru vdr-1.3.21-vanilla/Makefile vdr-1.3.21-dvbsubs/Makefile
--- vdr-1.3.21-vanilla/Makefile	2005-02-13 12:13:45.000000000 +0200
+++ vdr-1.3.21-dvbsubs/Makefile	2005-02-13 18:25:53.461100864 +0200
@@ -40,6 +40,8 @@
        skinclassic.o skins.o skinsttng.o sources.o spu.o status.o svdrp.o themes.o thread.o\
        timers.o tools.o transfer.o vdr.o videodir.o
 
+OBJS += osdcontroller.o rcontroller.o dvbsub.o
+
 FIXFONT_ISO8859_1 = -adobe-courier-bold-r-normal--25-*-100-100-m-*-iso8859-1
 OSDFONT_ISO8859_1 = -adobe-helvetica-medium-r-normal--23-*-100-100-p-*-iso8859-1
 SMLFONT_ISO8859_1 = -adobe-helvetica-medium-r-normal--18-*-100-100-p-*-iso8859-1
diff -Nru vdr-1.3.21-vanilla/dvbplayer.c vdr-1.3.21-dvbsubs/dvbplayer.c
--- vdr-1.3.21-vanilla/dvbplayer.c	2005-01-14 16:00:56.000000000 +0200
+++ vdr-1.3.21-dvbsubs/dvbplayer.c	2005-02-13 18:28:08.354593936 +0200
@@ -14,6 +14,8 @@
 #include "ringbuffer.h"
 #include "thread.h"
 #include "tools.h"
+#include "rcontroller.h"
+#include "dvbsub.h"
 
 // --- cBackTrace ----------------------------------------------------------
 
@@ -304,6 +306,31 @@
   firstPacket = true;
 }
 
+static void StripExtendedPackets(uchar *b, int Length)
+{
+  for (int i = 0; i < Length - 6; i++) {
+      if (b[i] == 0x00 && b[i + 1] == 0x00 && b[i + 2] == 0x01) {
+         uchar c = b[i + 3];
+         int l = b[i + 4] * 256 + b[i + 5] + 6;
+         switch (c) {
+           case 0xBD: // dolby
+                if (RecordingPatch::RecordingController.isExtendedPacket(b + i , l)) {
+                   RecordingPatch::RecordingController.Receive( b + i, l );
+                   // continue with deleting the data - otherwise it disturbs DVB replay
+                   int n = l;
+                   for (int j = i; j < Length && n--; j++)
+                        b[j] = 0x00;
+                   }
+                break;
+           default:
+                break;
+           }
+         if (l)
+            i += l - 1; // the loop increments, too!
+         }
+      }
+}
+
 bool cDvbPlayer::NextFile(uchar FileNumber, int FileOffset)
 {
   if (FileNumber > 0)
@@ -472,6 +499,7 @@
                     }
                  }
               if (p) {
+                 StripExtendedPackets(p, pc);
                  int w = PlayPes(p, pc, playMode != pmPlay);
                  if (w > 0) {
                     p += w;
diff -Nru vdr-1.3.21-vanilla/dvbsub.c vdr-1.3.21-dvbsubs/dvbsub.c
--- vdr-1.3.21-vanilla/dvbsub.c	1970-01-01 02:00:00.000000000 +0200
+++ vdr-1.3.21-dvbsubs/dvbsub.c	2005-02-13 18:25:53.465100256 +0200
@@ -0,0 +1,18 @@
+#include "dvbsub.h"
+
+cDvbSubtitlesRecording DvbSubtitlesRecording;
+
+cDvbSubtitlesRecording::cDvbSubtitlesRecording(){ 
+  query=0; 
+}
+void cDvbSubtitlesRecording::Subscribe(iPidQuery* listener){ 
+  query = listener ;
+}
+
+int cDvbSubtitlesRecording::GetPidByChannel( int DevNr, const cChannel* Channel, int Language )
+{ 
+  if (query) 
+    return query->GetPidByChannel( DevNr, Channel,Language );
+  else
+    return 0;
+}
diff -Nru vdr-1.3.21-vanilla/dvbsub.h vdr-1.3.21-dvbsubs/dvbsub.h
--- vdr-1.3.21-vanilla/dvbsub.h	1970-01-01 02:00:00.000000000 +0200
+++ vdr-1.3.21-dvbsubs/dvbsub.h	2005-02-13 18:25:53.466100104 +0200
@@ -0,0 +1,21 @@
+class cChannel;
+class cRecordControl;
+
+class iPidQuery
+{
+public:
+  virtual int GetPidByChannel( int DevNr, const cChannel* Channel, int Language ) = 0;
+};
+class cDvbSubtitlesRecording
+{
+public:
+  cDvbSubtitlesRecording();
+  void Subscribe(iPidQuery* listener);
+private:
+  friend class cRecordControl;
+  int GetPidByChannel( int DevNr, const cChannel* Channel, int Language );
+  iPidQuery* query;
+};
+
+extern cDvbSubtitlesRecording DvbSubtitlesRecording;
+
diff -Nru vdr-1.3.21-vanilla/menu.c vdr-1.3.21-dvbsubs/menu.c
--- vdr-1.3.21-vanilla/menu.c	2005-02-06 13:33:13.000000000 +0200
+++ vdr-1.3.21-dvbsubs/menu.c	2005-02-13 18:25:53.474098888 +0200
@@ -28,6 +28,7 @@
 #include "themes.h"
 #include "timers.h"
 #include "transfer.h"
+#include "dvbsub.h"
 #include "videodir.h"
 
 #define MENUTIMEOUT     120 // seconds
@@ -3018,7 +3019,8 @@
   isyslog("record %s", fileName);
   if (MakeDirs(fileName, true)) {
      const cChannel *ch = timer->Channel();
-     recorder = new cRecorder(fileName, ch->Ca(), timer->Priority(), ch->Vpid(), ch->Apids(), ch->Dpids(), ch->Spids());
+     int SubPids[3] = {DvbSubtitlesRecording.GetPidByChannel(device->DeviceNumber(), ch, 1), DvbSubtitlesRecording.GetPidByChannel(device->DeviceNumber(), ch, 2), 0};
+     recorder = new cRecorder(fileName, ch->Ca(), timer->Priority(), ch->Vpid(), ch->Apids(), ch->Dpids(), SubPids);
      if (device->AttachReceiver(recorder)) {
         Recording.WriteSummary();
         cStatus::MsgRecording(device, Recording.Name());
diff -Nru vdr-1.3.21-vanilla/osd.c vdr-1.3.21-dvbsubs/osd.c
--- vdr-1.3.21-vanilla/osd.c	2004-12-19 14:27:38.000000000 +0200
+++ vdr-1.3.21-dvbsubs/osd.c	2005-02-13 18:25:53.476098584 +0200
@@ -15,6 +15,7 @@
 #include <sys/stat.h>
 #include <sys/unistd.h>
 #include "tools.h"
+#include "osdcontroller.h"
 
 // --- cPalette --------------------------------------------------------------
 
@@ -575,6 +576,7 @@
 // --- cOsd ------------------------------------------------------------------
 
 bool cOsd::isOpen = false;
+bool cOsd::niosd  = false;
 
 cOsd::cOsd(int Left, int Top)
 {
@@ -594,6 +596,8 @@
       delete bitmaps[i];
   delete savedRegion;
   isOpen = false;
+  if (!niosd)
+     NonInteractiveOsdPatch::OsdController.Show();
 }
 
 cBitmap *cOsd::GetBitmap(int Area)
@@ -715,8 +719,11 @@
   osdProvider = NULL;
 }
 
-cOsd *cOsdProvider::NewOsd(int Left, int Top)
+cOsd *cOsdProvider::NewOsd(int Left, int Top, bool dontHide)
 {
+  if (!dontHide)
+     NonInteractiveOsdPatch::OsdController.Hide();
+  cOsd::niosd = dontHide;
   if (cOsd::IsOpen())
      esyslog("ERROR: attempt to open OSD while it is already open - using dummy OSD!");
   else if (osdProvider)
diff -Nru vdr-1.3.21-vanilla/osd.h vdr-1.3.21-dvbsubs/osd.h
--- vdr-1.3.21-vanilla/osd.h	2004-10-16 13:33:44.000000000 +0300
+++ vdr-1.3.21-dvbsubs/osd.h	2005-02-13 18:25:53.478098280 +0200
@@ -215,6 +215,8 @@
   cBitmap *bitmaps[MAXOSDAREAS];
   int numBitmaps;
   int left, top, width, height;
+public:
+  static bool niosd;
 protected:
   cOsd(int Left, int Top);
        ///< Initializes the OSD with the given coordinates.
@@ -327,7 +329,7 @@
   cOsdProvider(void);
       //XXX maybe parameter to make this one "sticky"??? (frame-buffer etc.)
   virtual ~cOsdProvider();
-  static cOsd *NewOsd(int Left, int Top);
+  static cOsd *NewOsd(int Left, int Top, bool dontHide = false);
       ///< Returns a pointer to a newly created cOsd object, which will be located
       ///< at the given coordinates. When the cOsd object is no longer needed, the
       ///< caller must delete it. If the OSD is already in use, or there is no OSD
diff -Nru vdr-1.3.21-vanilla/osdcontroller.c vdr-1.3.21-dvbsubs/osdcontroller.c
--- vdr-1.3.21-vanilla/osdcontroller.c	1970-01-01 02:00:00.000000000 +0200
+++ vdr-1.3.21-dvbsubs/osdcontroller.c	2005-02-13 18:25:53.480097976 +0200
@@ -0,0 +1,132 @@
+#include "osdcontroller.h"
+#include "thread.h"
+
+namespace NonInteractiveOsdPatch
+{
+
+  class cListenerListObject : public cListObject
+  {
+  public:
+    cListenerListObject(int priority, cOsdListener* listener);
+    bool operator< (const cListObject &ListObject);
+
+    int iPriority;
+    cOsdListener* iListener;
+  };
+
+  cListenerListObject::cListenerListObject(int priority, cOsdListener* listener)
+    : cListObject(),iPriority(priority), iListener( listener )
+  {
+  }
+  bool cListenerListObject::operator< (const cListObject &ListObject)
+  {
+    
+    return iPriority > ((cListenerListObject *)&ListObject)->iPriority;
+  }
+
+  cOsdController OsdController;
+  
+  cOsdController::cOsdController()
+    : iShowing( false )
+  {
+    iMutex = new cMutex();
+    iListeners = new cList<cListenerListObject>;
+  }
+
+  cOsdController::~cOsdController()
+  {
+    delete iListeners;
+    delete iMutex;
+  }
+
+  bool cOsdController::Subscribe(  int priority, cOsdListener* listener )
+  {
+   
+    cMutexLock( iMutex );
+    if ( !listener )
+      return false;
+    
+    for ( cListenerListObject* llo = iListeners->First();
+	  llo; llo = iListeners->Next(llo))
+    {
+      // check for duplicates
+      if ( llo->iListener == listener )
+	return false;
+    }
+
+    cListenerListObject *lo = new cListenerListObject(priority, listener);
+    iListeners->Add( lo );
+    iListeners->Sort();
+
+    // Give osd to the new listener if it has higher priority
+    // than the current one
+    if ( iShowing && !iCurrent )
+    {
+      listener->Show();
+      iCurrent = lo;
+    }
+    else if ( iShowing && iCurrent && iCurrent->iPriority < priority )
+    {
+      iCurrent->iListener->Hide();
+      ShowHighest();
+
+    }
+    
+    return true;
+  }
+
+  void cOsdController::Unsubscribe( cOsdListener* listener )
+  {
+    cMutexLock( iMutex );
+    if ( !listener )
+      return;
+
+    for ( cListenerListObject* llo = iListeners->First();
+	  llo; llo = iListeners->Next(llo))
+    {
+
+      if ( llo->iListener == listener )
+      {
+	iListeners->Del( llo, true );
+	if ( iShowing && llo == iCurrent )
+	{
+	  listener->Hide();
+	  ShowHighest();
+	}
+	break;
+      }
+    }
+
+  } 
+
+  void cOsdController::Show()
+  {
+    cMutexLock( iMutex );
+    iShowing = true;
+    ShowHighest();
+
+  }
+  
+  void cOsdController::Hide()
+  {
+    cMutexLock( iMutex );
+    iShowing = false;
+    if ( iCurrent )
+      iCurrent->iListener->Hide();
+    iCurrent = NULL;
+  }
+
+  void cOsdController::ShowHighest()
+  {
+
+    cListenerListObject* llo = iListeners->First();
+
+    if ( llo )
+      llo->iListener->Show();
+
+    iCurrent = llo;
+
+  }
+
+
+}
diff -Nru vdr-1.3.21-vanilla/osdcontroller.h vdr-1.3.21-dvbsubs/osdcontroller.h
--- vdr-1.3.21-vanilla/osdcontroller.h	1970-01-01 02:00:00.000000000 +0200
+++ vdr-1.3.21-dvbsubs/osdcontroller.h	2005-02-13 18:25:53.481097824 +0200
@@ -0,0 +1,50 @@
+#ifndef __OSDCONTROLLER_H
+#define __OSDCONTROLLER_H
+
+#include "tools.h"
+
+
+#define MAX_OSD_LISTENERS 10
+
+class cOsd;
+class cMutex;
+
+namespace NonInteractiveOsdPatch
+{
+
+  class cOsdListener
+  {
+    
+  public:
+    virtual void Show() = 0;
+    virtual void Hide() = 0;
+
+  };
+    
+  class cListenerListObject;
+
+  class cOsdController
+  {
+  public:
+    cOsdController();
+    ~cOsdController();
+    bool Subscribe( int priority, cOsdListener* listener );
+    void Unsubscribe( cOsdListener* listner );
+
+  private:
+    friend class cOsdProvider;
+    friend class cOsd;
+    void Show();
+    void Hide();
+    void ShowHighest();
+
+    bool iShowing;
+    cMutex* iMutex;
+    cListenerListObject* iCurrent;
+    cList<cListenerListObject>* iListeners;
+
+  };
+  extern cOsdController OsdController;
+
+}
+#endif
diff -Nru vdr-1.3.21-vanilla/rcontroller.c vdr-1.3.21-dvbsubs/rcontroller.c
--- vdr-1.3.21-vanilla/rcontroller.c	1970-01-01 02:00:00.000000000 +0200
+++ vdr-1.3.21-dvbsubs/rcontroller.c	2005-02-13 18:25:53.482097672 +0200
@@ -0,0 +1,82 @@
+#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
diff -Nru vdr-1.3.21-vanilla/rcontroller.h vdr-1.3.21-dvbsubs/rcontroller.h
--- vdr-1.3.21-vanilla/rcontroller.h	1970-01-01 02:00:00.000000000 +0200
+++ vdr-1.3.21-dvbsubs/rcontroller.h	2005-02-13 18:25:53.483097520 +0200
@@ -0,0 +1,28 @@
+#ifndef __RECORDING_PATCH_OSD_CONTROLLER_H
+#define __RECORDING_PATCH_OSD_CONTROLLER_H
+
+class cDvbPlayer;
+namespace RecordingPatch {
+
+  class iRecordingPlugin
+  {
+  public:
+    virtual void Receive(unsigned char DataIdentifier, unsigned char* Data, int Length) = 0;
+  };
+  
+  class cRecordingController
+  {
+  public:
+    cRecordingController();
+    ~cRecordingController();
+    void Subscribe(unsigned char DataIdentifier, iRecordingPlugin* plugin);
+    void Unsubscribe(unsigned char DataIdentifer, iRecordingPlugin* plugin);
+    bool isExtendedPacket(unsigned char* Data, int Length);
+    void Receive(unsigned char* Data, int Length);
+  private:
+    iRecordingPlugin** listeners;
+  };
+  extern cRecordingController RecordingController;
+
+}
+#endif
diff -Nru vdr-1.3.21-vanilla/remux.c vdr-1.3.21-dvbsubs/remux.c
--- vdr-1.3.21-vanilla/remux.c	2005-02-13 16:36:23.000000000 +0200
+++ vdr-1.3.21-dvbsubs/remux.c	2005-02-13 18:25:53.490096456 +0200
@@ -381,6 +381,9 @@
 //pts_dts flags
 #define PTS_ONLY         0x80
 
+#define PES_EXTENSION    0x01
+#define PES_EXTENSION2   0x01
+
 #define TS_SIZE        188
 #define PID_MASK_HI    0x1F
 #define CONT_CNT_MASK  0x0F
@@ -425,6 +428,8 @@
   int ccErrors;
   int ccCounter;
   cRepacker *repacker;
+  uint8_t dataIdentifier;
+  static uint8_t eHeadr[];
   static uint8_t headr[];
   void store(uint8_t *Data, int Count);
   void reset_ipack(void);
@@ -432,16 +437,17 @@
   void write_ipack(const uint8_t *Data, int Count);
   void instant_repack(const uint8_t *Buf, int Count);
 public:
-  cTS2PES(int Pid, cRingBufferLinear *ResultBuffer, int Size, uint8_t AudioCid = 0x00, uint8_t SubStreamId = 0x00, cRepacker *Repacker = NULL);
+  cTS2PES(int Pid, cRingBufferLinear *ResultBuffer, int Size, uint8_t AudioCid = 0x00, uint8_t SubStreamId = 0x00, cRepacker *Repacker = NULL, uint8_t DataIdentifier = 0x00);
   ~cTS2PES();
   int Pid(void) { return pid; }
   void ts_to_pes(const uint8_t *Buf); // don't need count (=188)
   void Clear(void);
   };
 
+uint8_t cTS2PES::eHeadr[] = { 0x01, 0x81 }; // extension header
 uint8_t cTS2PES::headr[] = { 0x00, 0x00, 0x01 };
 
-cTS2PES::cTS2PES(int Pid, cRingBufferLinear *ResultBuffer, int Size, uint8_t AudioCid, uint8_t SubStreamId, cRepacker *Repacker)
+cTS2PES::cTS2PES(int Pid, cRingBufferLinear *ResultBuffer, int Size, uint8_t AudioCid, uint8_t SubStreamId, cRepacker *Repacker, uint8_t DataIdentifier)
 {
   pid = Pid;
   resultBuffer = ResultBuffer;
@@ -457,6 +463,7 @@
   tsErrors = 0;
   ccErrors = 0;
   ccCounter = -1;
+  dataIdentifier = DataIdentifier;
 
   if (!(buf = MALLOC(uint8_t, size)))
      esyslog("Not enough memory for ts_transform");
@@ -512,10 +519,21 @@
 
   switch (mpeg) {
     case 2:
+         if ( dataIdentifier == 0 ) {
             buf[6] = 0x80;
             buf[7] = 0x00;
             buf[8] = 0x00;
             count = 9;
+            }
+         else {
+            buf[6] = 0x80;
+            buf[7] = 0x01; // pes_extension_flag == 1
+            buf[8] = 0x03; // pes_header_data_length == 3
+            buf[9] = 0x01; // pes_extension_flag_2=1
+            buf[10]= 0x81; // marker_bit=1, pes_extension_data_length=1 
+            buf[11] = dataIdentifier;
+            count = 12;
+            }
             break;
     case 1:
             buf[6] = 0x0F;
@@ -657,12 +675,21 @@
           case 7:
                   if (!done && mpeg == 2) {
                      flag2 = Buf[c++];
+                     if ( dataIdentifier && (flag2 & PES_EXTENSION) ) {
+                        esyslog("Error: cannot add extension to pes packet. Disabling.");
+                        dataIdentifier = 0;
+                        }
+                     else {
+                        flag2 |= PES_EXTENSION;
+                        }
                      found++;
                      }
                   break;
           case 8:
                   if (!done && mpeg == 2) {
                      hlength = Buf[c++];
+                     if ( dataIdentifier )
+                        hlength += 3;
                      found++;
                      }
                   break;
@@ -699,6 +726,20 @@
                   return;
                }
 
+            // Write header one byte at a time
+            // Remove from hlength size of our header (3)
+            if ( dataIdentifier ) {
+               while (c < Count && (found < (hlength + 9-3)) && found < plength+6) {
+                     write_ipack(Buf + c, 1);
+                     c++;
+                     found++;
+                     }
+               if (found == (hlength+9-3)) {
+                  write_ipack(eHeadr, 2); 
+                  write_ipack(&dataIdentifier, 1);
+                  }
+               }
+
             while (c < Count && found < plength + 6) {
                   int l = Count - c;
                   if (l + found > plength + 6)
@@ -802,13 +843,11 @@
      while (*DPids && numTracks < MAXTRACKS && n < MAXDPIDS)
            ts2pes[numTracks++] = new cTS2PES(*DPids++, resultBuffer, IPACKS, 0x00, 0x80 + n++, new cDolbyRepacker);
      }
-  /* future...
   if (SPids) {
      int n = 0;
      while (*SPids && numTracks < MAXTRACKS && n < MAXSPIDS)
-           ts2pes[numTracks++] = new cTS2PES(*SPids++, resultBuffer, IPACKS, 0x00, 0x28 + n++);
+           ts2pes[numTracks++] = new cTS2PES(*SPids++, resultBuffer, IPACKS, 0x00, 0x00, NULL, 0x28 + n++);
      }
-  */
 }
 
 cRemux::~cRemux()

--- NEW FILE: genclut.c ---
#include <stdio.h>

int main()
{
  fprintf(stderr, "static uint32_t default_2bit[4] = {\n");
  fprintf(stderr, "0x00000000,\n");
  fprintf(stderr, "0xFFFFFFFF,\n");
  fprintf(stderr, "0xFF000000,\n");
  fprintf(stderr, "0xFF%02X%02X%02X\n",128,128,128);
  fprintf(stderr, "};\n");
  
  fprintf(stderr, "static uint32_t default_4bit[16] = {\n");
  for (int i = 0; i < 16; i ++)
  {
    if (i & 0x8)
    {
      if (i == 0)
      {
	fprintf(stderr, "0x00000000,\n");
      }
      else
      {
	int r=0,g=0,b=0;
	if (i&1)
	  r = 0xFF;
	if (i&2)
	  g = 0xFF;
	if (i&4)
	  b = 0xFF;
	fprintf(stderr, "0xFF%02X%02X%02X,\n", b, g, r);
      }
    }
    else
    {
	int r=0,g=0,b=0;
	if (i&1)
	  r = 0x80;
	if (i&2)
	  g = 0x80;
	if (i&4)
	  b = 0x80;
	fprintf(stderr, "0xFF%02X%02X%02X,\n", b, g, r);
      
    }

  }
  fprintf(stderr, "};\n");

  fprintf(stderr, "static uint32_t default_8bit[256] = {\n");

  for (int i = 0; i < 256; i++)
  {
    if (i>0 && (i%4==0))
      fprintf(stderr,"\n");
    bool b1 = (i & 0x80) != 0;
    bool b5 = (i & 0x08) != 0;
    if (!b1 && !b5)
    {
      if (i==0)
      {
	fprintf(stderr, "0x00000000,");
      }
      else
      {
	int r=0,g=0,b=0;
	int t = 191;
	if (i&1)
	  r = 0xFF;
	if (i&2)
	  g = 0xFF;
	if (i&4)
	  b = 0xFF;
	
	fprintf(stderr, "0x%02X%02X%02X%02X,",t,b,g,r);

      }
    }
    if (!b1 && b5)
    {
      int r=0,g=0,b=0;
      int t = 0x80;
      if (i&1)
	r+=85;
      if (i&0x10)
	r+=170;
      
      if (i&2)
	g+=85;
      if (i&0x20)
	g+=170;
      
      if (i&4)
	b+=85;
      if (i&0x40)
	b+=170;
      fprintf(stderr, "0x%02X%02X%02X%02X,",t,b,g,r);
      
    }
    if (b1 && !b5)
    {
      int r=0x80-1, g=0x80-1, b=0x80-1;
      int t =0xFF; 
      if (i&1)
	r+=43;
      if (i&0x10)
	r+=85;
      
      if (i&2)
	g+=43;
      if (i&0x20)
	g+=85;
      
      if (i&4)
	b+=43;
      if (i&0x40)
	b+=85;
      
      
      fprintf(stderr, "0x%02X%02X%02X%02X,",t,b,g,r);

    }
    if (b1 && b5)
    {
      int r=0,g=0,b=0;
      int t = 0xFF;
      if (i&1)
	r+=43;
      if (i&0x10)
	r+=85;
      
      if (i&2)
	g+=43;
      if (i&0x20)
	g+=85;
      
      if (i&4)
	b+=43;
      if (i&0x40)
	b+=85;
      fprintf(stderr, "0x%02X%02X%02X%02X%c",t,b,g,r,i==255?'\n':',');

    }
  }
  fprintf(stderr, "};\n");

}


--- NEW FILE: receiver.h ---
#ifndef __SUBTITLES_RECEIVER_H
#define __SUBTITLES_RECEIVER_H

#include "dec.h"
#include "viewer.h"
#include <vdr/receiver.h>
#include <vdr/ringbuffer.h>

class cSynchronizer;
class cMutex;

class cSubtitlesReceiver : public cReceiver, public cThread {

private:
  SubtitlesViewer viewer;
  cSynchronizer* syncer;
  cMutex* mutex;
  cDecoder* decoder;
  int subPid,priority;
  bool subscribed;

  cRingBufferLinear *ringBuffer;
  bool active;
  uint64_t clearTime;

  void processTSPacket(const uchar* Data);

protected:
  virtual void Activate(bool On);
  virtual void Receive(uchar *Data, int Length);
  virtual void Action( void );

 public:
  cSubtitlesReceiver(int SubPid, int Priority);
  ~cSubtitlesReceiver();

};

#endif


--- NEW FILE: replay.c ---
#include "replay.h"
#include <unistd.h>
#include <vdr/osdcontroller.h>
#include <vdr/ringbuffer.h>
#include <vdr/device.h>
#include <vdr/thread.h>
#include "page.h"
#include "sync.h"
#define RINGBUFFERSIZE 1024*100
#define ORIGINAL_OR_COPY_MASK 0x01
#define PRIVATE_STREAM_1 0xBD

using namespace NonInteractiveOsdPatch;

cDvbSubtitlesReplay::cDvbSubtitlesReplay(int Priority, int DataId)
    :  viewer(), decoder(), clearTime(0), dataId(DataId),priority(Priority)

{
  subscribed = false;
  mutex = new cMutex();
  ringBuffer = new cRingBufferFrame(RINGBUFFERSIZE);  
  RecordingController.Subscribe( DataId, this );    
  syncer = GetSynchronizer();
  Start();
}
cDvbSubtitlesReplay::~cDvbSubtitlesReplay()
{
  active = false;
  RecordingController.Unsubscribe( dataId, this );    
  syncer->stop();

  mutex->Lock();
  if (subscribed)
    OsdController.Unsubscribe( &viewer );
  mutex->Unlock();

  Cancel(3);
  delete ringBuffer;
  delete syncer;
  delete mutex;
}
void cDvbSubtitlesReplay::Receive(unsigned char DataIdentifier, unsigned char* Data, int Length)
{

  cFrame* frame = new cFrame( Data, Length );
  if ( !ringBuffer->Put( frame ) )
    delete frame;

}

void cDvbSubtitlesReplay::Action()
{
  active = true;
  while (active)
  {
    cFrame* frame = ringBuffer->Get();
    if (frame)
      {
      unsigned char* data = frame->Data();
      int length = frame->Count();
      //      for (int i = 0; i < 16; i ++)
      //	fprintf(stderr,"%02X ", data[i]);
      //    fprintf(stderr, "\n");
      if ( length >= 9 
	   && data[0] == 0x00 
	   && data[1] == 0x00 
	   && data[2] == 0x01 
	   && data[3] == PRIVATE_STREAM_1 )
      {
	
	if ( data[6] & ORIGINAL_OR_COPY_MASK )
	{
	  decoder.addPesData(data, length, true );
	}
	else
	{
	  int hlength = data[8];
	  length -= 9 + hlength;
	  decoder.addPesData( &data[9+hlength], length, false );
	}
	  
      }
      ringBuffer->Drop( frame );
    }

    if (active && decoder.PageAvailable() )
    {

	mutex->Lock();
	if (!subscribed)
	{
	  OsdController.Subscribe(priority, &viewer);
	  subscribed = true;
	}
	mutex->Unlock();

	cSubtitlesPage* page = decoder.GetPage();
	
	syncer->sync(page->GetPts());

	viewer.SetPage( page );

	if (page->GetTimeout())
	    clearTime = msectime()+page->GetTimeout()*1000;
	else
	    clearTime = 0;
//	delete page;
    }
    
    // page timeout
    if (clearTime > 0 && msectime() > clearTime)
    {
      viewer.Clear();
      clearTime = 0;
    }
    usleep(10000);
  }

}



--- NEW FILE: COPYING ---
		    GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS

	    How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.

--- NEW FILE: region.c ---
#include "region.h"
#include <vdr/osd.h>
#include <vdr/tools.h>
#include "configuration.h"
#include "clut.h"

Region::Region( int aId )
    :iId(aId),iCanvas(0),bpp(2),loc(2)
{
  Reset();
}

Region::~Region()
{
  if ( iCanvas )
    delete iCanvas;
  Reset();
}

void Region::SetClut( Clut* aClut )
{

  iClut = aClut;

}

void Region::Draw( int aX, int aY, int aPixelCode, int rl)
{

    
    if ( iCanvas == NULL )
    {
	return;
    }

    // quantize to required  2bpp
    if (gSubtitlesConfiguration.dxr3comp)
    {
	int pixelCode = 0;
	if (aPixelCode & 0x8)
	    pixelCode |= 0x2;
	if (aPixelCode & 0x7)
	    pixelCode |= 0x1;
	aPixelCode = pixelCode;
    }

    const cSubtitlesPalette* palette  = iClut->GetPalette(4);

    if (palette == NULL)
    {
	return;
    }


    int numColors;
    const uint32_t* colors;
    if (gSubtitlesConfiguration.dxr3comp)
    {
	numColors = 4;
	static uint32_t __colors[] = {clrTransparent, clrBlack, clrWhite, clrWhite};
	colors = __colors;
    }
    else
    {
	numColors= palette->GetNumColors();
	colors = palette->GetColors();
    }

    if (aPixelCode >= 0  && aPixelCode < numColors)
    {
      if (rl == 1)
	iCanvas->DrawPixel (aX, aY, colors[aPixelCode]);
      else
	iCanvas->DrawRectangle (aX, aY, aX + rl - 1, aY, colors[aPixelCode]);
    }
}


void Region::Reset()
{

  iClut = 0;
  iWidth = 0;
  iHeight = 0;
  iX = 0;
  iY = 0;

}

void Region::SetSize( int aWidth, int aHeight ) 
{

  iWidth = aWidth;
  iHeight = aHeight;
  Create();

}

void Region::SetPosition( int aX, int aY )
{

  iX = aX;
  iY = aY;
}

void Region::Create( void )
{
    if (iCanvas)
	delete iCanvas;
    iCanvas = new cBitmap( iWidth, iHeight, gSubtitlesConfiguration.dxr3comp?2:4 );
    iCanvas->Reset();
}

int Region::X()
{
  return iX;
}

int Region::Y()
{
  return iY;
}


int Region::Width()
{
  return iWidth;
}

int Region::Height()
{
  return iHeight;
}


void Region::SetBpp(int Bpp, int Loc)
{

    bpp = Bpp;
    loc = Loc;
}

int Region::Id()
{

  return iId;

}

cBitmap* Region::Canvas( void )
{
  return iCanvas;

}

--- NEW FILE: replay.h ---
#include <map>
#include "viewer.h"
#include "dec.h"
#include <vdr/thread.h>
#include <vdr/rcontroller.h>

using namespace RecordingPatch;

class cRingBufferFrame;
class cSynchronizer;
class cMutex;


class cDvbSubtitlesReplay : public cThread, public iRecordingPlugin
{
public:
  cDvbSubtitlesReplay(int Priority, int DataId);
  ~cDvbSubtitlesReplay();
  virtual void Receive(unsigned char DataIdentifier, unsigned char* Data, int Length);
protected:
  virtual void Action();
private:
  bool active,subscribed;
  SubtitlesViewer viewer;
  cDecoder decoder;
  cRingBufferFrame* ringBuffer;
  uint64_t clearTime;
  cSynchronizer* syncer;
  cMutex* mutex;
  int dataId,priority;

};

--- NEW FILE: receiver.c ---
#include "receiver.h"
#include "dec.h"
#include <unistd.h>
#include <vdr/receiver.h>
#include <vdr/ringbuffer.h>
#include <vdr/osdcontroller.h>
#include <vdr/dvbsub.h>

#include "page.h"
#include "sync.h"
//#include <vdr/tools.h>

#define PAYLOAD_UNIT_START 0x40
#define TS_PACKET_SIZE 188
#define ADAPTATION_FIELD_CONTROL 0x30

using namespace NonInteractiveOsdPatch;
 
cSubtitlesReceiver::cSubtitlesReceiver(int SubPid, int Priority)
  : cReceiver(0, -1, SubPid), viewer(), subPid(SubPid),
priority(Priority),clearTime(0)
{
  //  fprintf(stderr, "receiver started with subtitling pid = %i\n",SubPid);
  mutex = new cMutex;
  decoder = new cDecoder();
  ringBuffer = new cRingBufferLinear(1024*188,188,true);
  subPid = SubPid;
  syncer = GetSynchronizer();
  subscribed = false;
}

cSubtitlesReceiver::~cSubtitlesReceiver()
{
  mutex->Lock();
  if (subscribed)
    OsdController.Unsubscribe(&viewer);
  mutex->Unlock();
  syncer->stop();
  Detach();

  //No more calls to the ::Receive
  delete ringBuffer;
  delete syncer;

  mutex->Lock();
  delete decoder;
  mutex->Unlock();
  delete mutex;

}

void cSubtitlesReceiver::Activate(bool On){

  if (On)
  {
    Start();
  }
  else
    {
      active=false;
      Cancel(3);
    }

  
}

void cSubtitlesReceiver::Receive(uchar *Data, int Length){

  if (!active || Length < 188)
    return;
  int p = ringBuffer->Put( Data, Length );
  if ( p < Length )
    esyslog("DvbSubtitles-receiver: Ring buffer overflow\n");

}

void cSubtitlesReceiver::Action( void ){

  active=true;  
  while (active) {
    
    {
      cMutexLock(mutex);
      int numBytes = TS_PACKET_SIZE;
      const uchar *b = ringBuffer->Get(numBytes);
      if ( b ) 
      {
	int numPackets = numBytes/TS_PACKET_SIZE;
	
	for (int i = 0; active && i < numPackets; i++ )
	{
	  processTSPacket( b + i*TS_PACKET_SIZE );
	}
      
	ringBuffer->Del( TS_PACKET_SIZE*numPackets );
      }
      if ( active && decoder->PageAvailable() )
      {
      
	if (!subscribed)
	{
	  OsdController.Subscribe(priority,&viewer);
	  subscribed = true;
	}
#if DEBUG
	fprintf(stderr, "Priority=%i receiver got page\n",priority);
#endif
	cSubtitlesPage* page = decoder->GetPage();
      
	syncer->sync(page->GetPts());
      
	viewer.SetPage( page );
	if (page->GetTimeout())
	  clearTime = msectime()+ page->GetTimeout()*1000;
	else
	  clearTime = 0;
	//delete page;
      }
    }
    // page timeout
    if (clearTime > 0 && msectime() > clearTime)
    {
      viewer.Clear();
      clearTime = 0;
    }
    usleep(10000);

  }
}

void cSubtitlesReceiver::processTSPacket(const uchar* Data)
{
  
  // XXX Handle transport errors
  bool newPacket = (Data[1] & PAYLOAD_UNIT_START) != 0;
  int  afc = ( Data[3] & ADAPTATION_FIELD_CONTROL ) >> 4;
  
  if ( afc == 0x2 )
    return;

  // Handle continuity counter

  int index = 4;
  if ( afc == 0x3 )
  {
    index += Data[index]+1;
  }
  decoder->addPesData( Data + index , TS_PACKET_SIZE-index, newPacket);
}


--- NEW FILE: clut.h ---
#ifndef __DVB_SUBTITLES_CLUT_H
#define __DVB_SUBTITLES_CLUT_H
#include <stdint.h>

// forward declarations

#define MAX_COLORS 256
class cSubtitlesPalette
{
 public:
  cSubtitlesPalette(int bpp);
  ~cSubtitlesPalette();
  
  uint32_t GetColor(int index) const;
  void SetColor(int index, uint32_t value);

  const uint32_t *GetColors() const {return colors;}
  int GetNumColors() const {return maxColors;}

 private:
  int maxColors;
  uint32_t colors[MAX_COLORS];
};

class Clut {
  
public:
  
  Clut( int aId );
  ~Clut();

  int Id();

  void Decode(unsigned char* Data, int Size);

  const cSubtitlesPalette *GetPalette(int bpp) const;
private:
  
  // attributes
  int      iId;
  cSubtitlesPalette palette2;
  cSubtitlesPalette palette4;
  cSubtitlesPalette palette8;

};

#endif //__DVB_SUBTITLES_CLUT_H

--- NEW FILE: clut.c ---
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include "clut.h"
#include "configuration.h"
#include <string.h>
#include <vdr/osdbase.h>
#include <vdr/tools.h>

/*
static uint32_t default_2bit[4] = {
0x00000000,
0xFFFFFFFF,
0xFF000000,
0xFF808080
};
static uint32_t default_4bit[16] = {
0xFF000000,
0xFF000080,
0xFF008000,
0xFF008080,
0xFF800000,
0xFF800080,
0xFF808000,
0xFF808080,
0xFF000000,
0xFF0000FF,
0xFF00FF00,
0xFF00FFFF,
0xFFFF0000,
0xFFFF00FF,
0xFFFFFF00,
0xFFFFFFFF,
};
static uint32_t default_8bit[256] = {
0x00000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x80000000,0x80000055,0x80005500,0x80005555,
0x80550000,0x80550055,0x80555500,0x80555555,
0xBF000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x800000AA,0x800000FF,0x800055AA,0x800055FF,
0x805500AA,0x805500FF,0x805555AA,0x805555FF,
0xBF000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x8000AA00,0x8000AA55,0x8000FF00,0x8000FF55,
0x8055AA00,0x8055AA55,0x8055FF00,0x8055FF55,
0xBF000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x8000AAAA,0x8000AAFF,0x8000FFAA,0x8000FFFF,
0x8055AAAA,0x8055AAFF,0x8055FFAA,0x8055FFFF,
0xBF000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x80AA0000,0x80AA0055,0x80AA5500,0x80AA5555,
0x80FF0000,0x80FF0055,0x80FF5500,0x80FF5555,
0xBF000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x80AA00AA,0x80AA00FF,0x80AA55AA,0x80AA55FF,
0x80FF00AA,0x80FF00FF,0x80FF55AA,0x80FF55FF,
0xBF000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x80AAAA00,0x80AAAA55,0x80AAFF00,0x80AAFF55,
0x80FFAA00,0x80FFAA55,0x80FFFF00,0x80FFFF55,
0xBF000000,0xBF0000FF,0xBF00FF00,0xBF00FFFF,
0xBFFF0000,0xBFFF00FF,0xBFFFFF00,0xBFFFFFFF,
0x80AAAAAA,0x80AAAAFF,0x80AAFFAA,0x80AAFFFF,
0x80FFAAAA,0x80FFAAFF,0x80FFFFAA,0x80FFFFFF,
0xFF7F7F7F,0xFF7F7FAA,0xFF7FAA7F,0xFF7FAAAA,
0xFFAA7F7F,0xFFAA7FAA,0xFFAAAA7F,0xFFAAAAAA,
0xFF000000,0xFF00002B,0xFF002B00,0xFF002B2B,
0xFF2B0000,0xFF2B002B,0xFF2B2B00,0xFF2B2B2B,
0xFF7F7FD4,0xFF7F7FFF,0xFF7FAAD4,0xFF7FAAFF,
0xFFAA7FD4,0xFFAA7FFF,0xFFAAAAD4,0xFFAAAAFF,
0xFF000055,0xFF000080,0xFF002B55,0xFF002B80,
0xFF2B0055,0xFF2B0080,0xFF2B2B55,0xFF2B2B80,
0xFF7FD47F,0xFF7FD4AA,0xFF7FFF7F,0xFF7FFFAA,
0xFFAAD47F,0xFFAAD4AA,0xFFAAFF7F,0xFFAAFFAA,
0xFF005500,0xFF00552B,0xFF008000,0xFF00802B,
0xFF2B5500,0xFF2B552B,0xFF2B8000,0xFF2B802B,
0xFF7FD4D4,0xFF7FD4FF,0xFF7FFFD4,0xFF7FFFFF,
0xFFAAD4D4,0xFFAAD4FF,0xFFAAFFD4,0xFFAAFFFF,
0xFF005555,0xFF005580,0xFF008055,0xFF008080,
0xFF2B5555,0xFF2B5580,0xFF2B8055,0xFF2B8080,
0xFFD47F7F,0xFFD47FAA,0xFFD4AA7F,0xFFD4AAAA,
0xFFFF7F7F,0xFFFF7FAA,0xFFFFAA7F,0xFFFFAAAA,
0xFF550000,0xFF55002B,0xFF552B00,0xFF552B2B,
0xFF800000,0xFF80002B,0xFF802B00,0xFF802B2B,
0xFFD47FD4,0xFFD47FFF,0xFFD4AAD4,0xFFD4AAFF,
0xFFFF7FD4,0xFFFF7FFF,0xFFFFAAD4,0xFFFFAAFF,
0xFF550055,0xFF550080,0xFF552B55,0xFF552B80,
0xFF800055,0xFF800080,0xFF802B55,0xFF802B80,
0xFFD4D47F,0xFFD4D4AA,0xFFD4FF7F,0xFFD4FFAA,
0xFFFFD47F,0xFFFFD4AA,0xFFFFFF7F,0xFFFFFFAA,
0xFF555500,0xFF55552B,0xFF558000,0xFF55802B,
0xFF805500,0xFF80552B,0xFF808000,0xFF80802B,
0xFFD4D4D4,0xFFD4D4FF,0xFFD4FFD4,0xFFD4FFFF,
0xFFFFD4D4,0xFFFFD4FF,0xFFFFFFD4,0xFFFFFFFF,
0xFF555555,0xFF555580,0xFF558055,0xFF558080,
0xFF805555,0xFF805580,0xFF808055,0xFF808080
};
*/

cSubtitlesPalette::cSubtitlesPalette(int bpp)
{
  if (bpp != 2 && bpp != 4 && bpp != 8)
    bpp = 8;

  maxColors = 1<<bpp;

  for (int i = 0; i < MAX_COLORS; i++)
  {
      colors[i] = clrWhite;
  }

}
cSubtitlesPalette::~cSubtitlesPalette()
{
}

void cSubtitlesPalette::SetColor(int index, uint32_t value)
{
  if (index >=0 && index < maxColors)
    colors[index] = value;
}

uint32_t cSubtitlesPalette::GetColor(int index) const
{
  if (index >0 && index < maxColors)
    return colors[index];
  return 0;

}
const cSubtitlesPalette *Clut::GetPalette(int bpp) const
{
  switch (bpp)
  {
  case 2:
    return &palette2;
  case 4:
    return &palette4;
  case 8:
    return &palette8;
  default:
    dsyslog("Clut::GetPalette with invalid bpp = %d",bpp);
    return NULL;
  }
  return NULL;
}

Clut::Clut( int aId )
:palette2(2),palette4(4),palette8(8){
  iId = aId;


}

Clut::~Clut()
{

}

int Clut::Id()
{

  return iId;

}

static uint32_t yuv2rgb(int Y,int Cb, int Cr)
{
    int Ey, Epb, Epr;
    int Eg, Eb, Er;

    Ey = (Y - 16);
    Epb = (Cb - 128);
    Epr = (Cr - 128);
    /* ITU-R 709 */
    Er = (((298 * Ey             + 460 * Epr) / 256) <? 255) >? 0;
    Eg = (((298 * Ey -  55 * Epb - 137 * Epr) / 256) <? 255) >? 0;
    Eb = (((298 * Ey + 543 * Epb            ) / 256) <? 255) >? 0;

    return (Er << 16) | (Eg << 8) | Eb;
}


void Clut::Decode(unsigned char* Data, int Size)
{
    
    int pl = 0;

    while (pl < Size)
    {
	unsigned char entry_id = Data[pl++];

	bool full_range = (Data[pl]&0x01)!=0;
	unsigned char entry_flags = Data[pl++]&0xE0;
	
	unsigned char y;
	unsigned char cr;
	unsigned char cb;
	unsigned char t;
	if (full_range)
	{
	    y  = Data[pl++];
	    cr = Data[pl++];
	    cb = Data[pl++];
	    t  = Data[pl++];

	}
	else
	{
	    y   =  Data[pl];
	    cr  =  (Data[pl++] & 0x03) << 6;
	    cr |=  (Data[pl]   & 0xC0) >> 2;
	    cb  =  (Data[pl]   & 0x3C) << 2;
	    t   =  (Data[pl++] & 0x03) << 6;
	}
	
	uint32_t value;
	if ( y == 0 )
	{
	  value = 0;
	}
	else
	{
	  value = yuv2rgb(y,cb,cr);
	  if (value)
	    value |= (((10-gSubtitlesConfiguration.fgTransparency) * (255 - t)) / 10) << 24;
	  else
	    value |= (((10-gSubtitlesConfiguration.bgTransparency) * (255 - t)) / 10) << 24;
	}

	
	if ((entry_flags & 0x80) && (entry_id<4))
	{
	  palette2.SetColor(entry_id,value);
	}

	if ((entry_flags & 0x40) && (entry_id < 16))
	{
	    palette4.SetColor(entry_id,value);
	}

	if ((entry_flags & 0x20))
	{
	  palette8.SetColor(entry_id,value);
	}
    }

}

--- NEW FILE: Makefile ---
#
# Makefile for a Video Disk Recorder plugin
#
# $Id: Makefile,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $

# The official name of this plugin.
# This name will be used in the '-P...' option of VDR to load the plugin.
# By default the main source file also carries this name.
#
PLUGIN = subtitles

### The version number of this plugin (taken from the main source file):

VERSION = $(shell grep 'static const char \*VERSION *=' $(PLUGIN).c | awk '{ print $$6 }' | sed -e 's/[";]//g')

### The C++ compiler and options:

CXX      ?= g++
CXXFLAGS ?= -O2 -g -Wall -Woverloaded-virtual -fPIC

### The directory environment:

DVBDIR = ../../../../DVB
VDRDIR = ../../..
LIBDIR = ../../lib
TMPDIR = /tmp

### Allow user defined options to overwrite defaults:

-include $(VDRDIR)/Make.config

### The version number of VDR (taken from VDR's "config.h"):

VDRVERSION = $(shell grep 'define VDRVERSION ' $(VDRDIR)/config.h | awk '{ print $$3 }' | sed -e 's/"//g')

### The name of the distribution archive:

ARCHIVE = $(PLUGIN)-$(VERSION)
PACKAGE = vdr-$(ARCHIVE)

### Includes and Defines (add further entries here):

INCLUDES += -I$(VDRDIR)/include -I$(DVBDIR)/include

DEFINES += -D_GNU_SOURCE -DPLUGIN_NAME_I18N='"$(PLUGIN)"'

ifdef DEBUG
DEFINES += -DDEBUG
endif

### The object files (add further files here):

OBJS = $(PLUGIN).o receiver.o object.o renderer.o region.o clut.o viewer.o dec.o replay.o configuration.o i18n.o page.o subtitle.o sync.o subfilter.o menu.o

### Implicit rules:

%.o: %.c
	$(CXX) $(CXXFLAGS) -c $(DEFINES) $(INCLUDES) $<

# Dependencies:

MAKEDEP = g++ -MM -MG
DEPFILE = .dependencies
$(DEPFILE): Makefile
	@$(MAKEDEP) $(DEFINES) $(INCLUDES) $(OBJS:%.o=%.c) > $@

-include $(DEPFILE)

### Targets:

all: libvdr-$(PLUGIN).so

libvdr-$(PLUGIN).so: $(OBJS)
	$(CXX) $(CXXFLAGS) -shared $(OBJS) -o $@
	@cp $@ $(LIBDIR)/$@.$(VDRVERSION)

dist: clean
	@-rm -rf $(TMPDIR)/$(ARCHIVE)
	@mkdir $(TMPDIR)/$(ARCHIVE)
	@cp -a * $(TMPDIR)/$(ARCHIVE)
	@tar czf $(PACKAGE).tgz -C $(TMPDIR) $(ARCHIVE)
	@-rm -rf $(TMPDIR)/$(ARCHIVE)
	@echo Distribution package created as $(PACKAGE).tgz

clean:
	@-rm -f $(OBJS) $(DEPFILE) *.so *.tgz core* *~

--- NEW FILE: i18n.c ---
/*
 * i18n.c: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id: i18n.c,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $
 */

#include "i18n.h"
#include <stdio.h>

const tI18nPhrase Phrases[] =
{
  { "DVB subtitles decoder", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Tekstitys (DVB)", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Textning, DVB", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "´ÕÚÞÔÕà DVB áãÑâØâàÞÒ", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Primary Language", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Ensisijainen kieli", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Primärt språk", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "¿ÕàÒëÙ ï×ëÚ", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Secondary Language", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Toissijainen kieli", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Sekundärt språk", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "²âÞàÞÙ ï×ëÚ", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Hearing Impaired", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Tekstitys kuulorajoitteisille", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Textning för hörselskadade", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "ÂØâàë ÔÛï áÛÐÑÞáÛëèÐéØå", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Record Subtitles", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Tallenna tekstitykset", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Inspelning av textning", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "·ÐßØáëÒÐâì áãÑâØâàë", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Subtitles Enabled", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Tekstitys aktiivinen", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Textning aktiverad", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "¿ÞÚÐ×ëÒÐâì áãÑâØâàë", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Offset", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Tasaus", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Justering", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "ÁÜÕéÕÝØÕ", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Video format", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Kuvasuhde", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Videoformat", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "ÄÞàÜÐâ ÒØÔÕÞ", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Synchronization", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Tahdistus", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Synkronisering", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "ÁØÝåàÞÝØ×ÐæØï", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Delay", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Viive", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Fördröjning", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "·ÐÔÕàÖÚÐ", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "All", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Kaikki", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Alla", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Available", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Nykyiset", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Tillgänglig", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "No Subtitles", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Ei tekstitystä", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Ingen textning", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Automatic", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Automaattinen", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Automatisk", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Choose Language", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Valitse kieli", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Välj språk", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Choose Language (DVB Subtitles)", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Valitse tekstityskieli (DVB)", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Välj språk för textning (DVB)", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Show Language Selector", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Näytä kielivalinta", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "Visa språkval", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "DXR3 Compability", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "DXR3-yhteensopivuus", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "kompabilitet med DXR3", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Background Transparency", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Taustan läpinäkyvyys", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { "Foreground Transparency", // English
    "", // Deutsch
    "", // Slovenski
    "", // Italiano
    "", // Nederlands
    "", // Português
    "", // Français
    "", // Norsk
    "Tekstityksen läpinäkyvyys", // suomi
    "", // Polski
    "", // Español
    "", // ÅëëçíéêÜ (Greek)
    "", // Svenska
    "", // Romaneste
    "", // Magyar
    "", // Català
    "", // ÀãááÚØÙ (Russian)
    "", // Hrvatski (Croatian)
    "", // Eesti
  },
  { NULL }
};

--- NEW FILE: renderer.h ---
#ifndef __DVB_SUBTITLES_RENDERER_H
#define __DVB_SUBTITLES_RENDERER_H

#include "clut.h"
#include "region.h"

class Renderer 
{

public:
  Renderer( Region* iRegion, int aX, int aY );
  virtual void Draw( int aX , int aY, int aPixelCode, int rl = 1 );
  const Clut *GetClut () { return iRegion->GetClut (); }

private:

  Region* iRegion;
  int iX;
  int iY;


};

#endif



--- NEW FILE: menu.c ---
/*
 * menu.c: Configuration menu
 *
 * $Id: menu.c,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $
 */


#include "menu.h"
#include "configuration.h"
#include <vdr/menuitems.h>

// Modified from Teletext subtitles

class cMenuSetupDvbSubs : public cMenuSetupPage {
 public:
  cMenuSetupDvbSubs();
 protected:
  virtual void Store(void);
  virtual eOSState ProcessKey(eKeys Key);
 private:
  virtual void Setup(void);
  int sync;
};


cMenuSetupPage *GetSetup()
{
    return new cMenuSetupDvbSubs();
}

cMenuSetupDvbSubs::cMenuSetupDvbSubs()
{

  Setup();
}

void cMenuSetupDvbSubs::Setup(void)
{

  int current = Current();

  if (gSubtitlesConfiguration.language >= I18nNumLanguages )
    gSubtitlesConfiguration.language = I18nNumLanguages-1;
  if (gSubtitlesConfiguration.language < 0)
    gSubtitlesConfiguration.language = 0;

  if (gSubtitlesConfiguration.language2 >= I18nNumLanguages )
    gSubtitlesConfiguration.language2 = I18nNumLanguages-1;
  if (gSubtitlesConfiguration.language2 < 0)
    gSubtitlesConfiguration.language2 = 0;

  Clear();
  Add(new cMenuEditBoolItem(tr("Subtitles Enabled"), &gSubtitlesConfiguration.enabled, tr("no"), tr("yes")));
  Add(new cMenuEditStraItem(tr("Primary Language"), &gSubtitlesConfiguration.language, 
			    I18nNumLanguages, I18nLanguages()));
  Add(new cMenuEditStraItem(tr("Secondary Language"), &gSubtitlesConfiguration.language2, 
			    I18nNumLanguages, I18nLanguages()));
//  Add(new cMenuEditBoolItem(tr("Hearing Impaired"), &gSubtitlesConfiguration.hearingImpaired, tr("no"), tr("yes")));
//  Add(new cMenuEditBoolItem(tr("Video format"), &gSubtitlesConfiguration.widescreen, "4:3","16:9"));
  if (gSubtitlesConfiguration.enabled)
  {
    Add(new cMenuEditBoolItem(tr("Synchronization"), &gSubtitlesConfiguration.sync));
    if (gSubtitlesConfiguration.sync==0)
    {
      Add(new cMenuEditIntItem(tr("Delay"), &gSubtitlesConfiguration.delay, -5, 10));
    }
    Add(new cMenuEditIntItem(tr("Offset"), &gSubtitlesConfiguration.offset, -50, 50));
  }
  Add(new cMenuEditBoolItem(tr("Record Subtitles"), &gSubtitlesConfiguration.recording, tr("no"), tr("yes")));

  Add(new cMenuEditBoolItem(tr("DXR3 Compability"), &gSubtitlesConfiguration.dxr3comp, tr("no"), tr("yes")));
  Add(new cMenuEditBoolItem(tr("Show Language Selector"), &gSubtitlesConfiguration.mainmenu, tr("no"), tr("yes")));
  Add(new cMenuEditIntItem(tr("Background Transparency"), &gSubtitlesConfiguration.bgTransparency, 0, 10));
  Add(new cMenuEditIntItem(tr("Foreground Transparency"), &gSubtitlesConfiguration.fgTransparency, 0, 9));

  SetCurrent(Get(current));
  Display();

}
eOSState  cMenuSetupDvbSubs::ProcessKey(eKeys Key)
{
    int oldEnabled = gSubtitlesConfiguration.enabled;
    int oldSync = gSubtitlesConfiguration.sync;

    eOSState state = cMenuSetupPage::ProcessKey(Key);

    if (Key != kNone && (gSubtitlesConfiguration.enabled != oldEnabled ||
			 gSubtitlesConfiguration.sync != oldSync))
	Setup();

    return state;

}
void cMenuSetupDvbSubs::Store(void)
{
  SetupStore("Language", gSubtitlesConfiguration.language);
  SetupStore("HearingImpaired", gSubtitlesConfiguration.hearingImpaired);
  SetupStore("VideoFormat", gSubtitlesConfiguration.widescreen);
  SetupStore("Record", gSubtitlesConfiguration.recording);
  SetupStore("Enabled", gSubtitlesConfiguration.enabled);
  SetupStore("Offset", gSubtitlesConfiguration.offset);
  SetupStore("Sync", gSubtitlesConfiguration.sync);
  SetupStore("Delay", gSubtitlesConfiguration.delay);
  SetupStore("Language2",gSubtitlesConfiguration.language2);
  SetupStore("Mainmenu", gSubtitlesConfiguration.mainmenu);
  SetupStore("Dxr3comp", gSubtitlesConfiguration.dxr3comp);
  SetupStore("BackgroundTransparency", gSubtitlesConfiguration.bgTransparency);
  SetupStore("ForegroundTransparency", gSubtitlesConfiguration.fgTransparency);
}

--- NEW FILE: renderer.c ---
#include "renderer.h"
#include "region.h"

Renderer::Renderer( Region* aRegion, int aX, int aY )
  : iRegion(aRegion), iX(aX), iY(aY)
{
  

}


void Renderer::Draw( int aX , int aY, int aPixelCode, int rl )
{

  iRegion->Draw( iX + aX, iY + aY, aPixelCode, rl );

}

--- NEW FILE: i18n.h ---
/*
 * i18n.h: A plugin for the Video Disk Recorder
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id: i18n.h,v 1.1 2005/04/04 22:53:36 dsalt-guest Exp $
 */


#ifndef __CAL_I18N_H
#define __CAL_I18N_H


#include <vdr/i18n.h>


extern const tI18nPhrase Phrases[];


#endif //__CAL_I18N_H