small private epg fix
[enigma2.git] / lib / dvb / epgcache.cpp
1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
3
4 #undef EPG_DEBUG  
5
6 #include <time.h>
7 #include <unistd.h>  // for usleep
8 #include <sys/vfs.h> // for statfs
9 // #include <libmd5sum.h>
10 #include <lib/base/eerror.h>
11 #include <lib/dvb/pmt.h>
12 #include <lib/dvb/db.h>
13 #include <Python.h>
14
15 int eventData::CacheSize=0;
16 descriptorMap eventData::descriptors;
17 __u8 eventData::data[4108];
18 extern const uint32_t crc32_table[256];
19
20 eventData::eventData(const eit_event_struct* e, int size, int type)
21         :ByteSize(size&0xFF), type(type&0xFF)
22 {
23         if (!e)
24                 return;
25
26         __u32 descr[65];
27         __u32 *pdescr=descr;
28
29         __u8 *data = (__u8*)e;
30         int ptr=10;
31         int descriptors_length = (data[ptr++]&0x0F) << 8;
32         descriptors_length |= data[ptr++];
33         while ( descriptors_length > 0 )
34         {
35                 __u8 *descr = data+ptr;
36                 int descr_len = descr[1]+2;
37
38                 __u32 crc = 0;
39                 int cnt=0;
40                 while(cnt++ < descr_len)
41                         crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
42
43                 descriptorMap::iterator it =
44                         descriptors.find(crc);
45                 if ( it == descriptors.end() )
46                 {
47                         CacheSize+=descr_len;
48                         __u8 *d = new __u8[descr_len];
49                         memcpy(d, descr, descr_len);
50                         descriptors[crc] = descriptorPair(1, d);
51                 }
52                 else
53                         ++it->second.first;
54
55                 *pdescr++=crc;
56                 descriptors_length -= descr_len;
57         }
58         ByteSize = 12+((pdescr-descr)*4);
59         EITdata = new __u8[ByteSize];
60         CacheSize+=ByteSize;
61         memcpy(EITdata, (__u8*) e, 12);
62         memcpy(EITdata+12, descr, ByteSize-12);
63 }
64
65 const eit_event_struct* eventData::get() const
66 {
67         int pos = 12;
68         int tmp = ByteSize-12;
69         memcpy(data, EITdata, 12);
70         __u32 *p = (__u32*)(EITdata+12);
71         while(tmp>0)
72         {
73                 descriptorMap::iterator it =
74                         descriptors.find(*p++);
75                 if ( it != descriptors.end() )
76                 {
77                         int b = it->second.second[1]+2;
78                         memcpy(data+pos, it->second.second, b );
79                         pos += b;
80                 }
81                 tmp-=4;
82         }
83
84         return (const eit_event_struct*)data;
85 }
86
87 eventData::~eventData()
88 {
89         if ( ByteSize )
90         {
91                 CacheSize-=ByteSize;
92                 ByteSize-=12;
93                 __u32 *d = (__u32*)(EITdata+12);
94                 while(ByteSize)
95                 {
96                         descriptorMap::iterator it =
97                                 descriptors.find(*d++);
98                         if ( it != descriptors.end() )
99                         {
100                                 descriptorPair &p = it->second;
101                                 if (!--p.first) // no more used descriptor
102                                 {
103                                         CacheSize -= it->second.second[1];
104                                         delete [] it->second.second;    // free descriptor memory
105                                         descriptors.erase(it);  // remove entry from descriptor map
106                                 }
107                         }
108                         ByteSize-=4;
109                 }
110                 delete [] EITdata;
111         }
112 }
113
114 void eventData::load(FILE *f)
115 {
116         int size=0;
117         int id=0;
118         __u8 header[2];
119         descriptorPair p;
120         fread(&size, sizeof(int), 1, f);
121         while(size)
122         {
123                 fread(&id, sizeof(__u32), 1, f);
124                 fread(&p.first, sizeof(int), 1, f);
125                 fread(header, 2, 1, f);
126                 int bytes = header[1]+2;
127                 p.second = new __u8[bytes];
128                 p.second[0] = header[0];
129                 p.second[1] = header[1];
130                 fread(p.second+2, bytes-2, 1, f);
131                 descriptors[id]=p;
132                 --size;
133                 CacheSize+=bytes;
134         }
135 }
136
137 void eventData::save(FILE *f)
138 {
139         int size=descriptors.size();
140         descriptorMap::iterator it(descriptors.begin());
141         fwrite(&size, sizeof(int), 1, f);
142         while(size)
143         {
144                 fwrite(&it->first, sizeof(__u32), 1, f);
145                 fwrite(&it->second.first, sizeof(int), 1, f);
146                 fwrite(it->second.second, it->second.second[1]+2, 1, f);
147                 ++it;
148                 --size;
149         }
150 }
151
152 eEPGCache* eEPGCache::instance;
153 pthread_mutex_t eEPGCache::cache_lock=
154         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
155 pthread_mutex_t eEPGCache::channel_map_lock=
156         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
157
158 DEFINE_REF(eEPGCache)
159
160 eEPGCache::eEPGCache()
161         :messages(this,1), cleanTimer(this)//, paused(0)
162 {
163         eDebug("[EPGC] Initialized EPGCache");
164
165         CONNECT(messages.recv_msg, eEPGCache::gotMessage);
166         CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
167         CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
168
169         ePtr<eDVBResourceManager> res_mgr;
170         eDVBResourceManager::getInstance(res_mgr);
171         if (!res_mgr)
172                 eDebug("[eEPGCache] no resource manager !!!!!!!");
173         else
174                 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
175         instance=this;
176 }
177
178 void eEPGCache::timeUpdated()
179 {
180         if (!sync())
181         {
182                 eDebug("[EPGC] time updated.. start EPG Mainloop");
183                 run();
184         } else
185                 messages.send(Message(Message::timeChanged));
186 }
187
188 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
189 {
190         if ( chan )
191         {
192 //              eDebug("[eEPGCache] add channel %p", chan);
193                 channel_data *data = new channel_data(this);
194                 data->channel = chan;
195                 data->prevChannelState = -1;
196 #ifdef ENABLE_PRIVATE_EPG
197                 data->m_PrivatePid = -1;
198 #endif
199                 singleLock s(channel_map_lock);
200                 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
201                 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
202         }
203 }
204
205 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
206 {
207         singleLock s(channel_map_lock);
208         channelMapIterator it =
209                 m_knownChannels.find(chan);
210         if ( it == m_knownChannels.end() )
211                 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
212         else
213         {
214                 channel_data &data = *it->second;
215                 ePtr<eDVBResourceManager> res_mgr;
216                 if ( eDVBResourceManager::getInstance( res_mgr ) )
217                         eDebug("[eEPGCache] no res manager!!");
218                 else
219                 {
220                         ePtr<iDVBDemux> demux;
221                         if ( data.channel->getDemux(demux, 0) )
222                         {
223                                 eDebug("[eEPGCache] no demux!!");
224                                 return;
225                         }
226                         else
227                         {
228                                 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
229                                 if ( res )
230                                 {
231                                         eDebug("[eEPGCache] couldnt initialize nownext reader!!");
232                                         return;
233                                 }
234
235                                 res = demux->createSectionReader( this, data.m_ScheduleReader );
236                                 if ( res )
237                                 {
238                                         eDebug("[eEPGCache] couldnt initialize schedule reader!!");
239                                         return;
240                                 }
241
242                                 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
243                                 if ( res )
244                                 {
245                                         eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
246                                         return;
247                                 }
248 #ifdef ENABLE_PRIVATE_EPG
249                                 res = demux->createSectionReader( this, data.m_PrivateReader );
250                                 if ( res )
251                                 {
252                                         eDebug("[eEPGCache] couldnt initialize private reader!!");
253                                         return;
254                                 }
255 #endif
256                                 messages.send(Message(Message::startChannel, chan));
257                                 // -> gotMessage -> changedService
258                         }
259                 }
260         }
261 }
262
263 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
264 {
265         channelMapIterator it =
266                 m_knownChannels.find(chan);
267         if ( it != m_knownChannels.end() )
268         {
269                 int state=0;
270                 chan->getState(state);
271                 if ( it->second->prevChannelState != state )
272                 {
273                         switch (state)
274                         {
275                                 case iDVBChannel::state_ok:
276                                 {
277                                         eDebug("[eEPGCache] channel %p running", chan);
278                                         DVBChannelRunning(chan);
279                                         break;
280                                 }
281                                 case iDVBChannel::state_release:
282                                 {
283                                         eDebug("[eEPGCache] remove channel %p", chan);
284                                         messages.send(Message(Message::leaveChannel, chan));
285                                         while(!it->second->can_delete)
286                                                 usleep(1000);
287                                         delete it->second;
288                                         m_knownChannels.erase(it);
289                                         // -> gotMessage -> abortEPG
290                                         break;
291                                 }
292                                 default: // ignore all other events
293                                         return;
294                         }
295                         it->second->prevChannelState = state;
296                 }
297         }
298 }
299
300 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
301 {
302         eit_t *eit = (eit_t*) data;
303
304         int len=HILO(eit->section_length)-1;//+3-4;
305         int ptr=EIT_SIZE;
306         if ( ptr >= len )
307                 return;
308
309         // This fixed the EPG on the Multichoice irdeto systems
310         // the EIT packet is non-compliant.. their EIT packet stinks
311         if ( data[ptr-1] < 0x40 )
312                 --ptr;
313
314         uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
315         eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
316         int eit_event_size;
317         int duration;
318
319         time_t TM = parseDVBtime( eit_event->start_time_1, eit_event->start_time_2,     eit_event->start_time_3, eit_event->start_time_4, eit_event->start_time_5);
320         time_t now = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
321
322         if ( TM != 3599 && TM > -1)
323                 channel->haveData |= source;
324
325         singleLock s(cache_lock);
326         // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
327         // oder eine durch [] erzeugte
328         std::pair<eventMap,timeMap> &servicemap = eventDB[service];
329         eventMap::iterator prevEventIt = servicemap.first.end();
330         timeMap::iterator prevTimeIt = servicemap.second.end();
331
332         while (ptr<len)
333         {
334                 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
335
336                 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
337                 TM = parseDVBtime(
338                         eit_event->start_time_1,
339                         eit_event->start_time_2,
340                         eit_event->start_time_3,
341                         eit_event->start_time_4,
342                         eit_event->start_time_5);
343
344                 if ( TM == 3599 )
345                         goto next;
346
347                 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
348                         goto next;
349
350                 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ )  // old events should not be cached
351                 {
352                         __u16 event_id = HILO(eit_event->event_id);
353 //                      eDebug("event_id is %d sid is %04x", event_id, service.sid);
354
355                         eventData *evt = 0;
356                         int ev_erase_count = 0;
357                         int tm_erase_count = 0;
358
359                         // search in eventmap
360                         eventMap::iterator ev_it =
361                                 servicemap.first.find(event_id);
362
363                         // entry with this event_id is already exist ?
364                         if ( ev_it != servicemap.first.end() )
365                         {
366                                 if ( source > ev_it->second->type )  // update needed ?
367                                         goto next; // when not.. the skip this entry
368
369                                 // search this event in timemap
370                                 timeMap::iterator tm_it_tmp = 
371                                         servicemap.second.find(ev_it->second->getStartTime());
372
373                                 if ( tm_it_tmp != servicemap.second.end() )
374                                 {
375                                         if ( tm_it_tmp->first == TM ) // correct eventData
376                                         {
377                                                 // exempt memory
378                                                 delete ev_it->second;
379                                                 evt = new eventData(eit_event, eit_event_size, source);
380                                                 ev_it->second=evt;
381                                                 tm_it_tmp->second=evt;
382                                                 goto next;
383                                         }
384                                         else
385                                         {
386                                                 tm_erase_count++;
387                                                 // delete the found record from timemap
388                                                 servicemap.second.erase(tm_it_tmp);
389                                                 prevTimeIt=servicemap.second.end();
390                                         }
391                                 }
392                         }
393
394                         // search in timemap, for check of a case if new time has coincided with time of other event 
395                         // or event was is not found in eventmap
396                         timeMap::iterator tm_it =
397                                 servicemap.second.find(TM);
398
399                         if ( tm_it != servicemap.second.end() )
400                         {
401                                 // i think, if event is not found on eventmap, but found on timemap updating nevertheless demands
402 #if 0
403                                 if ( source > tm_it->second->type && tm_erase_count == 0 ) // update needed ?
404                                         goto next; // when not.. the skip this entry
405 #endif
406
407                                 // search this time in eventmap
408                                 eventMap::iterator ev_it_tmp = 
409                                         servicemap.first.find(tm_it->second->getEventID());
410
411                                 if ( ev_it_tmp != servicemap.first.end() )
412                                 {
413                                         ev_erase_count++;                               
414                                         // delete the found record from eventmap
415                                         servicemap.first.erase(ev_it_tmp);
416                                         prevEventIt=servicemap.first.end();
417                                 }
418                         }
419                         
420                         evt = new eventData(eit_event, eit_event_size, source);
421 #if EPG_DEBUG
422                         bool consistencyCheck=true;
423 #endif
424                         if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
425                         {
426                                 // exempt memory
427                                 delete ev_it->second; 
428                                 delete tm_it->second;
429                                 ev_it->second=evt;
430                                 tm_it->second=evt;
431                         }
432                         else if (ev_erase_count == 0 && tm_erase_count > 0) 
433                         {
434                                 // exempt memory
435                                 delete ev_it->second;
436                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
437                                 ev_it->second=evt;
438                         }
439                         else if (ev_erase_count > 0 && tm_erase_count == 0)
440                         {
441                                 // exempt memory
442                                 delete tm_it->second;
443                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
444                                 tm_it->second=evt;
445                         }
446                         else // added new eventData
447                         {
448 #if EPG_DEBUG
449                                 consistencyCheck=false;
450 #endif
451                                 prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
452                                 prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
453                         }
454 #if EPG_DEBUG
455                         if ( consistencyCheck )
456                         {
457                                 if ( tm_it->second != evt || ev_it->second != evt )
458                                         eFatal("tm_it->second != ev_it->second");
459                                 else if ( tm_it->second->getStartTime() != tm_it->first )
460                                         eFatal("event start_time(%d) non equal timemap key(%d)", 
461                                                 tm_it->second->getStartTime(), tm_it->first );
462                                 else if ( tm_it->first != TM )
463                                         eFatal("timemap key(%d) non equal TM(%d)", 
464                                                 tm_it->first, TM);
465                                 else if ( ev_it->second->getEventID() != ev_it->first )
466                                         eFatal("event_id (%d) non equal event_map key(%d)",
467                                                 ev_it->second->getEventID(), ev_it->first);
468                                 else if ( ev_it->first != event_id )
469                                         eFatal("eventmap key(%d) non equal event_id(%d)", 
470                                                 ev_it->first, event_id );
471                         }
472 #endif
473                 }
474 next:
475 #if EPG_DEBUG
476                 if ( servicemap.first.size() != servicemap.second.size() )
477                 {
478                         FILE *f = fopen("/hdd/event_map.txt", "w+");
479                         int i=0;
480                         for (eventMap::iterator it(servicemap.first.begin())
481                                 ; it != servicemap.first.end(); ++it )
482                                 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
483                                         i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
484                         fclose(f);
485                         f = fopen("/hdd/time_map.txt", "w+");
486                         i=0;
487                         for (timeMap::iterator it(servicemap.second.begin())
488                                 ; it != servicemap.second.end(); ++it )
489                                         fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
490                                                 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
491                         fclose(f);
492
493                         eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d", 
494                                 service.sid, service.tsid, service.onid, 
495                                 servicemap.first.size(), servicemap.second.size() );
496                 }
497 #endif
498                 ptr += eit_event_size;
499                 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
500         }
501 }
502
503 void eEPGCache::flushEPG(const uniqueEPGKey & s)
504 {
505         eDebug("[EPGC] flushEPG %d", (int)(bool)s);
506         singleLock l(cache_lock);
507         if (s)  // clear only this service
508         {
509                 eventCache::iterator it = eventDB.find(s);
510                 if ( it != eventDB.end() )
511                 {
512                         eventMap &evMap = it->second.first;
513                         timeMap &tmMap = it->second.second;
514                         tmMap.clear();
515                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
516                                 delete i->second;
517                         evMap.clear();
518                         eventDB.erase(it);
519
520                         // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
521 #ifdef ENABLE_PRIVATE_EPG
522                         contentMaps::iterator it =
523                                 content_time_tables.find(s);
524                         if ( it != content_time_tables.end() )
525                         {
526                                 it->second.clear();
527                                 content_time_tables.erase(it);
528                         }
529 #endif
530                 }
531         }
532         else // clear complete EPG Cache
533         {
534                 for (eventCache::iterator it(eventDB.begin());
535                         it != eventDB.end(); ++it)
536                 {
537                         eventMap &evMap = it->second.first;
538                         timeMap &tmMap = it->second.second;
539                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
540                                 delete i->second;
541                         evMap.clear();
542                         tmMap.clear();
543                 }
544                 eventDB.clear();
545 #ifdef ENABLE_PRIVATE_EPG
546                 content_time_tables.clear();
547 #endif
548                 channelLastUpdated.clear();
549                 singleLock m(channel_map_lock);
550                 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
551                         it->second->startEPG();
552         }
553         eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
554 }
555
556 void eEPGCache::cleanLoop()
557 {
558         singleLock s(cache_lock);
559         if (!eventDB.empty())
560         {
561                 eDebug("[EPGC] start cleanloop");
562
563                 time_t now = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
564
565                 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
566                 {
567                         bool updated = false;
568                         for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
569                         {
570                                 if ( now > (It->first+It->second->getDuration()) )  // outdated normal entry (nvod references to)
571                                 {
572                                         // remove entry from eventMap
573                                         eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
574                                         if ( b != DBIt->second.first.end() )
575                                         {
576                                                 // release Heap Memory for this entry   (new ....)
577 //                                              eDebug("[EPGC] delete old event (evmap)");
578                                                 DBIt->second.first.erase(b);
579                                         }
580
581                                         // remove entry from timeMap
582 //                                      eDebug("[EPGC] release heap mem");
583                                         delete It->second;
584                                         DBIt->second.second.erase(It++);
585 //                                      eDebug("[EPGC] delete old event (timeMap)");
586                                         updated = true;
587                                 }
588                                 else
589                                         ++It;
590                         }
591 #ifdef ENABLE_PRIVATE_EPG
592                         if ( updated )
593                         {
594                                 contentMaps::iterator x =
595                                         content_time_tables.find( DBIt->first );
596                                 if ( x != content_time_tables.end() )
597                                 {
598                                         timeMap &tmMap = eventDB[DBIt->first].second;
599                                         for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
600                                         {
601                                                 for ( contentTimeMap::iterator it(i->second.begin());
602                                                         it != i->second.end(); )
603                                                 {
604                                                         if ( tmMap.find(it->second.first) == tmMap.end() )
605                                                                 i->second.erase(it++);
606                                                         else
607                                                                 ++it;
608                                                 }
609                                                 if ( i->second.size() )
610                                                         ++i;
611                                                 else
612                                                         x->second.erase(i++);
613                                         }
614                                 }
615                         }
616 #endif
617                 }
618                 eDebug("[EPGC] stop cleanloop");
619                 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
620         }
621         cleanTimer.start(CLEAN_INTERVAL,true);
622 }
623
624 eEPGCache::~eEPGCache()
625 {
626         messages.send(Message::quit);
627         kill(); // waiting for thread shutdown
628         singleLock s(cache_lock);
629         for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
630                 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
631                         delete It->second;
632 }
633
634 void eEPGCache::gotMessage( const Message &msg )
635 {
636         switch (msg.type)
637         {
638                 case Message::flush:
639                         flushEPG(msg.service);
640                         break;
641                 case Message::startChannel:
642                 {
643                         singleLock s(channel_map_lock);
644                         channelMapIterator channel =
645                                 m_knownChannels.find(msg.channel);
646                         if ( channel != m_knownChannels.end() )
647                                 channel->second->startChannel();
648                         break;
649                 }
650                 case Message::leaveChannel:
651                 {
652                         singleLock s(channel_map_lock);
653                         channelMapIterator channel =
654                                 m_knownChannels.find(msg.channel);
655                         if ( channel != m_knownChannels.end() )
656                                 channel->second->abortEPG();
657                         break;
658                 }
659                 case Message::quit:
660                         quit(0);
661                         break;
662 #ifdef ENABLE_PRIVATE_EPG
663                 case Message::got_private_pid:
664                 {
665                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
666                         {
667                                 eDVBChannel *channel = (eDVBChannel*) it->first;
668                                 channel_data *data = it->second;
669                                 eDVBChannelID chid = channel->getChannelID();
670                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
671                                         chid.original_network_id.get() == msg.service.onid &&
672                                         data->m_PrivatePid == -1 )
673                                 {
674                                         data->m_PrevVersion = -1;
675                                         data->m_PrivatePid = msg.pid;
676                                         data->m_PrivateService = msg.service;
677                                         updateMap::iterator It = channelLastUpdated.find( channel->getChannelID() );
678                                         int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (time(0)+eDVBLocalTimeHandler::getInstance()->difference()-It->second) * 1000 ) ) : ZAP_DELAY );
679                                         if (update < ZAP_DELAY)
680                                                 update = ZAP_DELAY;
681                                         data->startPrivateTimer.start(update, 1);
682                                         if (update >= 60000)
683                                                 eDebug("[EPGC] next private update in %i min", update/60000);
684                                         else if (update >= 1000)
685                                                 eDebug("[EPGC] next private update in %i sec", update/1000);
686                                         break;
687                                 }
688                         }
689                         break;
690                 }
691 #endif
692                 case Message::timeChanged:
693                         cleanLoop();
694                         break;
695                 default:
696                         eDebug("unhandled EPGCache Message!!");
697                         break;
698         }
699 }
700
701 void eEPGCache::thread()
702 {
703         hasStarted();
704         nice(4);
705         load();
706         cleanLoop();
707         runLoop();
708         save();
709 }
710
711 void eEPGCache::load()
712 {
713         singleLock s(cache_lock);
714         FILE *f = fopen("/hdd/epg.dat", "r");
715         if (f)
716         {
717                 int size=0;
718                 int cnt=0;
719 #if 0
720                 unsigned char md5_saved[16];
721                 unsigned char md5[16];
722                 bool md5ok=false;
723
724                 if (!md5_file("/hdd/epg.dat", 1, md5))
725                 {
726                         FILE *f = fopen("/hdd/epg.dat.md5", "r");
727                         if (f)
728                         {
729                                 fread( md5_saved, 16, 1, f);
730                                 fclose(f);
731                                 if ( !memcmp(md5_saved, md5, 16) )
732                                         md5ok=true;
733                         }
734                 }
735                 if ( md5ok )
736 #endif
737                 {
738                         unsigned int magic=0;
739                         fread( &magic, sizeof(int), 1, f);
740                         if (magic != 0x98765432)
741                         {
742                                 eDebug("epg file has incorrect byte order.. dont read it");
743                                 fclose(f);
744                                 return;
745                         }
746                         char text1[13];
747                         fread( text1, 13, 1, f);
748                         if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
749                         {
750                                 fread( &size, sizeof(int), 1, f);
751                                 while(size--)
752                                 {
753                                         uniqueEPGKey key;
754                                         eventMap evMap;
755                                         timeMap tmMap;
756                                         int size=0;
757                                         fread( &key, sizeof(uniqueEPGKey), 1, f);
758                                         fread( &size, sizeof(int), 1, f);
759                                         while(size--)
760                                         {
761                                                 __u8 len=0;
762                                                 __u8 type=0;
763                                                 eventData *event=0;
764                                                 fread( &type, sizeof(__u8), 1, f);
765                                                 fread( &len, sizeof(__u8), 1, f);
766                                                 event = new eventData(0, len, type);
767                                                 event->EITdata = new __u8[len];
768                                                 eventData::CacheSize+=len;
769                                                 fread( event->EITdata, len, 1, f);
770                                                 evMap[ event->getEventID() ]=event;
771                                                 tmMap[ event->getStartTime() ]=event;
772                                                 ++cnt;
773                                         }
774                                         eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
775                                 }
776                                 eventData::load(f);
777                                 eDebug("%d events read from /hdd/epg.dat", cnt);
778 #ifdef ENABLE_PRIVATE_EPG
779                                 char text2[11];
780                                 fread( text2, 11, 1, f);
781                                 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
782                                 {
783                                         size=0;
784                                         fread( &size, sizeof(int), 1, f);
785                                         while(size--)
786                                         {
787                                                 int size=0;
788                                                 uniqueEPGKey key;
789                                                 fread( &key, sizeof(uniqueEPGKey), 1, f);
790                                                 fread( &size, sizeof(int), 1, f);
791                                                 while(size--)
792                                                 {
793                                                         int size;
794                                                         int content_id;
795                                                         fread( &content_id, sizeof(int), 1, f);
796                                                         fread( &size, sizeof(int), 1, f);
797                                                         while(size--)
798                                                         {
799                                                                 time_t time1, time2;
800                                                                 __u16 event_id;
801                                                                 fread( &time1, sizeof(time_t), 1, f);
802                                                                 fread( &time2, sizeof(time_t), 1, f);
803                                                                 fread( &event_id, sizeof(__u16), 1, f);
804                                                                 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
805                                                         }
806                                                 }
807                                         }
808                                 }
809 #endif // ENABLE_PRIVATE_EPG
810                         }
811                         else
812                                 eDebug("[EPGC] don't read old epg database");
813                         fclose(f);
814                 }
815         }
816 }
817
818 void eEPGCache::save()
819 {
820         struct statfs s;
821         off64_t tmp;
822         if (statfs("/hdd", &s)<0)
823                 tmp=0;
824         else
825         {
826                 tmp=s.f_blocks;
827                 tmp*=s.f_bsize;
828         }
829
830         // prevent writes to builtin flash
831         if ( tmp < 1024*1024*50 ) // storage size < 50MB
832                 return;
833
834         // check for enough free space on storage
835         tmp=s.f_bfree;
836         tmp*=s.f_bsize;
837         if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
838                 return;
839
840         FILE *f = fopen("/hdd/epg.dat", "w");
841         int cnt=0;
842         if ( f )
843         {
844                 unsigned int magic = 0x98765432;
845                 fwrite( &magic, sizeof(int), 1, f);
846                 const char *text = "ENIGMA_EPG_V5";
847                 fwrite( text, 13, 1, f );
848                 int size = eventDB.size();
849                 fwrite( &size, sizeof(int), 1, f );
850                 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
851                 {
852                         timeMap &timemap = service_it->second.second;
853                         fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
854                         size = timemap.size();
855                         fwrite( &size, sizeof(int), 1, f);
856                         for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
857                         {
858                                 __u8 len = time_it->second->ByteSize;
859                                 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
860                                 fwrite( &len, sizeof(__u8), 1, f);
861                                 fwrite( time_it->second->EITdata, len, 1, f);
862                                 ++cnt;
863                         }
864                 }
865                 eDebug("%d events written to /hdd/epg.dat", cnt);
866                 eventData::save(f);
867 #ifdef ENABLE_PRIVATE_EPG
868                 const char* text3 = "PRIVATE_EPG";
869                 fwrite( text3, 11, 1, f );
870                 size = content_time_tables.size();
871                 fwrite( &size, sizeof(int), 1, f);
872                 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
873                 {
874                         contentMap &content_time_table = a->second;
875                         fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
876                         int size = content_time_table.size();
877                         fwrite( &size, sizeof(int), 1, f);
878                         for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
879                         {
880                                 int size = i->second.size();
881                                 fwrite( &i->first, sizeof(int), 1, f);
882                                 fwrite( &size, sizeof(int), 1, f);
883                                 for ( contentTimeMap::iterator it(i->second.begin());
884                                         it != i->second.end(); ++it )
885                                 {
886                                         fwrite( &it->first, sizeof(time_t), 1, f);
887                                         fwrite( &it->second.first, sizeof(time_t), 1, f);
888                                         fwrite( &it->second.second, sizeof(__u16), 1, f);
889                                 }
890                         }
891                 }
892 #endif
893                 fclose(f);
894 #if 0
895                 unsigned char md5[16];
896                 if (!md5_file("/hdd/epg.dat", 1, md5))
897                 {
898                         FILE *f = fopen("/hdd/epg.dat.md5", "w");
899                         if (f)
900                         {
901                                 fwrite( md5, 16, 1, f);
902                                 fclose(f);
903                         }
904                 }
905 #endif
906         }
907 }
908
909 eEPGCache::channel_data::channel_data(eEPGCache *ml)
910         :cache(ml)
911         ,abortTimer(ml), zapTimer(ml), startPrivateTimer(ml)
912         ,state(0), isRunning(0), haveData(0), can_delete(1)
913 {
914         CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
915         CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
916         CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
917 }
918
919 bool eEPGCache::channel_data::finishEPG()
920 {
921         if (!isRunning)  // epg ready
922         {
923                 eDebug("[EPGC] stop caching events(%ld)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
924                 zapTimer.start(UPDATE_INTERVAL, 1);
925                 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
926                 for (int i=0; i < 3; ++i)
927                 {
928                         seenSections[i].clear();
929                         calcedSections[i].clear();
930                 }
931                 singleLock l(cache->cache_lock);
932                 cache->channelLastUpdated[channel->getChannelID()] = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
933 #ifdef ENABLE_PRIVATE_EPG
934                 if (seenPrivateSections.empty())
935 #endif
936                 can_delete=1;
937                 return true;
938         }
939         return false;
940 }
941
942 void eEPGCache::channel_data::startEPG()
943 {
944         eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->difference()+time(0));
945         state=0;
946         haveData=0;
947         can_delete=0;
948         for (int i=0; i < 3; ++i)
949         {
950                 seenSections[i].clear();
951                 calcedSections[i].clear();
952         }
953
954         eDVBSectionFilterMask mask;
955         memset(&mask, 0, sizeof(mask));
956         mask.pid = 0x12;
957         mask.flags = eDVBSectionFilterMask::rfCRC;
958
959         mask.data[0] = 0x4E;
960         mask.mask[0] = 0xFE;
961         m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
962         m_NowNextReader->start(mask);
963         isRunning |= NOWNEXT;
964
965         mask.data[0] = 0x50;
966         mask.mask[0] = 0xF0;
967         m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
968         m_ScheduleReader->start(mask);
969         isRunning |= SCHEDULE;
970
971         mask.data[0] = 0x60;
972         mask.mask[0] = 0xF0;
973         m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
974         m_ScheduleOtherReader->start(mask);
975         isRunning |= SCHEDULE_OTHER;
976
977         abortTimer.start(7000,true);
978 }
979
980 void eEPGCache::channel_data::abortNonAvail()
981 {
982         if (!state)
983         {
984                 if ( !(haveData&eEPGCache::NOWNEXT) && (isRunning&eEPGCache::NOWNEXT) )
985                 {
986                         eDebug("[EPGC] abort non avail nownext reading");
987                         isRunning &= ~eEPGCache::NOWNEXT;
988                         m_NowNextReader->stop();
989                         m_NowNextConn=0;
990                 }
991                 if ( !(haveData&eEPGCache::SCHEDULE) && (isRunning&eEPGCache::SCHEDULE) )
992                 {
993                         eDebug("[EPGC] abort non avail schedule reading");
994                         isRunning &= ~SCHEDULE;
995                         m_ScheduleReader->stop();
996                         m_ScheduleConn=0;
997                 }
998                 if ( !(haveData&eEPGCache::SCHEDULE_OTHER) && (isRunning&eEPGCache::SCHEDULE_OTHER) )
999                 {
1000                         eDebug("[EPGC] abort non avail schedule_other reading");
1001                         isRunning &= ~SCHEDULE_OTHER;
1002                         m_ScheduleOtherReader->stop();
1003                         m_ScheduleOtherConn=0;
1004                 }
1005                 if ( isRunning )
1006                         abortTimer.start(90000, true);
1007                 else
1008                 {
1009                         ++state;
1010                         for (int i=0; i < 3; ++i)
1011                         {
1012                                 seenSections[i].clear();
1013                                 calcedSections[i].clear();
1014                         }
1015 #ifdef ENABLE_PRIVATE_EPG
1016                         if (seenPrivateSections.empty())
1017 #endif
1018                         can_delete=1;
1019                 }
1020         }
1021         ++state;
1022 }
1023
1024 void eEPGCache::channel_data::startChannel()
1025 {
1026         updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1027
1028         int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (time(0)+eDVBLocalTimeHandler::getInstance()->difference()-It->second) * 1000 ) ) : ZAP_DELAY );
1029
1030         if (update < ZAP_DELAY)
1031                 update = ZAP_DELAY;
1032
1033         zapTimer.start(update, 1);
1034         if (update >= 60000)
1035                 eDebug("[EPGC] next update in %i min", update/60000);
1036         else if (update >= 1000)
1037                 eDebug("[EPGC] next update in %i sec", update/1000);
1038 }
1039
1040 void eEPGCache::channel_data::abortEPG()
1041 {
1042         for (int i=0; i < 3; ++i)
1043         {
1044                 seenSections[i].clear();
1045                 calcedSections[i].clear();
1046         }
1047         abortTimer.stop();
1048         zapTimer.stop();
1049         if (isRunning)
1050         {
1051                 eDebug("[EPGC] abort caching events !!");
1052                 if (isRunning & eEPGCache::SCHEDULE)
1053                 {
1054                         isRunning &= ~eEPGCache::SCHEDULE;
1055                         m_ScheduleReader->stop();
1056                         m_ScheduleConn=0;
1057                 }
1058                 if (isRunning & eEPGCache::NOWNEXT)
1059                 {
1060                         isRunning &= ~eEPGCache::NOWNEXT;
1061                         m_NowNextReader->stop();
1062                         m_NowNextConn=0;
1063                 }
1064                 if (isRunning & SCHEDULE_OTHER)
1065                 {
1066                         isRunning &= ~eEPGCache::SCHEDULE_OTHER;
1067                         m_ScheduleOtherReader->stop();
1068                         m_ScheduleOtherConn=0;
1069                 }
1070         }
1071 #ifdef ENABLE_PRIVATE_EPG
1072         if (m_PrivateReader)
1073                 m_PrivateReader->stop();
1074         if (m_PrivateConn)
1075                 m_PrivateConn=0;
1076 #endif
1077         can_delete=1;
1078 }
1079
1080 void eEPGCache::channel_data::readData( const __u8 *data)
1081 {
1082         if (!data)
1083                 eDebug("get Null pointer from section reader !!");
1084         else
1085         {
1086                 int source;
1087                 int map;
1088                 iDVBSectionReader *reader=NULL;
1089                 switch(data[0])
1090                 {
1091                         case 0x4E ... 0x4F:
1092                                 reader=m_NowNextReader;
1093                                 source=eEPGCache::NOWNEXT;
1094                                 map=0;
1095                                 break;
1096                         case 0x50 ... 0x5F:
1097                                 reader=m_ScheduleReader;
1098                                 source=eEPGCache::SCHEDULE;
1099                                 map=1;
1100                                 break;
1101                         case 0x60 ... 0x6F:
1102                                 reader=m_ScheduleOtherReader;
1103                                 source=eEPGCache::SCHEDULE_OTHER;
1104                                 map=2;
1105                                 break;
1106                         default:
1107                                 eDebug("[EPGC] unknown table_id !!!");
1108                                 return;
1109                 }
1110                 tidMap &seenSections = this->seenSections[map];
1111                 tidMap &calcedSections = this->calcedSections[map];
1112                 if ( state == 1 && calcedSections == seenSections || state > 1 )
1113                 {
1114                         eDebugNoNewLine("[EPGC] ");
1115                         switch (source)
1116                         {
1117                                 case eEPGCache::NOWNEXT:
1118                                         m_NowNextConn=0;
1119                                         eDebugNoNewLine("nownext");
1120                                         break;
1121                                 case eEPGCache::SCHEDULE:
1122                                         m_ScheduleConn=0;
1123                                         eDebugNoNewLine("schedule");
1124                                         break;
1125                                 case eEPGCache::SCHEDULE_OTHER:
1126                                         m_ScheduleOtherConn=0;
1127                                         eDebugNoNewLine("schedule other");
1128                                         break;
1129                                 default: eDebugNoNewLine("unknown");break;
1130                         }
1131                         eDebug(" finished(%ld)", time(0)+eDVBLocalTimeHandler::getInstance()->difference());
1132                         if ( reader )
1133                                 reader->stop();
1134                         isRunning &= ~source;
1135                         if (!isRunning)
1136                                 finishEPG();
1137                 }
1138                 else
1139                 {
1140                         eit_t *eit = (eit_t*) data;
1141                         __u32 sectionNo = data[0] << 24;
1142                         sectionNo |= data[3] << 16;
1143                         sectionNo |= data[4] << 8;
1144                         sectionNo |= eit->section_number;
1145
1146                         tidMap::iterator it =
1147                                 seenSections.find(sectionNo);
1148
1149                         if ( it == seenSections.end() )
1150                         {
1151                                 seenSections.insert(sectionNo);
1152                                 calcedSections.insert(sectionNo);
1153                                 __u32 tmpval = sectionNo & 0xFFFFFF00;
1154                                 __u8 incr = source == NOWNEXT ? 1 : 8;
1155                                 for ( int i = 0; i <= eit->last_section_number; i+=incr )
1156                                 {
1157                                         if ( i == eit->section_number )
1158                                         {
1159                                                 for (int x=i; x <= eit->segment_last_section_number; ++x)
1160                                                         calcedSections.insert(tmpval|(x&0xFF));
1161                                         }
1162                                         else
1163                                                 calcedSections.insert(tmpval|(i&0xFF));
1164                                 }
1165                                 cache->sectionRead(data, source, this);
1166                         }
1167                 }
1168         }
1169 }
1170
1171 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1172 // if t == -1 we search the current event...
1173 {
1174         singleLock s(cache_lock);
1175         uniqueEPGKey key(service);
1176
1177         // check if EPG for this service is ready...
1178         eventCache::iterator It = eventDB.find( key );
1179         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1180         {
1181                 if (t==-1)
1182                         t = time(0)+eDVBLocalTimeHandler::getInstance()->difference();
1183                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1184                         It->second.second.upper_bound(t); // just >
1185                 if ( i != It->second.second.end() )
1186                 {
1187                         if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1188                         {
1189                                 timeMap::iterator x = i;
1190                                 --x;
1191                                 if ( x != It->second.second.end() )
1192                                 {
1193                                         time_t start_time = x->second->getStartTime();
1194                                         if (direction >= 0)
1195                                         {
1196                                                 if (t < start_time)
1197                                                         return -1;
1198                                                 if (t > (start_time+x->second->getDuration()))
1199                                                         return -1;
1200                                         }
1201                                         i = x;
1202                                 }
1203                                 else
1204                                         return -1;
1205                         }
1206                         result = i->second;
1207                         return 0;
1208                 }
1209         }
1210         return -1;
1211 }
1212
1213 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1214 {
1215         singleLock s(cache_lock);
1216         const eventData *data=0;
1217         RESULT ret = lookupEventTime(service, t, data, direction);
1218         if ( !ret && data )
1219                 result = data->get();
1220         return ret;
1221 }
1222
1223 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1224 {
1225         singleLock s(cache_lock);
1226         const eventData *data=0;
1227         RESULT ret = lookupEventTime(service, t, data, direction);
1228         if ( !ret && data )
1229                 result = new Event((uint8_t*)data->get());
1230         return ret;
1231 }
1232
1233 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1234 {
1235         singleLock s(cache_lock);
1236         const eventData *data=0;
1237         RESULT ret = lookupEventTime(service, t, data, direction);
1238         if ( !ret && data )
1239         {
1240                 Event ev((uint8_t*)data->get());
1241                 result = new eServiceEvent();
1242                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1243                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1244         }
1245         return ret;
1246 }
1247
1248 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1249 {
1250         singleLock s(cache_lock);
1251         uniqueEPGKey key( service );
1252
1253         eventCache::iterator It = eventDB.find( key );
1254         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1255         {
1256                 eventMap::iterator i( It->second.first.find( event_id ));
1257                 if ( i != It->second.first.end() )
1258                 {
1259                         result = i->second;
1260                         return 0;
1261                 }
1262                 else
1263                 {
1264                         result = 0;
1265                         eDebug("event %04x not found in epgcache", event_id);
1266                 }
1267         }
1268         return -1;
1269 }
1270
1271 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1272 {
1273         singleLock s(cache_lock);
1274         const eventData *data=0;
1275         RESULT ret = lookupEventId(service, event_id, data);
1276         if ( !ret && data )
1277                 result = data->get();
1278         return ret;
1279 }
1280
1281 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1282 {
1283         singleLock s(cache_lock);
1284         const eventData *data=0;
1285         RESULT ret = lookupEventId(service, event_id, data);
1286         if ( !ret && data )
1287                 result = new Event((uint8_t*)data->get());
1288         return ret;
1289 }
1290
1291 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1292 {
1293         singleLock s(cache_lock);
1294         const eventData *data=0;
1295         RESULT ret = lookupEventId(service, event_id, data);
1296         if ( !ret && data )
1297         {
1298                 Event ev((uint8_t*)data->get());
1299                 result = new eServiceEvent();
1300                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1301                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1302         }
1303         return ret;
1304 }
1305
1306 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1307 {
1308         eventCache::iterator It = eventDB.find( service );
1309         if ( It != eventDB.end() && It->second.second.size() )
1310         {
1311                 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1312                 if ( begin != -1 )
1313                 {
1314                         m_timemap_cursor = It->second.second.lower_bound(begin);
1315                         if ( m_timemap_cursor != It->second.second.end() )
1316                         {
1317                                 if ( m_timemap_cursor->second->getStartTime() != begin )
1318                                 {
1319                                         timeMap::iterator x = m_timemap_cursor;
1320                                         --x;
1321                                         if ( x != It->second.second.end() )
1322                                         {
1323                                                 time_t start_time = x->second->getStartTime();
1324                                                 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1325                                                         m_timemap_cursor = x;
1326                                         }
1327                                 }
1328                         }
1329                 }
1330                 else
1331                         m_timemap_cursor = It->second.second.begin();
1332                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1333                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1334                 return 0;
1335         }
1336         return -1;
1337 }
1338
1339 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1340 {
1341         if ( m_timemap_cursor != m_timemap_end )
1342         {
1343                 result = m_timemap_cursor++->second;
1344                 return 0;
1345         }
1346         return -1;
1347 }
1348
1349 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1350 {
1351         if ( m_timemap_cursor != m_timemap_end )
1352         {
1353                 result = m_timemap_cursor++->second->get();
1354                 return 0;
1355         }
1356         return -1;
1357 }
1358
1359 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1360 {
1361         if ( m_timemap_cursor != m_timemap_end )
1362         {
1363                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1364                 return 0;
1365         }
1366         return -1;
1367 }
1368
1369 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1370 {
1371         if ( m_timemap_cursor != m_timemap_end )
1372         {
1373                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1374                 result = new eServiceEvent();
1375                 return result->parseFrom(&ev, currentQueryTsidOnid);
1376         }
1377         return -1;
1378 }
1379
1380 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1381 {
1382         PyObject *tmp=NULL;
1383         int pos=0;
1384         while(pos < argcount)
1385         {
1386                 bool inc_refcount=false;
1387                 switch(argstring[pos])
1388                 {
1389                         case '0': // PyLong 0
1390                                 tmp = PyLong_FromLong(0);
1391                                 break;
1392                         case 'I': // Event Id
1393                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1394                                 break;
1395                         case 'B': // Event Begin Time
1396                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1397                                 break;
1398                         case 'D': // Event Duration
1399                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1400                                 break;
1401                         case 'T': // Event Title
1402                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1403                                 break;
1404                         case 'S': // Event Short Description
1405                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1406                                 break;
1407                         case 'E': // Event Extended Description
1408                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1409                                 break;
1410                         case 'C': // Current Time
1411                                 tmp = nowTime;
1412                                 inc_refcount = true;
1413                                 break;
1414                         case 'R': // service reference string
1415                                 tmp = service;
1416                                 inc_refcount = true;
1417                                 break;
1418                         case 'N': // service name
1419                                 tmp = service_name;
1420                                 inc_refcount = true;
1421                 }
1422                 if (!tmp)
1423                 {
1424                         tmp = Py_None;
1425                         inc_refcount = true;
1426                 }
1427                 if (inc_refcount)
1428                         Py_INCREF(tmp);
1429                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1430         }
1431 }
1432
1433 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1434 {
1435         if (convertFunc)
1436         {
1437                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1438                 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1439                 if (result == NULL)
1440                 {
1441                         if (service_name)
1442                                 Py_DECREF(service_name);
1443                         if (nowTime)
1444                                 Py_DECREF(nowTime);
1445                         Py_DECREF(convertFuncArgs);
1446                         Py_DECREF(dest_list);
1447                         return result;
1448                 }
1449                 PyList_Append(dest_list, result);
1450                 Py_DECREF(result);
1451         }
1452         else
1453         {
1454                 PyObject *tuple = PyTuple_New(argcount);
1455                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1456                 PyList_Append(dest_list, tuple);
1457                 Py_DECREF(tuple);
1458         }
1459         return 0;
1460 }
1461
1462 // here we get a python list
1463 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1464 //   0 = PyLong(0)
1465 //   I = Event Id
1466 //   B = Event Begin Time
1467 //   D = Event Duration
1468 //   T = Event Title
1469 //   S = Event Short Description
1470 //   E = Event Extended Description
1471 //   C = Current Time
1472 //   R = Service Reference
1473 //   N = Service Name
1474 // then for each service follows a tuple
1475 //   first tuple entry is the servicereference (as string... use the ref.toString() function)
1476 //   the second is the type of query
1477 //     2 = event_id
1478 //    -1 = event before given start_time
1479 //     0 = event intersects given start_time
1480 //    +1 = event after given start_time
1481 //   the third
1482 //      when type is eventid it is the event_id
1483 //      when type is time then it is the start_time ( 0 for now_time )
1484 //   the fourth is the end_time .. ( optional .. for query all events in time range)
1485
1486 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1487 {
1488         PyObject *convertFuncArgs=NULL;
1489         int argcount=0;
1490         char *argstring=NULL;
1491         if (!PyList_Check(list))
1492         {
1493                 PyErr_SetString(PyExc_StandardError,
1494                         "type error");
1495                 eDebug("no list");
1496                 return NULL;
1497         }
1498         int listIt=0;
1499         int listSize=PyList_Size(list);
1500         if (!listSize)
1501         {
1502                 PyErr_SetString(PyExc_StandardError,
1503                         "not params given");
1504                 eDebug("not params given");
1505                 return NULL;
1506         }
1507         else 
1508         {
1509                 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1510                 if (PyString_Check(argv))
1511                 {
1512                         argstring = PyString_AS_STRING(argv);
1513                         ++listIt;
1514                 }
1515                 else
1516                         argstring = "I"; // just event id as default
1517                 argcount = strlen(argstring);
1518 //              eDebug("have %d args('%s')", argcount, argstring);
1519         }
1520         if (convertFunc)
1521         {
1522                 if (!PyCallable_Check(convertFunc))
1523                 {
1524                         PyErr_SetString(PyExc_StandardError,
1525                                 "convertFunc must be callable");
1526                         eDebug("convertFunc is not callable");
1527                         return NULL;
1528                 }
1529                 convertFuncArgs = PyTuple_New(argcount);
1530         }
1531
1532         PyObject *nowTime = strchr(argstring, 'C') ?
1533                 PyLong_FromLong(time(0)+eDVBLocalTimeHandler::getInstance()->difference()) :
1534                 NULL;
1535
1536         bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1537
1538         // create dest list
1539         PyObject *dest_list=PyList_New(0);
1540         while(listSize > listIt)
1541         {
1542                 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1543                 if (PyTuple_Check(item))
1544                 {
1545                         bool service_changed=false;
1546                         int type=0;
1547                         long event_id=-1;
1548                         time_t stime=-1;
1549                         int minutes=0;
1550                         int tupleSize=PyTuple_Size(item);
1551                         int tupleIt=0;
1552                         PyObject *service=NULL;
1553                         while(tupleSize > tupleIt)  // parse query args
1554                         {
1555                                 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1556                                 switch(tupleIt++)
1557                                 {
1558                                         case 0:
1559                                         {
1560                                                 if (!PyString_Check(entry))
1561                                                 {
1562                                                         eDebug("tuple entry 0 is no a string");
1563                                                         goto skip_entry;
1564                                                 }
1565                                                 service = entry;
1566                                                 break;
1567                                         }
1568                                         case 1:
1569                                                 type=PyInt_AsLong(entry);
1570                                                 if (type < -1 || type > 2)
1571                                                 {
1572                                                         eDebug("unknown type %d", type);
1573                                                         goto skip_entry;
1574                                                 }
1575                                                 break;
1576                                         case 2:
1577                                                 event_id=stime=PyInt_AsLong(entry);
1578                                                 break;
1579                                         case 3:
1580                                                 minutes=PyInt_AsLong(entry);
1581                                                 break;
1582                                         default:
1583                                                 eDebug("unneeded extra argument");
1584                                                 break;
1585                                 }
1586                         }
1587                         eServiceReference ref(PyString_AS_STRING(service));
1588                         if (ref.type != eServiceReference::idDVB)
1589                         {
1590                                 eDebug("service reference for epg query is not valid");
1591                                 continue;
1592                         }
1593
1594                         // redirect subservice querys to parent service
1595                         eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1596                         if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1597                         {
1598                                 eServiceCenterPtr service_center;
1599                                 if (!eServiceCenter::getPrivInstance(service_center))
1600                                 {
1601                                         dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1602                                         dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1603                                         dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1604                                         dvb_ref.setParentServiceID(eServiceID(0));
1605                                         dvb_ref.name="";
1606                                         service = PyString_FromString(dvb_ref.toString().c_str());
1607                                         service_changed = true;
1608                                 }
1609                         }
1610
1611                         PyObject *service_name=NULL;
1612                         if (must_get_service_name)
1613                         {
1614                                 ePtr<iStaticServiceInformation> sptr;
1615                                 eServiceCenterPtr service_center;
1616                                 eServiceCenter::getPrivInstance(service_center);
1617                                 if (service_center)
1618                                 {
1619                                         service_center->info(ref, sptr);
1620                                         if (sptr)
1621                                         {
1622                                                 std::string name;
1623                                                 sptr->getName(ref, name);
1624                                                 if (name.length())
1625                                                         service_name = PyString_FromString(name.c_str());
1626                                         }
1627                                 }
1628                                 if (!service_name)
1629                                         service_name = PyString_FromString("<n/a>");
1630                         }
1631                         if (minutes)
1632                         {
1633                                 Lock();
1634                                 if (!startTimeQuery(ref, stime, minutes))
1635                                 {
1636                                         ePtr<eServiceEvent> ptr;
1637                                         while (!getNextTimeEntry(ptr))
1638                                         {
1639                                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1640                                                 if (ret)
1641                                                         return ret;
1642                                         }
1643                                 }
1644                                 Unlock();
1645                         }
1646                         else
1647                         {
1648                                 ePtr<eServiceEvent> ptr;
1649                                 if (stime)
1650                                 {
1651                                         if (type == 2)
1652                                                 lookupEventId(ref, event_id, ptr);
1653                                         else
1654                                                 lookupEventTime(ref, stime, ptr, type);
1655                                 }
1656                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1657                                 if (ret)
1658                                         return ret;
1659                         }
1660                         if (service_changed)
1661                                 Py_DECREF(service);
1662                         if (service_name)
1663                                 Py_DECREF(service_name);
1664                 }
1665 skip_entry:
1666                 ;
1667         }
1668         if (convertFuncArgs)
1669                 Py_DECREF(convertFuncArgs);
1670         if (nowTime)
1671                 Py_DECREF(nowTime);
1672         return dest_list;
1673 }
1674
1675 void fillTuple2(PyObject *tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, PyObject *service_name, PyObject *service_reference)
1676 {
1677         PyObject *tmp=NULL;
1678         int pos=0;
1679         while(pos < argcount)
1680         {
1681                 bool inc_refcount=false;
1682                 switch(argstring[pos])
1683                 {
1684                         case '0': // PyLong 0
1685                                 tmp = PyLong_FromLong(0);
1686                                 break;
1687                         case 'I': // Event Id
1688                                 tmp = PyLong_FromLong(evData->getEventID());
1689                                 break;
1690                         case 'B': // Event Begin Time
1691                                 if (ptr)
1692                                         tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1693                                 else
1694                                         tmp = PyLong_FromLong(evData->getStartTime());
1695                                 break;
1696                         case 'D': // Event Duration
1697                                 if (ptr)
1698                                         tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1699                                 else
1700                                         tmp = PyLong_FromLong(evData->getDuration());
1701                                 break;
1702                         case 'T': // Event Title
1703                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1704                                 break;
1705                         case 'S': // Event Short Description
1706                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1707                                 break;
1708                         case 'E': // Event Extended Description
1709                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1710                                 break;
1711                         case 'R': // service reference string
1712                                 tmp = service_reference;
1713                                 inc_refcount = true;
1714                                 break;
1715                         case 'N': // service name
1716                                 tmp = service_name;
1717                                 inc_refcount = true;
1718                                 break;
1719                 }
1720                 if (!tmp)
1721                 {
1722                         tmp = Py_None;
1723                         inc_refcount = true;
1724                 }
1725                 if (inc_refcount)
1726                         Py_INCREF(tmp);
1727                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1728         }
1729 }
1730
1731 // here we get a python tuple
1732 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1733 //   I = Event Id
1734 //   B = Event Begin Time
1735 //   D = Event Duration
1736 //   T = Event Title
1737 //   S = Event Short Description
1738 //   E = Event Extended Description
1739 //   R = Service Reference
1740 //   N = Service Name
1741 //  the second tuple entry is the MAX matches value
1742 //  the third tuple entry is the type of query
1743 //     0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1744 //     1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1745 //     2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1746 //  when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1747 //   the fourth is the servicereference string
1748 //   the fifth is the eventid
1749 //  when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1750 //   the fourth is the search text
1751 //   the fifth is
1752 //     0 = case sensitive (CASE_CHECK)
1753 //     1 = case insensitive (NO_CASECHECK)
1754
1755 PyObject *eEPGCache::search(PyObject *arg)
1756 {
1757         PyObject *ret = 0;
1758         int descridx = -1;
1759         __u32 descr[512];
1760         int eventid = -1;
1761         const char *argstring=0;
1762         char *refstr=0;
1763         int argcount=0;
1764         int querytype=-1;
1765         bool needServiceEvent=false;
1766         int maxmatches=0;
1767
1768         if (PyTuple_Check(arg))
1769         {
1770                 int tuplesize=PyTuple_Size(arg);
1771                 if (tuplesize > 0)
1772                 {
1773                         PyObject *obj = PyTuple_GET_ITEM(arg,0);
1774                         if (PyString_Check(obj))
1775                         {
1776                                 argcount = PyString_GET_SIZE(obj);
1777                                 argstring = PyString_AS_STRING(obj);
1778                                 for (int i=0; i < argcount; ++i)
1779                                         switch(argstring[i])
1780                                         {
1781                                         case 'S':
1782                                         case 'E':
1783                                         case 'T':
1784                                                 needServiceEvent=true;
1785                                         default:
1786                                                 break;
1787                                         }
1788                         }
1789                         else
1790                         {
1791                                 PyErr_SetString(PyExc_StandardError,
1792                                         "type error");
1793                                 eDebug("tuple arg 0 is not a string");
1794                                 return NULL;
1795                         }
1796                 }
1797                 if (tuplesize > 1)
1798                         maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1799                 if (tuplesize > 2)
1800                 {
1801                         querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1802                         if (tuplesize > 4 && querytype == 0)
1803                         {
1804                                 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1805                                 if (PyString_Check(obj))
1806                                 {
1807                                         refstr = PyString_AS_STRING(obj);
1808                                         eServiceReferenceDVB ref(refstr);
1809                                         if (ref.valid())
1810                                         {
1811                                                 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1812                                                 singleLock s(cache_lock);
1813                                                 const eventData *evData = 0;
1814                                                 lookupEventId(ref, eventid, evData);
1815                                                 if (evData)
1816                                                 {
1817                                                         __u8 *data = evData->EITdata;
1818                                                         int tmp = evData->ByteSize-12;
1819                                                         __u32 *p = (__u32*)(data+12);
1820                                                                 // search short and extended event descriptors
1821                                                         while(tmp>0)
1822                                                         {
1823                                                                 __u32 crc = *p++;
1824                                                                 descriptorMap::iterator it =
1825                                                                         eventData::descriptors.find(crc);
1826                                                                 if (it != eventData::descriptors.end())
1827                                                                 {
1828                                                                         __u8 *descr_data = it->second.second;
1829                                                                         switch(descr_data[0])
1830                                                                         {
1831                                                                         case 0x4D ... 0x4E:
1832                                                                                 descr[++descridx]=crc;
1833                                                                         default:
1834                                                                                 break;
1835                                                                         }
1836                                                                 }
1837                                                                 tmp-=4;
1838                                                         }
1839                                                 }
1840                                                 if (descridx<0)
1841                                                         eDebug("event not found");
1842                                         }
1843                                         else
1844                                         {
1845                                                 PyErr_SetString(PyExc_StandardError,
1846                                                         "type error");
1847                                                 eDebug("tuple arg 4 is not a valid service reference string");
1848                                                 return NULL;
1849                                         }
1850                                 }
1851                                 else
1852                                 {
1853                                         PyErr_SetString(PyExc_StandardError,
1854                                         "type error");
1855                                         eDebug("tuple arg 4 is not a string");
1856                                         return NULL;
1857                                 }
1858                         }
1859                         else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
1860                         {
1861                                 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1862                                 if (PyString_Check(obj))
1863                                 {
1864                                         int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1865                                         const char *str = PyString_AS_STRING(obj);
1866                                         int textlen = PyString_GET_SIZE(obj);
1867                                         if (querytype == 1)
1868                                                 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
1869                                         else
1870                                                 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
1871                                         singleLock s(cache_lock);
1872                                         for (descriptorMap::iterator it(eventData::descriptors.begin());
1873                                                 it != eventData::descriptors.end() && descridx < 511; ++it)
1874                                         {
1875                                                 __u8 *data = it->second.second;
1876                                                 if ( data[0] == 0x4D ) // short event descriptor
1877                                                 {
1878                                                         int title_len = data[5];
1879                                                         if ( querytype == 1 )
1880                                                         {
1881                                                                 if (title_len > textlen)
1882                                                                         continue;
1883                                                                 else if (title_len < textlen)
1884                                                                         continue;
1885                                                                 if ( casetype )
1886                                                                 {
1887                                                                         if ( !strncasecmp((const char*)data+6, str, title_len) )
1888                                                                         {
1889 //                                                                              std::string s((const char*)data+6, title_len);
1890 //                                                                              eDebug("match1 %s %s", str, s.c_str() );
1891                                                                                 descr[++descridx] = it->first;
1892                                                                         }
1893                                                                 }
1894                                                                 else if ( !strncmp((const char*)data+6, str, title_len) )
1895                                                                 {
1896 //                                                                      std::string s((const char*)data+6, title_len);
1897 //                                                                      eDebug("match2 %s %s", str, s.c_str() );
1898                                                                         descr[++descridx] = it->first;
1899                                                                 }
1900                                                         }
1901                                                         else
1902                                                         {
1903                                                                 int idx=0;
1904                                                                 while((title_len-idx) >= textlen)
1905                                                                 {
1906                                                                         if (casetype)
1907                                                                         {
1908                                                                                 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
1909                                                                                 {
1910                                                                                         descr[++descridx] = it->first;
1911 //                                                                                      std::string s((const char*)data+6, title_len);
1912 //                                                                                      eDebug("match 3 %s %s", str, s.c_str() );
1913                                                                                         break;
1914                                                                                 }
1915                                                                                 else if (!strncmp((const char*)data+6+idx, str, textlen) )
1916                                                                                 {
1917                                                                                         descr[++descridx] = it->first;
1918 //                                                                                      std::string s((const char*)data+6, title_len);
1919 //                                                                                      eDebug("match 4 %s %s", str, s.c_str() );
1920                                                                                         break;
1921                                                                                 }
1922                                                                         }
1923                                                                         ++idx;
1924                                                                 }
1925                                                         }
1926                                                 }
1927                                         }
1928                                 }
1929                                 else
1930                                 {
1931                                         PyErr_SetString(PyExc_StandardError,
1932                                                 "type error");
1933                                         eDebug("tuple arg 4 is not a string");
1934                                         return NULL;
1935                                 }
1936                         }
1937                         else
1938                         {
1939                                 PyErr_SetString(PyExc_StandardError,
1940                                         "type error");
1941                                 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
1942                                 return NULL;
1943                         }
1944                 }
1945                 else
1946                 {
1947                         PyErr_SetString(PyExc_StandardError,
1948                                 "type error");
1949                         eDebug("not enough args in tuple");
1950                         return NULL;
1951                 }
1952         }
1953         else
1954         {
1955                 PyErr_SetString(PyExc_StandardError,
1956                         "type error");
1957                 eDebug("arg 0 is not a tuple");
1958                 return NULL;
1959         }
1960
1961         if (descridx > -1)
1962         {
1963                 int maxcount=maxmatches;
1964                 eServiceReferenceDVB ref(refstr?refstr:"");
1965                 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
1966                 // in this case we start searching with the base service
1967                 bool first = ref.valid() ? true : false;
1968                 singleLock s(cache_lock);
1969                 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
1970                 while(cit != eventDB.end() && maxcount)
1971                 {
1972                         if ( ref.valid() && !first && cit->first == ref )
1973                         {
1974                                 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
1975                                 ++cit;
1976                                 continue;
1977                         }
1978                         PyObject *service_name=0;
1979                         PyObject *service_reference=0;
1980                         timeMap &evmap = cit->second.second;
1981                         // check all events
1982                         for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
1983                         {
1984                                 if (evit->second->getEventID() == eventid)
1985                                         continue;
1986                                 __u8 *data = evit->second->EITdata;
1987                                 int tmp = evit->second->ByteSize-12;
1988                                 __u32 *p = (__u32*)(data+12);
1989                                 // check if any of our descriptor used by this event
1990                                 int cnt=-1;
1991                                 while(tmp>0)
1992                                 {
1993                                         __u32 crc32 = *p++;
1994                                         for ( int i=0; i <= descridx; ++i)
1995                                         {
1996                                                 if (descr[i] == crc32)  // found...
1997                                                         ++cnt;
1998                                         }
1999                                         tmp-=4;
2000                                 }
2001                                 if ( (querytype == 0 && cnt == descridx) ||
2002                                          ((querytype == 1 || querytype == 2) && cnt != -1) )
2003                                 {
2004                                         const uniqueEPGKey &service = cit->first;
2005                                         eServiceReference ref =
2006                                                 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2007                                         if (ref.valid())
2008                                         {
2009                                         // create servive event
2010                                                 ePtr<eServiceEvent> ptr;
2011                                                 if (needServiceEvent)
2012                                                 {
2013                                                         lookupEventId(ref, evit->first, ptr);
2014                                                         if (!ptr)
2015                                                                 eDebug("event not found !!!!!!!!!!!");
2016                                                 }
2017                                         // create service name
2018                                                 if (!service_name && strchr(argstring,'N'))
2019                                                 {
2020                                                         ePtr<iStaticServiceInformation> sptr;
2021                                                         eServiceCenterPtr service_center;
2022                                                         eServiceCenter::getPrivInstance(service_center);
2023                                                         if (service_center)
2024                                                         {
2025                                                                 service_center->info(ref, sptr);
2026                                                                 if (sptr)
2027                                                                 {
2028                                                                         std::string name;
2029                                                                         sptr->getName(ref, name);
2030                                                                         if (name.length())
2031                                                                                 service_name = PyString_FromString(name.c_str());
2032                                                                 }
2033                                                         }
2034                                                         if (!service_name)
2035                                                                 service_name = PyString_FromString("<n/a>");
2036                                                 }
2037                                         // create servicereference string
2038                                                 if (!service_reference && strchr(argstring,'R'))
2039                                                         service_reference = PyString_FromString(ref.toString().c_str());
2040                                         // create list
2041                                                 if (!ret)
2042                                                         ret = PyList_New(0);
2043                                         // create tuple
2044                                                 PyObject *tuple = PyTuple_New(argcount);
2045                                         // fill tuple
2046                                                 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2047                                                 PyList_Append(ret, tuple);
2048                                                 Py_DECREF(tuple);
2049                                                 --maxcount;
2050                                         }
2051                                 }
2052                         }
2053                         if (service_name)
2054                                 Py_DECREF(service_name);
2055                         if (service_reference)
2056                                 Py_DECREF(service_reference);
2057                         if (first)
2058                         {
2059                                 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2060                                 first=false;
2061                                 cit=eventDB.begin();
2062                         }
2063                         else
2064                                 ++cit;
2065                 }
2066         }
2067
2068         if (!ret)
2069         {
2070                 Py_INCREF(Py_None);
2071                 ret=Py_None;
2072         }
2073
2074         return ret;
2075 }
2076
2077 #ifdef ENABLE_PRIVATE_EPG
2078 #include <dvbsi++/descriptor_tag.h>
2079 #include <dvbsi++/unknown_descriptor.h>
2080 #include <dvbsi++/private_data_specifier_descriptor.h>
2081
2082 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2083 {
2084         ePtr<eTable<ProgramMapSection> > ptr;
2085         if (!pmthandler->getPMT(ptr) && ptr)
2086         {
2087                 std::vector<ProgramMapSection*>::const_iterator i;
2088                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2089                 {
2090                         const ProgramMapSection &pmt = **i;
2091
2092                         ElementaryStreamInfoConstIterator es;
2093                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2094                         {
2095                                 int tmp=0;
2096                                 switch ((*es)->getType())
2097                                 {
2098                                 case 0x05: // private
2099                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2100                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2101                                         {
2102                                                 switch ((*desc)->getTag())
2103                                                 {
2104                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2105                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2106                                                                         tmp |= 1;
2107                                                                 break;
2108                                                         case 0x90:
2109                                                         {
2110                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2111                                                                 int descr_len = descr->getLength();
2112                                                                 if (descr_len == 4)
2113                                                                 {
2114                                                                         uint8_t data[descr_len+2];
2115                                                                         descr->writeToBuffer(data);
2116                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2117                                                                                 tmp |= 2;
2118                                                                 }
2119                                                                 break;
2120                                                         }
2121                                                         default:
2122                                                                 break;
2123                                                 }
2124                                         }
2125                                 default:
2126                                         break;
2127                                 }
2128                                 if (tmp==3)
2129                                 {
2130                                         eServiceReferenceDVB ref;
2131                                         if (!pmthandler->getServiceReference(ref))
2132                                         {
2133                                                 int pid = (*es)->getPid();
2134                                                 messages.send(Message(Message::got_private_pid, ref, pid));
2135                                                 return;
2136                                         }
2137                                 }
2138                         }
2139                 }
2140         }
2141         else
2142                 eDebug("PMTready but no pmt!!");
2143 }
2144
2145 struct date_time
2146 {
2147         __u8 data[5];
2148         time_t tm;
2149         date_time( const date_time &a )
2150         {
2151                 memcpy(data, a.data, 5);
2152                 tm = a.tm;
2153         }
2154         date_time( const __u8 data[5])
2155         {
2156                 memcpy(this->data, data, 5);
2157                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2158         }
2159         date_time()
2160         {
2161         }
2162         const __u8& operator[](int pos) const
2163         {
2164                 return data[pos];
2165         }
2166 };
2167
2168 struct less_datetime
2169 {
2170         bool operator()( const date_time &a, const date_time &b ) const
2171         {
2172                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2173         }
2174 };
2175
2176 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
2177 {
2178         contentMap &content_time_table = content_time_tables[current_service];
2179         singleLock s(cache_lock);
2180         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2181         eventMap &evMap = eventDB[current_service].first;
2182         timeMap &tmMap = eventDB[current_service].second;
2183         int ptr=8;
2184         int content_id = data[ptr++] << 24;
2185         content_id |= data[ptr++] << 16;
2186         content_id |= data[ptr++] << 8;
2187         content_id |= data[ptr++];
2188
2189         contentTimeMap &time_event_map =
2190                 content_time_table[content_id];
2191         for ( contentTimeMap::iterator it( time_event_map.begin() );
2192                 it != time_event_map.end(); ++it )
2193         {
2194                 eventMap::iterator evIt( evMap.find(it->second.second) );
2195                 if ( evIt != evMap.end() )
2196                 {
2197                         delete evIt->second;
2198                         evMap.erase(evIt);
2199                 }
2200                 tmMap.erase(it->second.first);
2201         }
2202         time_event_map.clear();
2203
2204         __u8 duration[3];
2205         memcpy(duration, data+ptr, 3);
2206         ptr+=3;
2207         int duration_sec =
2208                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2209
2210         const __u8 *descriptors[65];
2211         const __u8 **pdescr = descriptors;
2212
2213         int descriptors_length = (data[ptr++]&0x0F) << 8;
2214         descriptors_length |= data[ptr++];
2215         while ( descriptors_length > 0 )
2216         {
2217                 int descr_type = data[ptr];
2218                 int descr_len = data[ptr+1];
2219                 descriptors_length -= (descr_len+2);
2220                 if ( descr_type == 0xf2 )
2221                 {
2222                         ptr+=2;
2223                         int tsid = data[ptr++] << 8;
2224                         tsid |= data[ptr++];
2225                         int onid = data[ptr++] << 8;
2226                         onid |= data[ptr++];
2227                         int sid = data[ptr++] << 8;
2228                         sid |= data[ptr++];
2229
2230 // WORKAROUND for wrong transmitted epg data
2231                         if ( onid == 0x85 && tsid == 0x11 && sid == 0xd3 )  // premiere sends wrong tsid here
2232                                 tsid = 0x1;
2233                         else if ( onid == 0x85 && tsid == 0x3 && sid == 0xf5 ) // premiere sends wrong sid here
2234                                 sid = 0xdc;
2235 ////////////////////////////////////////////
2236                                 
2237                         uniqueEPGKey service( sid, onid, tsid );
2238                         descr_len -= 6;
2239                         while( descr_len > 0 )
2240                         {
2241                                 __u8 datetime[5];
2242                                 datetime[0] = data[ptr++];
2243                                 datetime[1] = data[ptr++];
2244                                 int tmp_len = data[ptr++];
2245                                 descr_len -= 3;
2246                                 while( tmp_len > 0 )
2247                                 {
2248                                         memcpy(datetime+2, data+ptr, 3);
2249                                         ptr+=3;
2250                                         descr_len -= 3;
2251                                         tmp_len -= 3;
2252                                         start_times[datetime].push_back(service);
2253                                 }
2254                         }
2255                 }
2256                 else
2257                 {
2258                         *pdescr++=data+ptr;
2259                         ptr += 2;
2260                         ptr += descr_len;
2261                 }
2262         }
2263         __u8 event[4098];
2264         eit_event_struct *ev_struct = (eit_event_struct*) event;
2265         ev_struct->running_status = 0;
2266         ev_struct->free_CA_mode = 1;
2267         memcpy(event+7, duration, 3);
2268         ptr = 12;
2269         const __u8 **d=descriptors;
2270         while ( d < pdescr )
2271         {
2272                 memcpy(event+ptr, *d, ((*d)[1])+2);
2273                 ptr+=(*d++)[1];
2274                 ptr+=2;
2275         }
2276         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2277         {
2278                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2279                 if ( (it->first.tm + duration_sec) < now )
2280                         continue;
2281                 memcpy(event+2, it->first.data, 5);
2282                 int bptr = ptr;
2283                 int cnt=0;
2284                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2285                 {
2286                         event[bptr++] = 0x4A;
2287                         __u8 *len = event+(bptr++);
2288                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
2289                         event[bptr++] = (i->tsid & 0xFF);
2290                         event[bptr++] = (i->onid & 0xFF00) >> 8;
2291                         event[bptr++] = (i->onid & 0xFF);
2292                         event[bptr++] = (i->sid & 0xFF00) >> 8;
2293                         event[bptr++] = (i->sid & 0xFF);
2294                         event[bptr++] = 0xB0;
2295                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2296                         *len = ((event+bptr) - len)-1;
2297                 }
2298                 int llen = bptr - 12;
2299                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2300                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2301
2302                 time_t stime = it->first.tm;
2303                 while( tmMap.find(stime) != tmMap.end() )
2304                         ++stime;
2305                 event[6] += (stime - it->first.tm);
2306                 __u16 event_id = 0;
2307                 while( evMap.find(event_id) != evMap.end() )
2308                         ++event_id;
2309                 event[0] = (event_id & 0xFF00) >> 8;
2310                 event[1] = (event_id & 0xFF);
2311                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2312                 eventData *d = new eventData( ev_struct, bptr, eEPGCache::SCHEDULE );
2313                 evMap[event_id] = d;
2314                 tmMap[stime] = d;
2315         }
2316 }
2317
2318 void eEPGCache::channel_data::startPrivateReader()
2319 {
2320         eDVBSectionFilterMask mask;
2321         memset(&mask, 0, sizeof(mask));
2322         mask.pid = m_PrivatePid;
2323         mask.flags = eDVBSectionFilterMask::rfCRC;
2324         mask.data[0] = 0xA0;
2325         mask.mask[0] = 0xFF;
2326         eDebug("start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2327         if (m_PrevVersion != -1)
2328         {
2329                 mask.data[3] = m_PrevVersion << 1;
2330                 mask.mask[3] = 0x3E;
2331                 mask.mode[3] = 0x3E;
2332         }
2333         seenPrivateSections.clear();
2334         m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2335         m_PrivateReader->start(mask);
2336 }
2337
2338 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2339 {
2340         if (!data)
2341                 eDebug("get Null pointer from section reader !!");
2342         else
2343         {
2344                 if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2345                 {
2346 #ifdef NEED_DEMUX_WORKAROUND
2347                         int version = data[5];
2348                         version = ((version & 0x3E) >> 1);
2349                         can_delete = 0;
2350                         if ( m_PrevVersion != version )
2351                         {
2352                                 cache->privateSectionRead(m_PrivateService, data);
2353                                 seenPrivateSections.insert(data[6]);
2354                         }
2355                         else
2356                                 eDebug("ignore");
2357 #else
2358                         can_delete = 0;
2359                         cache->privateSectionRead(m_PrivateService, data);
2360                         seenPrivateSections.insert(data[6]);
2361 #endif
2362                 }
2363                 if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2364                 {
2365                         eDebug("[EPGC] private finished");
2366                         if (!isRunning)
2367                                 can_delete = 1;
2368                         m_PrevVersion = (data[5] & 0x3E) >> 1;
2369                         m_PrivateReader->stop();
2370                         startPrivateTimer.start(UPDATE_INTERVAL, 1);
2371                 }
2372         }
2373 }
2374
2375 #endif // ENABLE_PRIVATE_EPG