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