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