47ebb355ace29307014238cdcc58ed7b7b06dfe3
[enigma2.git] / lib / dvb / epgcache.cpp
1 #include <lib/dvb/epgcache.h>
2 #include <lib/dvb/dvb.h>
3
4 #undef EPG_DEBUG  
5
6 #ifdef EPG_DEBUG
7 #include <lib/service/event.h>
8 #endif
9
10 #include <time.h>
11 #include <unistd.h>  // for usleep
12 #include <sys/vfs.h> // for statfs
13 // #include <libmd5sum.h>
14 #include <lib/base/eerror.h>
15 #include <lib/dvb/pmt.h>
16 #include <lib/dvb/db.h>
17 #include <lib/python/python.h>
18
19 int eventData::CacheSize=0;
20 descriptorMap eventData::descriptors;
21 __u8 eventData::data[4108];
22 extern const uint32_t crc32_table[256];
23
24 const eServiceReference &handleGroup(const eServiceReference &ref)
25 {
26         if (ref.flags & eServiceReference::isGroup)
27         {
28                 ePtr<eDVBResourceManager> res;
29                 if (!eDVBResourceManager::getInstance(res))
30                 {
31                         ePtr<iDVBChannelList> db;
32                         if (!res->getChannelList(db))
33                         {
34                                 eBouquet *bouquet=0;
35                                 if (!db->getBouquet(ref, bouquet))
36                                 {
37                                         std::list<eServiceReference>::iterator it(bouquet->m_services.begin());
38                                         if (it != bouquet->m_services.end())
39                                                 return *it;
40                                 }
41                         }
42                 }
43         }
44         return ref;
45 }
46
47
48 eventData::eventData(const eit_event_struct* e, int size, int type)
49         :ByteSize(size&0xFF), type(type&0xFF)
50 {
51         if (!e)
52                 return;
53
54         __u32 descr[65];
55         __u32 *pdescr=descr;
56
57         __u8 *data = (__u8*)e;
58         int ptr=10;
59         int descriptors_length = (data[ptr++]&0x0F) << 8;
60         descriptors_length |= data[ptr++];
61         while ( descriptors_length > 0 )
62         {
63                 __u8 *descr = data+ptr;
64                 int descr_len = descr[1]+2;
65
66                 __u32 crc = 0;
67                 int cnt=0;
68                 while(cnt++ < descr_len)
69                         crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ data[ptr++]) & 0xFF];
70
71                 descriptorMap::iterator it =
72                         descriptors.find(crc);
73                 if ( it == descriptors.end() )
74                 {
75                         CacheSize+=descr_len;
76                         __u8 *d = new __u8[descr_len];
77                         memcpy(d, descr, descr_len);
78                         descriptors[crc] = descriptorPair(1, d);
79                 }
80                 else
81                         ++it->second.first;
82
83                 *pdescr++=crc;
84                 descriptors_length -= descr_len;
85         }
86         ASSERT(pdescr <= &descr[65]);
87         ByteSize = 12+((pdescr-descr)*4);
88         EITdata = new __u8[ByteSize];
89         CacheSize+=ByteSize;
90         memcpy(EITdata, (__u8*) e, 12);
91         memcpy(EITdata+12, descr, ByteSize-12);
92 }
93
94 const eit_event_struct* eventData::get() const
95 {
96         int pos = 12;
97         int tmp = ByteSize-12;
98         memcpy(data, EITdata, 12);
99         __u32 *p = (__u32*)(EITdata+12);
100         while(tmp>0)
101         {
102                 descriptorMap::iterator it =
103                         descriptors.find(*p++);
104                 if ( it != descriptors.end() )
105                 {
106                         int b = it->second.second[1]+2;
107                         memcpy(data+pos, it->second.second, b );
108                         pos += b;
109                 }
110                 tmp-=4;
111         }
112         ASSERT(pos <= 4108);
113
114         return (const eit_event_struct*)data;
115 }
116
117 eventData::~eventData()
118 {
119         if ( ByteSize )
120         {
121                 CacheSize-=ByteSize;
122                 ByteSize-=12;
123                 __u32 *d = (__u32*)(EITdata+12);
124                 while(ByteSize)
125                 {
126                         descriptorMap::iterator it =
127                                 descriptors.find(*d++);
128                         if ( it != descriptors.end() )
129                         {
130                                 descriptorPair &p = it->second;
131                                 if (!--p.first) // no more used descriptor
132                                 {
133                                         CacheSize -= it->second.second[1];
134                                         delete [] it->second.second;    // free descriptor memory
135                                         descriptors.erase(it);  // remove entry from descriptor map
136                                 }
137                         }
138                         else
139                                 eFatal("[descriptor not found in descriptor cache!!!!!!");
140                         ByteSize-=4;
141                 }
142                 delete [] EITdata;
143         }
144 }
145
146 void eventData::load(FILE *f)
147 {
148         int size=0;
149         int id=0;
150         __u8 header[2];
151         descriptorPair p;
152         fread(&size, sizeof(int), 1, f);
153         while(size)
154         {
155                 fread(&id, sizeof(__u32), 1, f);
156                 fread(&p.first, sizeof(int), 1, f);
157                 fread(header, 2, 1, f);
158                 int bytes = header[1]+2;
159                 p.second = new __u8[bytes];
160                 p.second[0] = header[0];
161                 p.second[1] = header[1];
162                 fread(p.second+2, bytes-2, 1, f);
163                 descriptors[id]=p;
164                 --size;
165                 CacheSize+=bytes;
166         }
167 }
168
169 void eventData::save(FILE *f)
170 {
171         int size=descriptors.size();
172         descriptorMap::iterator it(descriptors.begin());
173         fwrite(&size, sizeof(int), 1, f);
174         while(size)
175         {
176                 fwrite(&it->first, sizeof(__u32), 1, f);
177                 fwrite(&it->second.first, sizeof(int), 1, f);
178                 fwrite(it->second.second, it->second.second[1]+2, 1, f);
179                 ++it;
180                 --size;
181         }
182 }
183
184 eEPGCache* eEPGCache::instance;
185 pthread_mutex_t eEPGCache::cache_lock=
186         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
187 pthread_mutex_t eEPGCache::channel_map_lock=
188         PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
189
190 DEFINE_REF(eEPGCache)
191
192 eEPGCache::eEPGCache()
193         :messages(this,1), cleanTimer(this)//, paused(0)
194 {
195         eDebug("[EPGC] Initialized EPGCache");
196
197         CONNECT(messages.recv_msg, eEPGCache::gotMessage);
198         CONNECT(eDVBLocalTimeHandler::getInstance()->m_timeUpdated, eEPGCache::timeUpdated);
199         CONNECT(cleanTimer.timeout, eEPGCache::cleanLoop);
200
201         ePtr<eDVBResourceManager> res_mgr;
202         eDVBResourceManager::getInstance(res_mgr);
203         if (!res_mgr)
204                 eDebug("[eEPGCache] no resource manager !!!!!!!");
205         else
206                 res_mgr->connectChannelAdded(slot(*this,&eEPGCache::DVBChannelAdded), m_chanAddedConn);
207         instance=this;
208 }
209
210 void eEPGCache::timeUpdated()
211 {
212         if (!sync())
213         {
214                 eDebug("[EPGC] time updated.. start EPG Mainloop");
215                 run();
216         } else
217                 messages.send(Message(Message::timeChanged));
218 }
219
220 void eEPGCache::DVBChannelAdded(eDVBChannel *chan)
221 {
222         if ( chan )
223         {
224 //              eDebug("[eEPGCache] add channel %p", chan);
225                 channel_data *data = new channel_data(this);
226                 data->channel = chan;
227                 data->prevChannelState = -1;
228 #ifdef ENABLE_PRIVATE_EPG
229                 data->m_PrivatePid = -1;
230 #endif
231                 singleLock s(channel_map_lock);
232                 m_knownChannels.insert( std::pair<iDVBChannel*, channel_data* >(chan, data) );
233                 chan->connectStateChange(slot(*this, &eEPGCache::DVBChannelStateChanged), data->m_stateChangedConn);
234         }
235 }
236
237 void eEPGCache::DVBChannelRunning(iDVBChannel *chan)
238 {
239         channelMapIterator it =
240                 m_knownChannels.find(chan);
241         if ( it == m_knownChannels.end() )
242                 eDebug("[eEPGCache] will start non existing channel %p !!!", chan);
243         else
244         {
245                 channel_data &data = *it->second;
246                 ePtr<eDVBResourceManager> res_mgr;
247                 if ( eDVBResourceManager::getInstance( res_mgr ) )
248                         eDebug("[eEPGCache] no res manager!!");
249                 else
250                 {
251                         ePtr<iDVBDemux> demux;
252                         if ( data.channel->getDemux(demux, 0) )
253                         {
254                                 eDebug("[eEPGCache] no demux!!");
255                                 return;
256                         }
257                         else
258                         {
259                                 RESULT res = demux->createSectionReader( this, data.m_NowNextReader );
260                                 if ( res )
261                                 {
262                                         eDebug("[eEPGCache] couldnt initialize nownext reader!!");
263                                         return;
264                                 }
265
266                                 res = demux->createSectionReader( this, data.m_ScheduleReader );
267                                 if ( res )
268                                 {
269                                         eDebug("[eEPGCache] couldnt initialize schedule reader!!");
270                                         return;
271                                 }
272
273                                 res = demux->createSectionReader( this, data.m_ScheduleOtherReader );
274                                 if ( res )
275                                 {
276                                         eDebug("[eEPGCache] couldnt initialize schedule other reader!!");
277                                         return;
278                                 }
279 #ifdef ENABLE_PRIVATE_EPG
280                                 res = demux->createSectionReader( this, data.m_PrivateReader );
281                                 if ( res )
282                                 {
283                                         eDebug("[eEPGCache] couldnt initialize private reader!!");
284                                         return;
285                                 }
286 #endif
287 #ifdef ENABLE_MHW_EPG
288                                 res = demux->createSectionReader( this, data.m_MHWReader );
289                                 if ( res )
290                                 {
291                                         eDebug("[eEPGCache] couldnt initialize mhw reader!!");
292                                         return;
293                                 }
294                                 res = demux->createSectionReader( this, data.m_MHWReader2 );
295                                 if ( res )
296                                 {
297                                         eDebug("[eEPGCache] couldnt initialize mhw reader!!");
298                                         return;
299                                 }
300 #endif
301                                 messages.send(Message(Message::startChannel, chan));
302                                 // -> gotMessage -> changedService
303                         }
304                 }
305         }
306 }
307
308 void eEPGCache::DVBChannelStateChanged(iDVBChannel *chan)
309 {
310         channelMapIterator it =
311                 m_knownChannels.find(chan);
312         if ( it != m_knownChannels.end() )
313         {
314                 int state=0;
315                 chan->getState(state);
316                 if ( it->second->prevChannelState != state )
317                 {
318                         switch (state)
319                         {
320                                 case iDVBChannel::state_ok:
321                                 {
322                                         eDebug("[eEPGCache] channel %p running", chan);
323                                         DVBChannelRunning(chan);
324                                         break;
325                                 }
326                                 case iDVBChannel::state_release:
327                                 {
328                                         eDebug("[eEPGCache] remove channel %p", chan);
329                                         messages.send(Message(Message::leaveChannel, chan));
330                                         pthread_mutex_lock(&it->second->channel_active);
331                                         singleLock s(channel_map_lock);
332                                         m_knownChannels.erase(it);
333                                         pthread_mutex_unlock(&it->second->channel_active);
334                                         delete it->second;
335                                         it->second=0;
336                                         // -> gotMessage -> abortEPG
337                                         break;
338                                 }
339                                 default: // ignore all other events
340                                         return;
341                         }
342                         if (it->second)
343                                 it->second->prevChannelState = state;
344                 }
345         }
346 }
347
348 void eEPGCache::FixOverlapping(std::pair<eventMap,timeMap> &servicemap, time_t TM, int duration, const timeMap::iterator &tm_it, const uniqueEPGKey &service)
349 {
350         timeMap::iterator tmp = tm_it;
351         while ((tmp->first+tmp->second->getDuration()-300) > TM)
352         {
353                 if(tmp->first != TM 
354 #ifdef ENABLE_PRIVATE_EPG
355                         && tmp->second->type != PRIVATE 
356 #endif
357 #ifdef ENABLE_MHW
358                         && tmp->second->type != MHW
359 #endif
360                         )
361                 {
362                         __u16 event_id = tmp->second->getEventID();
363                         servicemap.first.erase(event_id);
364 #ifdef EPG_DEBUG
365                         Event evt((uint8_t*)tmp->second->get());
366                         eServiceEvent event;
367                         event.parseFrom(&evt, service.sid<<16|service.onid);
368                         eDebug("(1)erase no more used event %04x %d\n%s %s\n%s",
369                                 service.sid, event_id,
370                                 event.getBeginTimeString().c_str(),
371                                 event.getEventName().c_str(),
372                                 event.getExtendedDescription().c_str());
373 #endif
374                         delete tmp->second;
375                         if (tmp == servicemap.second.begin())
376                         {
377                                 servicemap.second.erase(tmp);
378                                 break;
379                         }
380                         else
381                                 servicemap.second.erase(tmp--);
382                 }
383                 else
384                 {
385                         if (tmp == servicemap.second.begin())
386                                 break;
387                         --tmp;
388                 }
389         }
390
391         tmp = tm_it;
392         while(tmp->first < (TM+duration-300))
393         {
394                 if (tmp->first != TM && tmp->second->type != PRIVATE)
395                 {
396                         __u16 event_id = tmp->second->getEventID();
397                         servicemap.first.erase(event_id);
398 #ifdef EPG_DEBUG  
399                         Event evt((uint8_t*)tmp->second->get());
400                         eServiceEvent event;
401                         event.parseFrom(&evt, service.sid<<16|service.onid);
402                         eDebug("(2)erase no more used event %04x %d\n%s %s\n%s",
403                                 service.sid, event_id,
404                                 event.getBeginTimeString().c_str(),
405                                 event.getEventName().c_str(),
406                                 event.getExtendedDescription().c_str());
407 #endif
408                         delete tmp->second;
409                         servicemap.second.erase(tmp++);
410                 }
411                 else
412                         ++tmp;
413                 if (tmp == servicemap.second.end())
414                         break;
415         }
416 }
417
418 void eEPGCache::sectionRead(const __u8 *data, int source, channel_data *channel)
419 {
420         eit_t *eit = (eit_t*) data;
421
422         int len=HILO(eit->section_length)-1;//+3-4;
423         int ptr=EIT_SIZE;
424         if ( ptr >= len )
425                 return;
426
427         // This fixed the EPG on the Multichoice irdeto systems
428         // the EIT packet is non-compliant.. their EIT packet stinks
429         if ( data[ptr-1] < 0x40 )
430                 --ptr;
431
432         uniqueEPGKey service( HILO(eit->service_id), HILO(eit->original_network_id), HILO(eit->transport_stream_id) );
433         eit_event_struct* eit_event = (eit_event_struct*) (data+ptr);
434         int eit_event_size;
435         int duration;
436
437         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);
438         time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
439
440         if ( TM != 3599 && TM > -1)
441                 channel->haveData |= source;
442
443         singleLock s(cache_lock);
444         // hier wird immer eine eventMap zurück gegeben.. entweder eine vorhandene..
445         // oder eine durch [] erzeugte
446         std::pair<eventMap,timeMap> &servicemap = eventDB[service];
447         eventMap::iterator prevEventIt = servicemap.first.end();
448         timeMap::iterator prevTimeIt = servicemap.second.end();
449
450         while (ptr<len)
451         {
452                 eit_event_size = HILO(eit_event->descriptors_loop_length)+EIT_LOOP_SIZE;
453
454                 duration = fromBCD(eit_event->duration_1)*3600+fromBCD(eit_event->duration_2)*60+fromBCD(eit_event->duration_3);
455                 TM = parseDVBtime(
456                         eit_event->start_time_1,
457                         eit_event->start_time_2,
458                         eit_event->start_time_3,
459                         eit_event->start_time_4,
460                         eit_event->start_time_5);
461
462                 if ( TM == 3599 )
463                         goto next;
464
465                 if ( TM != 3599 && (TM+duration < now || TM > now+14*24*60*60) )
466                         goto next;
467
468                 if ( now <= (TM+duration) || TM == 3599 /*NVOD Service*/ )  // old events should not be cached
469                 {
470                         __u16 event_id = HILO(eit_event->event_id);
471 //                      eDebug("event_id is %d sid is %04x", event_id, service.sid);
472
473                         eventData *evt = 0;
474                         int ev_erase_count = 0;
475                         int tm_erase_count = 0;
476
477                         // search in eventmap
478                         eventMap::iterator ev_it =
479                                 servicemap.first.find(event_id);
480
481                         // entry with this event_id is already exist ?
482                         if ( ev_it != servicemap.first.end() )
483                         {
484                                 if ( source > ev_it->second->type )  // update needed ?
485                                         goto next; // when not.. then skip this entry
486
487                                 // search this event in timemap
488                                 timeMap::iterator tm_it_tmp =
489                                         servicemap.second.find(ev_it->second->getStartTime());
490
491                                 if ( tm_it_tmp != servicemap.second.end() )
492                                 {
493                                         if ( tm_it_tmp->first == TM ) // just update eventdata
494                                         {
495                                                 // exempt memory
496                                                 delete ev_it->second;
497                                                 ev_it->second = tm_it_tmp->second =
498                                                         new eventData(eit_event, eit_event_size, source);
499                                                 FixOverlapping(servicemap, TM, duration, tm_it_tmp, service);
500                                                 goto next;
501                                         }
502                                         else  // event has new event begin time
503                                         {
504                                                 tm_erase_count++;
505                                                 // delete the found record from timemap
506                                                 servicemap.second.erase(tm_it_tmp);
507                                                 prevTimeIt=servicemap.second.end();
508                                         }
509                                 }
510                         }
511
512                         // search in timemap, for check of a case if new time has coincided with time of other event
513                         // or event was is not found in eventmap
514                         timeMap::iterator tm_it =
515                                 servicemap.second.find(TM);
516
517                         if ( tm_it != servicemap.second.end() )
518                         {
519                                 // event with same start time but another event_id...
520                                 if ( source > tm_it->second->type &&
521                                         ev_it == servicemap.first.end() )
522                                         goto next; // when not.. then skip this entry
523
524                                 // search this time in eventmap
525                                 eventMap::iterator ev_it_tmp =
526                                         servicemap.first.find(tm_it->second->getEventID());
527
528                                 if ( ev_it_tmp != servicemap.first.end() )
529                                 {
530                                         ev_erase_count++;
531                                         // delete the found record from eventmap
532                                         servicemap.first.erase(ev_it_tmp);
533                                         prevEventIt=servicemap.first.end();
534                                 }
535                         }
536
537                         evt = new eventData(eit_event, eit_event_size, source);
538 #ifdef EPG_DEBUG
539                         bool consistencyCheck=true;
540 #endif
541                         if (ev_erase_count > 0 && tm_erase_count > 0) // 2 different pairs have been removed
542                         {
543                                 // exempt memory
544                                 delete ev_it->second;
545                                 delete tm_it->second;
546                                 ev_it->second=evt;
547                                 tm_it->second=evt;
548                         }
549                         else if (ev_erase_count == 0 && tm_erase_count > 0)
550                         {
551                                 // exempt memory
552                                 delete ev_it->second;
553                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
554                                 ev_it->second=evt;
555                         }
556                         else if (ev_erase_count > 0 && tm_erase_count == 0)
557                         {
558                                 // exempt memory
559                                 delete tm_it->second;
560                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
561                                 tm_it->second=evt;
562                         }
563                         else // added new eventData
564                         {
565 #ifdef EPG_DEBUG
566                                 consistencyCheck=false;
567 #endif
568                                 ev_it=prevEventIt=servicemap.first.insert( prevEventIt, std::pair<const __u16, eventData*>( event_id, evt) );
569                                 tm_it=prevTimeIt=servicemap.second.insert( prevTimeIt, std::pair<const time_t, eventData*>( TM, evt ) );
570                         }
571
572                         FixOverlapping(servicemap, TM, duration, tm_it, service);
573
574 #ifdef EPG_DEBUG
575                         if ( consistencyCheck )
576                         {
577                                 if ( tm_it->second != evt || ev_it->second != evt )
578                                         eFatal("tm_it->second != ev_it->second");
579                                 else if ( tm_it->second->getStartTime() != tm_it->first )
580                                         eFatal("event start_time(%d) non equal timemap key(%d)",
581                                                 tm_it->second->getStartTime(), tm_it->first );
582                                 else if ( tm_it->first != TM )
583                                         eFatal("timemap key(%d) non equal TM(%d)",
584                                                 tm_it->first, TM);
585                                 else if ( ev_it->second->getEventID() != ev_it->first )
586                                         eFatal("event_id (%d) non equal event_map key(%d)",
587                                                 ev_it->second->getEventID(), ev_it->first);
588                                 else if ( ev_it->first != event_id )
589                                         eFatal("eventmap key(%d) non equal event_id(%d)",
590                                                 ev_it->first, event_id );
591                         }
592 #endif
593                 }
594 next:
595 #ifdef EPG_DEBUG
596                 if ( servicemap.first.size() != servicemap.second.size() )
597                 {
598                         FILE *f = fopen("/hdd/event_map.txt", "w+");
599                         int i=0;
600                         for (eventMap::iterator it(servicemap.first.begin())
601                                 ; it != servicemap.first.end(); ++it )
602                                 fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
603                                         i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
604                         fclose(f);
605                         f = fopen("/hdd/time_map.txt", "w+");
606                         i=0;
607                         for (timeMap::iterator it(servicemap.second.begin())
608                                 ; it != servicemap.second.end(); ++it )
609                                         fprintf(f, "%d(key %d) -> time %d, event_id %d, data %p\n", 
610                                                 i++, (int)it->first, (int)it->second->getStartTime(), (int)it->second->getEventID(), it->second );
611                         fclose(f);
612
613                         eFatal("(1)map sizes not equal :( sid %04x tsid %04x onid %04x size %d size2 %d", 
614                                 service.sid, service.tsid, service.onid, 
615                                 servicemap.first.size(), servicemap.second.size() );
616                 }
617 #endif
618                 ptr += eit_event_size;
619                 eit_event=(eit_event_struct*)(((__u8*)eit_event)+eit_event_size);
620         }
621 }
622
623 void eEPGCache::flushEPG(const uniqueEPGKey & s)
624 {
625         eDebug("[EPGC] flushEPG %d", (int)(bool)s);
626         singleLock l(cache_lock);
627         if (s)  // clear only this service
628         {
629                 eventCache::iterator it = eventDB.find(s);
630                 if ( it != eventDB.end() )
631                 {
632                         eventMap &evMap = it->second.first;
633                         timeMap &tmMap = it->second.second;
634                         tmMap.clear();
635                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
636                                 delete i->second;
637                         evMap.clear();
638                         eventDB.erase(it);
639
640                         // TODO .. search corresponding channel for removed service and remove this channel from lastupdated map
641 #ifdef ENABLE_PRIVATE_EPG
642                         contentMaps::iterator it =
643                                 content_time_tables.find(s);
644                         if ( it != content_time_tables.end() )
645                         {
646                                 it->second.clear();
647                                 content_time_tables.erase(it);
648                         }
649 #endif
650                 }
651         }
652         else // clear complete EPG Cache
653         {
654                 for (eventCache::iterator it(eventDB.begin());
655                         it != eventDB.end(); ++it)
656                 {
657                         eventMap &evMap = it->second.first;
658                         timeMap &tmMap = it->second.second;
659                         for (eventMap::iterator i = evMap.begin(); i != evMap.end(); ++i)
660                                 delete i->second;
661                         evMap.clear();
662                         tmMap.clear();
663                 }
664                 eventDB.clear();
665 #ifdef ENABLE_PRIVATE_EPG
666                 content_time_tables.clear();
667 #endif
668                 channelLastUpdated.clear();
669                 singleLock m(channel_map_lock);
670                 for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
671                         it->second->startEPG();
672         }
673         eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
674 }
675
676 void eEPGCache::cleanLoop()
677 {
678         singleLock s(cache_lock);
679         if (!eventDB.empty())
680         {
681                 eDebug("[EPGC] start cleanloop");
682
683                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
684
685                 for (eventCache::iterator DBIt = eventDB.begin(); DBIt != eventDB.end(); DBIt++)
686                 {
687                         bool updated = false;
688                         for (timeMap::iterator It = DBIt->second.second.begin(); It != DBIt->second.second.end() && It->first < now;)
689                         {
690                                 if ( now > (It->first+It->second->getDuration()) )  // outdated normal entry (nvod references to)
691                                 {
692                                         // remove entry from eventMap
693                                         eventMap::iterator b(DBIt->second.first.find(It->second->getEventID()));
694                                         if ( b != DBIt->second.first.end() )
695                                         {
696                                                 // release Heap Memory for this entry   (new ....)
697 //                                              eDebug("[EPGC] delete old event (evmap)");
698                                                 DBIt->second.first.erase(b);
699                                         }
700
701                                         // remove entry from timeMap
702 //                                      eDebug("[EPGC] release heap mem");
703                                         delete It->second;
704                                         DBIt->second.second.erase(It++);
705 //                                      eDebug("[EPGC] delete old event (timeMap)");
706                                         updated = true;
707                                 }
708                                 else
709                                         ++It;
710                         }
711 #ifdef ENABLE_PRIVATE_EPG
712                         if ( updated )
713                         {
714                                 contentMaps::iterator x =
715                                         content_time_tables.find( DBIt->first );
716                                 if ( x != content_time_tables.end() )
717                                 {
718                                         timeMap &tmMap = DBIt->second.second;
719                                         for ( contentMap::iterator i = x->second.begin(); i != x->second.end(); )
720                                         {
721                                                 for ( contentTimeMap::iterator it(i->second.begin());
722                                                         it != i->second.end(); )
723                                                 {
724                                                         if ( tmMap.find(it->second.first) == tmMap.end() )
725                                                                 i->second.erase(it++);
726                                                         else
727                                                                 ++it;
728                                                 }
729                                                 if ( i->second.size() )
730                                                         ++i;
731                                                 else
732                                                         x->second.erase(i++);
733                                         }
734                                 }
735                         }
736 #endif
737                 }
738                 eDebug("[EPGC] stop cleanloop");
739                 eDebug("[EPGC] %i bytes for cache used", eventData::CacheSize);
740         }
741         cleanTimer.start(CLEAN_INTERVAL,true);
742 }
743
744 eEPGCache::~eEPGCache()
745 {
746         messages.send(Message::quit);
747         kill(); // waiting for thread shutdown
748         singleLock s(cache_lock);
749         for (eventCache::iterator evIt = eventDB.begin(); evIt != eventDB.end(); evIt++)
750                 for (eventMap::iterator It = evIt->second.first.begin(); It != evIt->second.first.end(); It++)
751                         delete It->second;
752 }
753
754 void eEPGCache::gotMessage( const Message &msg )
755 {
756         switch (msg.type)
757         {
758                 case Message::flush:
759                         flushEPG(msg.service);
760                         break;
761                 case Message::startChannel:
762                 {
763                         singleLock s(channel_map_lock);
764                         channelMapIterator channel =
765                                 m_knownChannels.find(msg.channel);
766                         if ( channel != m_knownChannels.end() )
767                                 channel->second->startChannel();
768                         break;
769                 }
770                 case Message::leaveChannel:
771                 {
772                         singleLock s(channel_map_lock);
773                         channelMapIterator channel =
774                                 m_knownChannels.find(msg.channel);
775                         if ( channel != m_knownChannels.end() )
776                                 channel->second->abortEPG();
777                         break;
778                 }
779                 case Message::quit:
780                         quit(0);
781                         break;
782 #ifdef ENABLE_PRIVATE_EPG
783                 case Message::got_private_pid:
784                 {
785                         singleLock s(channel_map_lock);
786                         for (channelMapIterator it(m_knownChannels.begin()); it != m_knownChannels.end(); ++it)
787                         {
788                                 eDVBChannel *channel = (eDVBChannel*) it->first;
789                                 channel_data *data = it->second;
790                                 eDVBChannelID chid = channel->getChannelID();
791                                 if ( chid.transport_stream_id.get() == msg.service.tsid &&
792                                         chid.original_network_id.get() == msg.service.onid &&
793                                         data->m_PrivatePid == -1 )
794                                 {
795                                         data->m_PrevVersion = -1;
796                                         data->m_PrivatePid = msg.pid;
797                                         data->m_PrivateService = msg.service;
798                                         int onid = chid.original_network_id.get();
799                                         onid |= 0x80000000;  // we use highest bit as private epg indicator
800                                         chid.original_network_id = onid;
801                                         updateMap::iterator It = channelLastUpdated.find( chid );
802                                         int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
803                                         if (update < ZAP_DELAY)
804                                                 update = ZAP_DELAY;
805                                         data->startPrivateTimer.start(update, 1);
806                                         if (update >= 60000)
807                                                 eDebug("[EPGC] next private update in %i min", update/60000);
808                                         else if (update >= 1000)
809                                                 eDebug("[EPGC] next private update in %i sec", update/1000);
810                                         break;
811                                 }
812                         }
813                         break;
814                 }
815 #endif
816                 case Message::timeChanged:
817                         cleanLoop();
818                         break;
819                 default:
820                         eDebug("unhandled EPGCache Message!!");
821                         break;
822         }
823 }
824
825 void eEPGCache::thread()
826 {
827         hasStarted();
828         nice(4);
829         load();
830         cleanLoop();
831         runLoop();
832         save();
833 }
834
835 void eEPGCache::load()
836 {
837         singleLock s(cache_lock);
838         FILE *f = fopen("/hdd/epg.dat", "r");
839         if (f)
840         {
841                 int size=0;
842                 int cnt=0;
843 #if 0
844                 unsigned char md5_saved[16];
845                 unsigned char md5[16];
846                 bool md5ok=false;
847
848                 if (!md5_file("/hdd/epg.dat", 1, md5))
849                 {
850                         FILE *f = fopen("/hdd/epg.dat.md5", "r");
851                         if (f)
852                         {
853                                 fread( md5_saved, 16, 1, f);
854                                 fclose(f);
855                                 if ( !memcmp(md5_saved, md5, 16) )
856                                         md5ok=true;
857                         }
858                 }
859                 if ( md5ok )
860 #endif
861                 {
862                         unsigned int magic=0;
863                         fread( &magic, sizeof(int), 1, f);
864                         if (magic != 0x98765432)
865                         {
866                                 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
867                                 fclose(f);
868                                 return;
869                         }
870                         char text1[13];
871                         fread( text1, 13, 1, f);
872                         if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
873                         {
874                                 fread( &size, sizeof(int), 1, f);
875                                 while(size--)
876                                 {
877                                         uniqueEPGKey key;
878                                         eventMap evMap;
879                                         timeMap tmMap;
880                                         int size=0;
881                                         fread( &key, sizeof(uniqueEPGKey), 1, f);
882                                         fread( &size, sizeof(int), 1, f);
883                                         while(size--)
884                                         {
885                                                 __u8 len=0;
886                                                 __u8 type=0;
887                                                 eventData *event=0;
888                                                 fread( &type, sizeof(__u8), 1, f);
889                                                 fread( &len, sizeof(__u8), 1, f);
890                                                 event = new eventData(0, len, type);
891                                                 event->EITdata = new __u8[len];
892                                                 eventData::CacheSize+=len;
893                                                 fread( event->EITdata, len, 1, f);
894                                                 evMap[ event->getEventID() ]=event;
895                                                 tmMap[ event->getStartTime() ]=event;
896                                                 ++cnt;
897                                         }
898                                         eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
899                                 }
900                                 eventData::load(f);
901                                 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
902 #ifdef ENABLE_PRIVATE_EPG
903                                 char text2[11];
904                                 fread( text2, 11, 1, f);
905                                 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
906                                 {
907                                         size=0;
908                                         fread( &size, sizeof(int), 1, f);
909                                         while(size--)
910                                         {
911                                                 int size=0;
912                                                 uniqueEPGKey key;
913                                                 fread( &key, sizeof(uniqueEPGKey), 1, f);
914                                                 eventMap &evMap=eventDB[key].first;
915                                                 fread( &size, sizeof(int), 1, f);
916                                                 while(size--)
917                                                 {
918                                                         int size;
919                                                         int content_id;
920                                                         fread( &content_id, sizeof(int), 1, f);
921                                                         fread( &size, sizeof(int), 1, f);
922                                                         while(size--)
923                                                         {
924                                                                 time_t time1, time2;
925                                                                 __u16 event_id;
926                                                                 fread( &time1, sizeof(time_t), 1, f);
927                                                                 fread( &time2, sizeof(time_t), 1, f);
928                                                                 fread( &event_id, sizeof(__u16), 1, f);
929                                                                 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
930                                                                 eventMap::iterator it =
931                                                                         evMap.find(event_id);
932                                                                 if (it != evMap.end())
933                                                                         it->second->type = PRIVATE;
934                                                         }
935                                                 }
936                                         }
937                                 }
938 #endif // ENABLE_PRIVATE_EPG
939                         }
940                         else
941                                 eDebug("[EPGC] don't read old epg database");
942                         fclose(f);
943                 }
944         }
945 }
946
947 void eEPGCache::save()
948 {
949         struct statfs s;
950         off64_t tmp;
951         if (statfs("/hdd", &s)<0)
952                 tmp=0;
953         else
954         {
955                 tmp=s.f_blocks;
956                 tmp*=s.f_bsize;
957         }
958
959         // prevent writes to builtin flash
960         if ( tmp < 1024*1024*50 ) // storage size < 50MB
961                 return;
962
963         // check for enough free space on storage
964         tmp=s.f_bfree;
965         tmp*=s.f_bsize;
966         if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
967                 return;
968
969         FILE *f = fopen("/hdd/epg.dat", "w");
970         int cnt=0;
971         if ( f )
972         {
973                 unsigned int magic = 0x98765432;
974                 fwrite( &magic, sizeof(int), 1, f);
975                 const char *text = "ENIGMA_EPG_V5";
976                 fwrite( text, 13, 1, f );
977                 int size = eventDB.size();
978                 fwrite( &size, sizeof(int), 1, f );
979                 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
980                 {
981                         timeMap &timemap = service_it->second.second;
982                         fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
983                         size = timemap.size();
984                         fwrite( &size, sizeof(int), 1, f);
985                         for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
986                         {
987                                 __u8 len = time_it->second->ByteSize;
988                                 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
989                                 fwrite( &len, sizeof(__u8), 1, f);
990                                 fwrite( time_it->second->EITdata, len, 1, f);
991                                 ++cnt;
992                         }
993                 }
994                 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
995                 eventData::save(f);
996 #ifdef ENABLE_PRIVATE_EPG
997                 const char* text3 = "PRIVATE_EPG";
998                 fwrite( text3, 11, 1, f );
999                 size = content_time_tables.size();
1000                 fwrite( &size, sizeof(int), 1, f);
1001                 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
1002                 {
1003                         contentMap &content_time_table = a->second;
1004                         fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
1005                         int size = content_time_table.size();
1006                         fwrite( &size, sizeof(int), 1, f);
1007                         for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
1008                         {
1009                                 int size = i->second.size();
1010                                 fwrite( &i->first, sizeof(int), 1, f);
1011                                 fwrite( &size, sizeof(int), 1, f);
1012                                 for ( contentTimeMap::iterator it(i->second.begin());
1013                                         it != i->second.end(); ++it )
1014                                 {
1015                                         fwrite( &it->first, sizeof(time_t), 1, f);
1016                                         fwrite( &it->second.first, sizeof(time_t), 1, f);
1017                                         fwrite( &it->second.second, sizeof(__u16), 1, f);
1018                                 }
1019                         }
1020                 }
1021 #endif
1022                 fclose(f);
1023 #if 0
1024                 unsigned char md5[16];
1025                 if (!md5_file("/hdd/epg.dat", 1, md5))
1026                 {
1027                         FILE *f = fopen("/hdd/epg.dat.md5", "w");
1028                         if (f)
1029                         {
1030                                 fwrite( md5, 16, 1, f);
1031                                 fclose(f);
1032                         }
1033                 }
1034 #endif
1035         }
1036 }
1037
1038 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1039         :cache(ml)
1040         ,abortTimer(ml), zapTimer(ml), state(0)
1041         ,isRunning(0), haveData(0)
1042 #ifdef ENABLE_PRIVATE_EPG
1043         ,startPrivateTimer(ml)
1044 #endif
1045 #ifdef ENABLE_MHW_EPG
1046         ,m_MHWTimeoutTimer(ml)
1047 #endif
1048 {
1049 #ifdef ENABLE_MHW_EPG
1050         CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1051 #endif
1052         CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1053         CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1054 #ifdef ENABLE_PRIVATE_EPG
1055         CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1056 #endif
1057         pthread_mutex_init(&channel_active, 0);
1058 }
1059
1060 bool eEPGCache::channel_data::finishEPG()
1061 {
1062         if (!isRunning)  // epg ready
1063         {
1064                 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1065                 zapTimer.start(UPDATE_INTERVAL, 1);
1066                 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1067                 for (int i=0; i < 3; ++i)
1068                 {
1069                         seenSections[i].clear();
1070                         calcedSections[i].clear();
1071                 }
1072                 singleLock l(cache->cache_lock);
1073                 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1074 #ifdef ENABLE_MHW_EPG
1075                 cleanup();
1076 #endif
1077                 return true;
1078         }
1079         return false;
1080 }
1081
1082 void eEPGCache::channel_data::startEPG()
1083 {
1084         eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1085         state=0;
1086         haveData=0;
1087         for (int i=0; i < 3; ++i)
1088         {
1089                 seenSections[i].clear();
1090                 calcedSections[i].clear();
1091         }
1092
1093         eDVBSectionFilterMask mask;
1094         memset(&mask, 0, sizeof(mask));
1095
1096 #ifdef ENABLE_MHW_EPG
1097         mask.pid = 0xD3;
1098         mask.data[0] = 0x91;
1099         mask.mask[0] = 0xFF;
1100         m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1101         m_MHWReader->start(mask);
1102         isRunning |= MHW;
1103         memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1104
1105         mask.pid = 0x231;
1106         mask.data[0] = 0xC8;
1107         mask.mask[0] = 0xFF;
1108         mask.data[1] = 0;
1109         mask.mask[1] = 0xFF;
1110         m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1111         m_MHWReader2->start(mask);
1112         isRunning |= MHW;
1113         memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1114         mask.data[1] = 0;
1115         mask.mask[1] = 0;
1116 #endif
1117
1118         mask.pid = 0x12;
1119         mask.flags = eDVBSectionFilterMask::rfCRC;
1120
1121         mask.data[0] = 0x4E;
1122         mask.mask[0] = 0xFE;
1123         m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1124         m_NowNextReader->start(mask);
1125         isRunning |= NOWNEXT;
1126
1127         mask.data[0] = 0x50;
1128         mask.mask[0] = 0xF0;
1129         m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1130         m_ScheduleReader->start(mask);
1131         isRunning |= SCHEDULE;
1132
1133         mask.data[0] = 0x60;
1134         m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1135         m_ScheduleOtherReader->start(mask);
1136         isRunning |= SCHEDULE_OTHER;
1137
1138         abortTimer.start(7000,true);
1139 }
1140
1141 void eEPGCache::channel_data::abortNonAvail()
1142 {
1143         if (!state)
1144         {
1145                 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1146                 {
1147                         eDebug("[EPGC] abort non avail nownext reading");
1148                         isRunning &= ~NOWNEXT;
1149                         m_NowNextReader->stop();
1150                         m_NowNextConn=0;
1151                 }
1152                 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1153                 {
1154                         eDebug("[EPGC] abort non avail schedule reading");
1155                         isRunning &= ~SCHEDULE;
1156                         m_ScheduleReader->stop();
1157                         m_ScheduleConn=0;
1158                 }
1159                 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1160                 {
1161                         eDebug("[EPGC] abort non avail schedule_other reading");
1162                         isRunning &= ~SCHEDULE_OTHER;
1163                         m_ScheduleOtherReader->stop();
1164                         m_ScheduleOtherConn=0;
1165                 }
1166 #ifdef ENABLE_MHW_EPG
1167                 if ( !(haveData&MHW) && (isRunning&MHW) )
1168                 {
1169                         eDebug("[EPGC] abort non avail mhw reading");
1170                         isRunning &= ~MHW;
1171                         m_MHWReader->stop();
1172                         m_MHWConn=0;
1173                         m_MHWReader2->stop();
1174                         m_MHWConn2=0;
1175                 }
1176 #endif
1177                 if ( isRunning )
1178                         abortTimer.start(90000, true);
1179                 else
1180                 {
1181                         ++state;
1182                         for (int i=0; i < 3; ++i)
1183                         {
1184                                 seenSections[i].clear();
1185                                 calcedSections[i].clear();
1186                         }
1187                 }
1188         }
1189         ++state;
1190 }
1191
1192 void eEPGCache::channel_data::startChannel()
1193 {
1194         pthread_mutex_lock(&channel_active);
1195         updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1196
1197         int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1198
1199         if (update < ZAP_DELAY)
1200                 update = ZAP_DELAY;
1201
1202         zapTimer.start(update, 1);
1203         if (update >= 60000)
1204                 eDebug("[EPGC] next update in %i min", update/60000);
1205         else if (update >= 1000)
1206                 eDebug("[EPGC] next update in %i sec", update/1000);
1207 }
1208
1209 void eEPGCache::channel_data::abortEPG()
1210 {
1211         for (int i=0; i < 3; ++i)
1212         {
1213                 seenSections[i].clear();
1214                 calcedSections[i].clear();
1215         }
1216         abortTimer.stop();
1217         zapTimer.stop();
1218         if (isRunning)
1219         {
1220                 eDebug("[EPGC] abort caching events !!");
1221                 if (isRunning & SCHEDULE)
1222                 {
1223                         isRunning &= ~SCHEDULE;
1224                         m_ScheduleReader->stop();
1225                         m_ScheduleConn=0;
1226                 }
1227                 if (isRunning & NOWNEXT)
1228                 {
1229                         isRunning &= ~NOWNEXT;
1230                         m_NowNextReader->stop();
1231                         m_NowNextConn=0;
1232                 }
1233                 if (isRunning & SCHEDULE_OTHER)
1234                 {
1235                         isRunning &= ~SCHEDULE_OTHER;
1236                         m_ScheduleOtherReader->stop();
1237                         m_ScheduleOtherConn=0;
1238                 }
1239 #ifdef ENABLE_MHW_EPG
1240                 if (isRunning & MHW)
1241                 {
1242                         isRunning &= ~MHW;
1243                         m_MHWReader->stop();
1244                         m_MHWConn=0;
1245                         m_MHWReader2->stop();
1246                         m_MHWConn2=0;
1247                 }
1248 #endif
1249         }
1250 #ifdef ENABLE_PRIVATE_EPG
1251         if (m_PrivateReader)
1252                 m_PrivateReader->stop();
1253         if (m_PrivateConn)
1254                 m_PrivateConn=0;
1255 #endif
1256         pthread_mutex_unlock(&channel_active);
1257 }
1258
1259 void eEPGCache::channel_data::readData( const __u8 *data)
1260 {
1261         int source;
1262         int map;
1263         iDVBSectionReader *reader=NULL;
1264         switch(data[0])
1265         {
1266                 case 0x4E ... 0x4F:
1267                         reader=m_NowNextReader;
1268                         source=NOWNEXT;
1269                         map=0;
1270                         break;
1271                 case 0x50 ... 0x5F:
1272                         reader=m_ScheduleReader;
1273                         source=SCHEDULE;
1274                         map=1;
1275                         break;
1276                 case 0x60 ... 0x6F:
1277                         reader=m_ScheduleOtherReader;
1278                         source=SCHEDULE_OTHER;
1279                         map=2;
1280                         break;
1281                 default:
1282                         eDebug("[EPGC] unknown table_id !!!");
1283                         return;
1284         }
1285         tidMap &seenSections = this->seenSections[map];
1286         tidMap &calcedSections = this->calcedSections[map];
1287         if ( state == 1 && calcedSections == seenSections || state > 1 )
1288         {
1289                 eDebugNoNewLine("[EPGC] ");
1290                 switch (source)
1291                 {
1292                         case NOWNEXT:
1293                                 m_NowNextConn=0;
1294                                 eDebugNoNewLine("nownext");
1295                                 break;
1296                         case SCHEDULE:
1297                                 m_ScheduleConn=0;
1298                                 eDebugNoNewLine("schedule");
1299                                 break;
1300                         case SCHEDULE_OTHER:
1301                                 m_ScheduleOtherConn=0;
1302                                 eDebugNoNewLine("schedule other");
1303                                 break;
1304                         default: eDebugNoNewLine("unknown");break;
1305                 }
1306                 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1307                 if ( reader )
1308                         reader->stop();
1309                 isRunning &= ~source;
1310                 if (!isRunning)
1311                         finishEPG();
1312         }
1313         else
1314         {
1315                 eit_t *eit = (eit_t*) data;
1316                 __u32 sectionNo = data[0] << 24;
1317                 sectionNo |= data[3] << 16;
1318                 sectionNo |= data[4] << 8;
1319                 sectionNo |= eit->section_number;
1320
1321                 tidMap::iterator it =
1322                         seenSections.find(sectionNo);
1323
1324                 if ( it == seenSections.end() )
1325                 {
1326                         seenSections.insert(sectionNo);
1327                         calcedSections.insert(sectionNo);
1328                         __u32 tmpval = sectionNo & 0xFFFFFF00;
1329                         __u8 incr = source == NOWNEXT ? 1 : 8;
1330                         for ( int i = 0; i <= eit->last_section_number; i+=incr )
1331                         {
1332                                 if ( i == eit->section_number )
1333                                 {
1334                                         for (int x=i; x <= eit->segment_last_section_number; ++x)
1335                                                 calcedSections.insert(tmpval|(x&0xFF));
1336                                 }
1337                                 else
1338                                         calcedSections.insert(tmpval|(i&0xFF));
1339                         }
1340                         cache->sectionRead(data, source, this);
1341                 }
1342         }
1343 }
1344
1345 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1346 // if t == -1 we search the current event...
1347 {
1348         singleLock s(cache_lock);
1349         uniqueEPGKey key(handleGroup(service));
1350
1351         // check if EPG for this service is ready...
1352         eventCache::iterator It = eventDB.find( key );
1353         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1354         {
1355                 if (t==-1)
1356                         t = eDVBLocalTimeHandler::getInstance()->nowTime();
1357                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1358                         It->second.second.upper_bound(t); // just >
1359                 if ( i != It->second.second.end() )
1360                 {
1361                         if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1362                         {
1363                                 timeMap::iterator x = i;
1364                                 --x;
1365                                 if ( x != It->second.second.end() )
1366                                 {
1367                                         time_t start_time = x->second->getStartTime();
1368                                         if (direction >= 0)
1369                                         {
1370                                                 if (t < start_time)
1371                                                         return -1;
1372                                                 if (t > (start_time+x->second->getDuration()))
1373                                                         return -1;
1374                                         }
1375                                         i = x;
1376                                 }
1377                                 else
1378                                         return -1;
1379                         }
1380                         result = i->second;
1381                         return 0;
1382                 }
1383         }
1384         return -1;
1385 }
1386
1387 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1388 {
1389         singleLock s(cache_lock);
1390         const eventData *data=0;
1391         RESULT ret = lookupEventTime(service, t, data, direction);
1392         if ( !ret && data )
1393                 result = data->get();
1394         return ret;
1395 }
1396
1397 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1398 {
1399         singleLock s(cache_lock);
1400         const eventData *data=0;
1401         RESULT ret = lookupEventTime(service, t, data, direction);
1402         if ( !ret && data )
1403                 result = new Event((uint8_t*)data->get());
1404         return ret;
1405 }
1406
1407 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1408 {
1409         singleLock s(cache_lock);
1410         const eventData *data=0;
1411         RESULT ret = lookupEventTime(service, t, data, direction);
1412         if ( !ret && data )
1413         {
1414                 Event ev((uint8_t*)data->get());
1415                 result = new eServiceEvent();
1416                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1417                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1418         }
1419         return ret;
1420 }
1421
1422 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1423 {
1424         singleLock s(cache_lock);
1425         uniqueEPGKey key(handleGroup(service));
1426
1427         eventCache::iterator It = eventDB.find( key );
1428         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1429         {
1430                 eventMap::iterator i( It->second.first.find( event_id ));
1431                 if ( i != It->second.first.end() )
1432                 {
1433                         result = i->second;
1434                         return 0;
1435                 }
1436                 else
1437                 {
1438                         result = 0;
1439                         eDebug("[EPGC] event %04x not found in epgcache", event_id);
1440                 }
1441         }
1442         return -1;
1443 }
1444
1445 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1446 {
1447         singleLock s(cache_lock);
1448         const eventData *data=0;
1449         RESULT ret = lookupEventId(service, event_id, data);
1450         if ( !ret && data )
1451                 result = data->get();
1452         return ret;
1453 }
1454
1455 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1456 {
1457         singleLock s(cache_lock);
1458         const eventData *data=0;
1459         RESULT ret = lookupEventId(service, event_id, data);
1460         if ( !ret && data )
1461                 result = new Event((uint8_t*)data->get());
1462         return ret;
1463 }
1464
1465 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1466 {
1467         singleLock s(cache_lock);
1468         const eventData *data=0;
1469         RESULT ret = lookupEventId(service, event_id, data);
1470         if ( !ret && data )
1471         {
1472                 Event ev((uint8_t*)data->get());
1473                 result = new eServiceEvent();
1474                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1475                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1476         }
1477         return ret;
1478 }
1479
1480 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1481 {
1482         Lock();
1483         eventCache::iterator It = eventDB.find(handleGroup(service));
1484         if ( It != eventDB.end() && It->second.second.size() )
1485         {
1486                 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1487                 if ( begin != -1 )
1488                 {
1489                         m_timemap_cursor = It->second.second.lower_bound(begin);
1490                         if ( m_timemap_cursor != It->second.second.end() )
1491                         {
1492                                 if ( m_timemap_cursor->second->getStartTime() != begin )
1493                                 {
1494                                         timeMap::iterator x = m_timemap_cursor;
1495                                         --x;
1496                                         if ( x != It->second.second.end() )
1497                                         {
1498                                                 time_t start_time = x->second->getStartTime();
1499                                                 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1500                                                         m_timemap_cursor = x;
1501                                         }
1502                                 }
1503                         }
1504                 }
1505                 else
1506                         m_timemap_cursor = It->second.second.begin();
1507                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1508                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1509                 Unlock();
1510                 return 0;
1511         }
1512         Unlock();
1513         return -1;
1514 }
1515
1516 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1517 {
1518         if ( m_timemap_cursor != m_timemap_end )
1519         {
1520                 result = m_timemap_cursor++->second;
1521                 return 0;
1522         }
1523         return -1;
1524 }
1525
1526 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1527 {
1528         if ( m_timemap_cursor != m_timemap_end )
1529         {
1530                 result = m_timemap_cursor++->second->get();
1531                 return 0;
1532         }
1533         return -1;
1534 }
1535
1536 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1537 {
1538         if ( m_timemap_cursor != m_timemap_end )
1539         {
1540                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1541                 return 0;
1542         }
1543         return -1;
1544 }
1545
1546 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1547 {
1548         if ( m_timemap_cursor != m_timemap_end )
1549         {
1550                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1551                 result = new eServiceEvent();
1552                 return result->parseFrom(&ev, currentQueryTsidOnid);
1553         }
1554         return -1;
1555 }
1556
1557 void fillTuple(ePyObject tuple, char *argstring, int argcount, ePyObject service, ePtr<eServiceEvent> &ptr, ePyObject nowTime, ePyObject service_name )
1558 {
1559         ePyObject tmp;
1560         int pos=0;
1561         while(pos < argcount)
1562         {
1563                 bool inc_refcount=false;
1564                 switch(argstring[pos])
1565                 {
1566                         case '0': // PyLong 0
1567                                 tmp = PyLong_FromLong(0);
1568                                 break;
1569                         case 'I': // Event Id
1570                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1571                                 break;
1572                         case 'B': // Event Begin Time
1573                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1574                                 break;
1575                         case 'D': // Event Duration
1576                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1577                                 break;
1578                         case 'T': // Event Title
1579                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1580                                 break;
1581                         case 'S': // Event Short Description
1582                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1583                                 break;
1584                         case 'E': // Event Extended Description
1585                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1586                                 break;
1587                         case 'C': // Current Time
1588                                 tmp = nowTime;
1589                                 inc_refcount = true;
1590                                 break;
1591                         case 'R': // service reference string
1592                                 tmp = service;
1593                                 inc_refcount = true;
1594                                 break;
1595                         case 'N': // service name
1596                                 tmp = service_name;
1597                                 inc_refcount = true;
1598                 }
1599                 if (!tmp)
1600                 {
1601                         tmp = Py_None;
1602                         inc_refcount = true;
1603                 }
1604                 if (inc_refcount)
1605                         Py_INCREF(tmp);
1606                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1607         }
1608 }
1609
1610 int handleEvent(ePtr<eServiceEvent> &ptr, ePyObject dest_list, char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1611 {
1612         if (convertFunc)
1613         {
1614                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1615                 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1616                 if (result)
1617                 {
1618                         if (service_name)
1619                                 Py_DECREF(service_name);
1620                         if (nowTime)
1621                                 Py_DECREF(nowTime);
1622                         Py_DECREF(convertFuncArgs);
1623                         Py_DECREF(dest_list);
1624                         PyErr_SetString(PyExc_StandardError,
1625                                 "error in convertFunc execute");
1626                         eDebug("error in convertFunc execute");
1627                         return -1;
1628                 }
1629                 PyList_Append(dest_list, result);
1630                 Py_DECREF(result);
1631         }
1632         else
1633         {
1634                 ePyObject tuple = PyTuple_New(argcount);
1635                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1636                 PyList_Append(dest_list, tuple);
1637                 Py_DECREF(tuple);
1638         }
1639         return 0;
1640 }
1641
1642 // here we get a python list
1643 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1644 //   0 = PyLong(0)
1645 //   I = Event Id
1646 //   B = Event Begin Time
1647 //   D = Event Duration
1648 //   T = Event Title
1649 //   S = Event Short Description
1650 //   E = Event Extended Description
1651 //   C = Current Time
1652 //   R = Service Reference
1653 //   N = Service Name
1654 // then for each service follows a tuple
1655 //   first tuple entry is the servicereference (as string... use the ref.toString() function)
1656 //   the second is the type of query
1657 //     2 = event_id
1658 //    -1 = event before given start_time
1659 //     0 = event intersects given start_time
1660 //    +1 = event after given start_time
1661 //   the third
1662 //      when type is eventid it is the event_id
1663 //      when type is time then it is the start_time ( 0 for now_time )
1664 //   the fourth is the end_time .. ( optional .. for query all events in time range)
1665
1666 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1667 {
1668         ePyObject convertFuncArgs;
1669         int argcount=0;
1670         char *argstring=NULL;
1671         if (!PyList_Check(list))
1672         {
1673                 PyErr_SetString(PyExc_StandardError,
1674                         "type error");
1675                 eDebug("no list");
1676                 return NULL;
1677         }
1678         int listIt=0;
1679         int listSize=PyList_Size(list);
1680         if (!listSize)
1681         {
1682                 PyErr_SetString(PyExc_StandardError,
1683                         "not params given");
1684                 eDebug("not params given");
1685                 return NULL;
1686         }
1687         else 
1688         {
1689                 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1690                 if (PyString_Check(argv))
1691                 {
1692                         argstring = PyString_AS_STRING(argv);
1693                         ++listIt;
1694                 }
1695                 else
1696                         argstring = "I"; // just event id as default
1697                 argcount = strlen(argstring);
1698 //              eDebug("have %d args('%s')", argcount, argstring);
1699         }
1700         if (convertFunc)
1701         {
1702                 if (!PyCallable_Check(convertFunc))
1703                 {
1704                         PyErr_SetString(PyExc_StandardError,
1705                                 "convertFunc must be callable");
1706                         eDebug("convertFunc is not callable");
1707                         return NULL;
1708                 }
1709                 convertFuncArgs = PyTuple_New(argcount);
1710         }
1711
1712         ePyObject nowTime = strchr(argstring, 'C') ?
1713                 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1714                 ePyObject();
1715
1716         bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1717
1718         // create dest list
1719         ePyObject dest_list=PyList_New(0);
1720         while(listSize > listIt)
1721         {
1722                 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1723                 if (PyTuple_Check(item))
1724                 {
1725                         bool service_changed=false;
1726                         int type=0;
1727                         long event_id=-1;
1728                         time_t stime=-1;
1729                         int minutes=0;
1730                         int tupleSize=PyTuple_Size(item);
1731                         int tupleIt=0;
1732                         ePyObject service;
1733                         while(tupleSize > tupleIt)  // parse query args
1734                         {
1735                                 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1736                                 switch(tupleIt++)
1737                                 {
1738                                         case 0:
1739                                         {
1740                                                 if (!PyString_Check(entry))
1741                                                 {
1742                                                         eDebug("tuple entry 0 is no a string");
1743                                                         goto skip_entry;
1744                                                 }
1745                                                 service = entry;
1746                                                 break;
1747                                         }
1748                                         case 1:
1749                                                 type=PyInt_AsLong(entry);
1750                                                 if (type < -1 || type > 2)
1751                                                 {
1752                                                         eDebug("unknown type %d", type);
1753                                                         goto skip_entry;
1754                                                 }
1755                                                 break;
1756                                         case 2:
1757                                                 event_id=stime=PyInt_AsLong(entry);
1758                                                 break;
1759                                         case 3:
1760                                                 minutes=PyInt_AsLong(entry);
1761                                                 break;
1762                                         default:
1763                                                 eDebug("unneeded extra argument");
1764                                                 break;
1765                                 }
1766                         }
1767                         eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1768                         if (ref.type != eServiceReference::idDVB)
1769                         {
1770                                 eDebug("service reference for epg query is not valid");
1771                                 continue;
1772                         }
1773
1774                         // redirect subservice querys to parent service
1775                         eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1776                         if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1777                         {
1778                                 eServiceCenterPtr service_center;
1779                                 if (!eServiceCenter::getPrivInstance(service_center))
1780                                 {
1781                                         dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1782                                         dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1783                                         dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1784                                         dvb_ref.setParentServiceID(eServiceID(0));
1785                                         dvb_ref.name="";
1786                                         service = PyString_FromString(dvb_ref.toString().c_str());
1787                                         service_changed = true;
1788                                 }
1789                         }
1790
1791                         ePyObject service_name;
1792                         if (must_get_service_name)
1793                         {
1794                                 ePtr<iStaticServiceInformation> sptr;
1795                                 eServiceCenterPtr service_center;
1796                                 eServiceCenter::getPrivInstance(service_center);
1797                                 if (service_center)
1798                                 {
1799                                         service_center->info(ref, sptr);
1800                                         if (sptr)
1801                                         {
1802                                                 std::string name;
1803                                                 sptr->getName(ref, name);
1804                                                 if (name.length())
1805                                                         service_name = PyString_FromString(name.c_str());
1806                                         }
1807                                 }
1808                                 if (!service_name)
1809                                         service_name = PyString_FromString("<n/a>");
1810                         }
1811                         if (minutes)
1812                         {
1813                                 Lock();
1814                                 if (!startTimeQuery(ref, stime, minutes))
1815                                 {
1816                                         ePtr<eServiceEvent> ptr;
1817                                         while (!getNextTimeEntry(ptr))
1818                                         {
1819                                                 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1820                                                 {
1821                                                         Unlock();
1822                                                         return 0;  // error
1823                                                 }
1824                                         }
1825                                 }
1826                                 Unlock();
1827                         }
1828                         else
1829                         {
1830                                 ePtr<eServiceEvent> ptr;
1831                                 if (stime)
1832                                 {
1833                                         if (type == 2)
1834                                                 lookupEventId(ref, event_id, ptr);
1835                                         else
1836                                                 lookupEventTime(ref, stime, ptr, type);
1837                                 }
1838                                 if (handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1839                                         return 0; // error
1840                         }
1841                         if (service_changed)
1842                                 Py_DECREF(service);
1843                         if (service_name)
1844                                 Py_DECREF(service_name);
1845                 }
1846 skip_entry:
1847                 ;
1848         }
1849         if (convertFuncArgs)
1850                 Py_DECREF(convertFuncArgs);
1851         if (nowTime)
1852                 Py_DECREF(nowTime);
1853         return dest_list;
1854 }
1855
1856 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, ePyObject service_name, ePyObject service_reference)
1857 {
1858         ePyObject tmp;
1859         int pos=0;
1860         while(pos < argcount)
1861         {
1862                 bool inc_refcount=false;
1863                 switch(argstring[pos])
1864                 {
1865                         case '0': // PyLong 0
1866                                 tmp = PyLong_FromLong(0);
1867                                 break;
1868                         case 'I': // Event Id
1869                                 tmp = PyLong_FromLong(evData->getEventID());
1870                                 break;
1871                         case 'B': // Event Begin Time
1872                                 if (ptr)
1873                                         tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1874                                 else
1875                                         tmp = PyLong_FromLong(evData->getStartTime());
1876                                 break;
1877                         case 'D': // Event Duration
1878                                 if (ptr)
1879                                         tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1880                                 else
1881                                         tmp = PyLong_FromLong(evData->getDuration());
1882                                 break;
1883                         case 'T': // Event Title
1884                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1885                                 break;
1886                         case 'S': // Event Short Description
1887                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1888                                 break;
1889                         case 'E': // Event Extended Description
1890                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1891                                 break;
1892                         case 'R': // service reference string
1893                                 tmp = service_reference;
1894                                 inc_refcount = true;
1895                                 break;
1896                         case 'N': // service name
1897                                 tmp = service_name;
1898                                 inc_refcount = true;
1899                                 break;
1900                 }
1901                 if (!tmp)
1902                 {
1903                         tmp = Py_None;
1904                         inc_refcount = true;
1905                 }
1906                 if (inc_refcount)
1907                         Py_INCREF(tmp);
1908                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1909         }
1910 }
1911
1912 // here we get a python tuple
1913 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1914 //   I = Event Id
1915 //   B = Event Begin Time
1916 //   D = Event Duration
1917 //   T = Event Title
1918 //   S = Event Short Description
1919 //   E = Event Extended Description
1920 //   R = Service Reference
1921 //   N = Service Name
1922 //  the second tuple entry is the MAX matches value
1923 //  the third tuple entry is the type of query
1924 //     0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1925 //     1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1926 //     2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1927 //  when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1928 //   the fourth is the servicereference string
1929 //   the fifth is the eventid
1930 //  when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1931 //   the fourth is the search text
1932 //   the fifth is
1933 //     0 = case sensitive (CASE_CHECK)
1934 //     1 = case insensitive (NO_CASECHECK)
1935
1936 PyObject *eEPGCache::search(ePyObject arg)
1937 {
1938         ePyObject ret;
1939         int descridx = -1;
1940         __u32 descr[512];
1941         int eventid = -1;
1942         const char *argstring=0;
1943         char *refstr=0;
1944         int argcount=0;
1945         int querytype=-1;
1946         bool needServiceEvent=false;
1947         int maxmatches=0;
1948
1949         if (PyTuple_Check(arg))
1950         {
1951                 int tuplesize=PyTuple_Size(arg);
1952                 if (tuplesize > 0)
1953                 {
1954                         ePyObject obj = PyTuple_GET_ITEM(arg,0);
1955                         if (PyString_Check(obj))
1956                         {
1957                                 argcount = PyString_GET_SIZE(obj);
1958                                 argstring = PyString_AS_STRING(obj);
1959                                 for (int i=0; i < argcount; ++i)
1960                                         switch(argstring[i])
1961                                         {
1962                                         case 'S':
1963                                         case 'E':
1964                                         case 'T':
1965                                                 needServiceEvent=true;
1966                                         default:
1967                                                 break;
1968                                         }
1969                         }
1970                         else
1971                         {
1972                                 PyErr_SetString(PyExc_StandardError,
1973                                         "type error");
1974                                 eDebug("tuple arg 0 is not a string");
1975                                 return NULL;
1976                         }
1977                 }
1978                 if (tuplesize > 1)
1979                         maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1980                 if (tuplesize > 2)
1981                 {
1982                         querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1983                         if (tuplesize > 4 && querytype == 0)
1984                         {
1985                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
1986                                 if (PyString_Check(obj))
1987                                 {
1988                                         refstr = PyString_AS_STRING(obj);
1989                                         eServiceReferenceDVB ref(refstr);
1990                                         if (ref.valid())
1991                                         {
1992                                                 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1993                                                 singleLock s(cache_lock);
1994                                                 const eventData *evData = 0;
1995                                                 lookupEventId(ref, eventid, evData);
1996                                                 if (evData)
1997                                                 {
1998                                                         __u8 *data = evData->EITdata;
1999                                                         int tmp = evData->ByteSize-12;
2000                                                         __u32 *p = (__u32*)(data+12);
2001                                                                 // search short and extended event descriptors
2002                                                         while(tmp>0)
2003                                                         {
2004                                                                 __u32 crc = *p++;
2005                                                                 descriptorMap::iterator it =
2006                                                                         eventData::descriptors.find(crc);
2007                                                                 if (it != eventData::descriptors.end())
2008                                                                 {
2009                                                                         __u8 *descr_data = it->second.second;
2010                                                                         switch(descr_data[0])
2011                                                                         {
2012                                                                         case 0x4D ... 0x4E:
2013                                                                                 descr[++descridx]=crc;
2014                                                                         default:
2015                                                                                 break;
2016                                                                         }
2017                                                                 }
2018                                                                 tmp-=4;
2019                                                         }
2020                                                 }
2021                                                 if (descridx<0)
2022                                                         eDebug("event not found");
2023                                         }
2024                                         else
2025                                         {
2026                                                 PyErr_SetString(PyExc_StandardError,
2027                                                         "type error");
2028                                                 eDebug("tuple arg 4 is not a valid service reference string");
2029                                                 return NULL;
2030                                         }
2031                                 }
2032                                 else
2033                                 {
2034                                         PyErr_SetString(PyExc_StandardError,
2035                                         "type error");
2036                                         eDebug("tuple arg 4 is not a string");
2037                                         return NULL;
2038                                 }
2039                         }
2040                         else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2041                         {
2042                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2043                                 if (PyString_Check(obj))
2044                                 {
2045                                         int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2046                                         const char *str = PyString_AS_STRING(obj);
2047                                         int textlen = PyString_GET_SIZE(obj);
2048                                         if (querytype == 1)
2049                                                 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2050                                         else
2051                                                 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2052                                         singleLock s(cache_lock);
2053                                         for (descriptorMap::iterator it(eventData::descriptors.begin());
2054                                                 it != eventData::descriptors.end() && descridx < 511; ++it)
2055                                         {
2056                                                 __u8 *data = it->second.second;
2057                                                 if ( data[0] == 0x4D ) // short event descriptor
2058                                                 {
2059                                                         int title_len = data[5];
2060                                                         if ( querytype == 1 )
2061                                                         {
2062                                                                 if (title_len > textlen)
2063                                                                         continue;
2064                                                                 else if (title_len < textlen)
2065                                                                         continue;
2066                                                                 if ( casetype )
2067                                                                 {
2068                                                                         if ( !strncasecmp((const char*)data+6, str, title_len) )
2069                                                                         {
2070 //                                                                              std::string s((const char*)data+6, title_len);
2071 //                                                                              eDebug("match1 %s %s", str, s.c_str() );
2072                                                                                 descr[++descridx] = it->first;
2073                                                                         }
2074                                                                 }
2075                                                                 else if ( !strncmp((const char*)data+6, str, title_len) )
2076                                                                 {
2077 //                                                                      std::string s((const char*)data+6, title_len);
2078 //                                                                      eDebug("match2 %s %s", str, s.c_str() );
2079                                                                         descr[++descridx] = it->first;
2080                                                                 }
2081                                                         }
2082                                                         else
2083                                                         {
2084                                                                 int idx=0;
2085                                                                 while((title_len-idx) >= textlen)
2086                                                                 {
2087                                                                         if (casetype)
2088                                                                         {
2089                                                                                 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2090                                                                                 {
2091                                                                                         descr[++descridx] = it->first;
2092 //                                                                                      std::string s((const char*)data+6, title_len);
2093 //                                                                                      eDebug("match 3 %s %s", str, s.c_str() );
2094                                                                                         break;
2095                                                                                 }
2096                                                                                 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2097                                                                                 {
2098                                                                                         descr[++descridx] = it->first;
2099 //                                                                                      std::string s((const char*)data+6, title_len);
2100 //                                                                                      eDebug("match 4 %s %s", str, s.c_str() );
2101                                                                                         break;
2102                                                                                 }
2103                                                                         }
2104                                                                         ++idx;
2105                                                                 }
2106                                                         }
2107                                                 }
2108                                         }
2109                                 }
2110                                 else
2111                                 {
2112                                         PyErr_SetString(PyExc_StandardError,
2113                                                 "type error");
2114                                         eDebug("tuple arg 4 is not a string");
2115                                         return NULL;
2116                                 }
2117                         }
2118                         else
2119                         {
2120                                 PyErr_SetString(PyExc_StandardError,
2121                                         "type error");
2122                                 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2123                                 return NULL;
2124                         }
2125                 }
2126                 else
2127                 {
2128                         PyErr_SetString(PyExc_StandardError,
2129                                 "type error");
2130                         eDebug("not enough args in tuple");
2131                         return NULL;
2132                 }
2133         }
2134         else
2135         {
2136                 PyErr_SetString(PyExc_StandardError,
2137                         "type error");
2138                 eDebug("arg 0 is not a tuple");
2139                 return NULL;
2140         }
2141
2142         ASSERT(descridx <= 512);
2143
2144         if (descridx > -1)
2145         {
2146                 int maxcount=maxmatches;
2147                 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2148                 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2149                 // in this case we start searching with the base service
2150                 bool first = ref.valid() ? true : false;
2151                 singleLock s(cache_lock);
2152                 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2153                 while(cit != eventDB.end() && maxcount)
2154                 {
2155                         if ( ref.valid() && !first && cit->first == ref )
2156                         {
2157                                 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2158                                 ++cit;
2159                                 continue;
2160                         }
2161                         ePyObject service_name;
2162                         ePyObject service_reference;
2163                         timeMap &evmap = cit->second.second;
2164                         // check all events
2165                         for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2166                         {
2167                                 int evid = evit->second->getEventID();
2168                                 if ( evid == eventid)
2169                                         continue;
2170                                 __u8 *data = evit->second->EITdata;
2171                                 int tmp = evit->second->ByteSize-12;
2172                                 __u32 *p = (__u32*)(data+12);
2173                                 // check if any of our descriptor used by this event
2174                                 int cnt=-1;
2175                                 while(tmp>0)
2176                                 {
2177                                         __u32 crc32 = *p++;
2178                                         for ( int i=0; i <= descridx; ++i)
2179                                         {
2180                                                 if (descr[i] == crc32)  // found...
2181                                                         ++cnt;
2182                                         }
2183                                         tmp-=4;
2184                                 }
2185                                 if ( (querytype == 0 && cnt == descridx) ||
2186                                          ((querytype == 1 || querytype == 2) && cnt != -1) )
2187                                 {
2188                                         const uniqueEPGKey &service = cit->first;
2189                                         eServiceReference ref =
2190                                                 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2191                                         if (ref.valid())
2192                                         {
2193                                         // create servive event
2194                                                 ePtr<eServiceEvent> ptr;
2195                                                 if (needServiceEvent)
2196                                                 {
2197                                                         lookupEventId(ref, evid, ptr);
2198                                                         if (!ptr)
2199                                                                 eDebug("event not found !!!!!!!!!!!");
2200                                                 }
2201                                         // create service name
2202                                                 if (!service_name && strchr(argstring,'N'))
2203                                                 {
2204                                                         ePtr<iStaticServiceInformation> sptr;
2205                                                         eServiceCenterPtr service_center;
2206                                                         eServiceCenter::getPrivInstance(service_center);
2207                                                         if (service_center)
2208                                                         {
2209                                                                 service_center->info(ref, sptr);
2210                                                                 if (sptr)
2211                                                                 {
2212                                                                         std::string name;
2213                                                                         sptr->getName(ref, name);
2214                                                                         if (name.length())
2215                                                                                 service_name = PyString_FromString(name.c_str());
2216                                                                 }
2217                                                         }
2218                                                         if (!service_name)
2219                                                                 service_name = PyString_FromString("<n/a>");
2220                                                 }
2221                                         // create servicereference string
2222                                                 if (!service_reference && strchr(argstring,'R'))
2223                                                         service_reference = PyString_FromString(ref.toString().c_str());
2224                                         // create list
2225                                                 if (!ret)
2226                                                         ret = PyList_New(0);
2227                                         // create tuple
2228                                                 ePyObject tuple = PyTuple_New(argcount);
2229                                         // fill tuple
2230                                                 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2231                                                 PyList_Append(ret, tuple);
2232                                                 Py_DECREF(tuple);
2233                                                 --maxcount;
2234                                         }
2235                                 }
2236                         }
2237                         if (service_name)
2238                                 Py_DECREF(service_name);
2239                         if (service_reference)
2240                                 Py_DECREF(service_reference);
2241                         if (first)
2242                         {
2243                                 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2244                                 first=false;
2245                                 cit=eventDB.begin();
2246                         }
2247                         else
2248                                 ++cit;
2249                 }
2250         }
2251
2252         if (!ret)
2253                 Py_RETURN_NONE;
2254
2255         return ret;
2256 }
2257
2258 #ifdef ENABLE_PRIVATE_EPG
2259 #include <dvbsi++/descriptor_tag.h>
2260 #include <dvbsi++/unknown_descriptor.h>
2261 #include <dvbsi++/private_data_specifier_descriptor.h>
2262
2263 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2264 {
2265         ePtr<eTable<ProgramMapSection> > ptr;
2266         if (!pmthandler->getPMT(ptr) && ptr)
2267         {
2268                 std::vector<ProgramMapSection*>::const_iterator i;
2269                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2270                 {
2271                         const ProgramMapSection &pmt = **i;
2272
2273                         ElementaryStreamInfoConstIterator es;
2274                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2275                         {
2276                                 int tmp=0;
2277                                 switch ((*es)->getType())
2278                                 {
2279                                 case 0x05: // private
2280                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2281                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2282                                         {
2283                                                 switch ((*desc)->getTag())
2284                                                 {
2285                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2286                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2287                                                                         tmp |= 1;
2288                                                                 break;
2289                                                         case 0x90:
2290                                                         {
2291                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2292                                                                 int descr_len = descr->getLength();
2293                                                                 if (descr_len == 4)
2294                                                                 {
2295                                                                         uint8_t data[descr_len+2];
2296                                                                         descr->writeToBuffer(data);
2297                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2298                                                                                 tmp |= 2;
2299                                                                 }
2300                                                                 break;
2301                                                         }
2302                                                         default:
2303                                                                 break;
2304                                                 }
2305                                         }
2306                                 default:
2307                                         break;
2308                                 }
2309                                 if (tmp==3)
2310                                 {
2311                                         eServiceReferenceDVB ref;
2312                                         if (!pmthandler->getServiceReference(ref))
2313                                         {
2314                                                 int pid = (*es)->getPid();
2315                                                 messages.send(Message(Message::got_private_pid, ref, pid));
2316                                                 return;
2317                                         }
2318                                 }
2319                         }
2320                 }
2321         }
2322         else
2323                 eDebug("PMTready but no pmt!!");
2324 }
2325
2326 struct date_time
2327 {
2328         __u8 data[5];
2329         time_t tm;
2330         date_time( const date_time &a )
2331         {
2332                 memcpy(data, a.data, 5);
2333                 tm = a.tm;
2334         }
2335         date_time( const __u8 data[5])
2336         {
2337                 memcpy(this->data, data, 5);
2338                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2339         }
2340         date_time()
2341         {
2342         }
2343         const __u8& operator[](int pos) const
2344         {
2345                 return data[pos];
2346         }
2347 };
2348
2349 struct less_datetime
2350 {
2351         bool operator()( const date_time &a, const date_time &b ) const
2352         {
2353                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2354         }
2355 };
2356
2357 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
2358 {
2359         contentMap &content_time_table = content_time_tables[current_service];
2360         singleLock s(cache_lock);
2361         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2362         eventMap &evMap = eventDB[current_service].first;
2363         timeMap &tmMap = eventDB[current_service].second;
2364         int ptr=8;
2365         int content_id = data[ptr++] << 24;
2366         content_id |= data[ptr++] << 16;
2367         content_id |= data[ptr++] << 8;
2368         content_id |= data[ptr++];
2369
2370         contentTimeMap &time_event_map =
2371                 content_time_table[content_id];
2372         for ( contentTimeMap::iterator it( time_event_map.begin() );
2373                 it != time_event_map.end(); ++it )
2374         {
2375                 eventMap::iterator evIt( evMap.find(it->second.second) );
2376                 if ( evIt != evMap.end() )
2377                 {
2378                         delete evIt->second;
2379                         evMap.erase(evIt);
2380                 }
2381                 tmMap.erase(it->second.first);
2382         }
2383         time_event_map.clear();
2384
2385         __u8 duration[3];
2386         memcpy(duration, data+ptr, 3);
2387         ptr+=3;
2388         int duration_sec =
2389                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2390
2391         const __u8 *descriptors[65];
2392         const __u8 **pdescr = descriptors;
2393
2394         int descriptors_length = (data[ptr++]&0x0F) << 8;
2395         descriptors_length |= data[ptr++];
2396         while ( descriptors_length > 0 )
2397         {
2398                 int descr_type = data[ptr];
2399                 int descr_len = data[ptr+1];
2400                 descriptors_length -= (descr_len+2);
2401                 if ( descr_type == 0xf2 )
2402                 {
2403                         ptr+=2;
2404                         int tsid = data[ptr++] << 8;
2405                         tsid |= data[ptr++];
2406                         int onid = data[ptr++] << 8;
2407                         onid |= data[ptr++];
2408                         int sid = data[ptr++] << 8;
2409                         sid |= data[ptr++];
2410
2411 // WORKAROUND for wrong transmitted epg data (01.08.2006)
2412                         if ( onid == 0x85 )
2413                         {
2414                                 switch( (tsid << 16) | sid )
2415                                 {
2416                                         case 0x01030b: sid = 0x1b; tsid = 4; break;  // Premiere Win
2417                                         case 0x0300f0: sid = 0xe0; tsid = 2; break;
2418                                         case 0x0300f1: sid = 0xe1; tsid = 2; break;
2419                                         case 0x0300f5: sid = 0xdc; break;
2420                                         case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2421                                         case 0x1100d3: sid = 0xe3; break;
2422                                 }
2423                         }
2424 ////////////////////////////////////////////
2425
2426                         uniqueEPGKey service( sid, onid, tsid );
2427                         descr_len -= 6;
2428                         while( descr_len > 0 )
2429                         {
2430                                 __u8 datetime[5];
2431                                 datetime[0] = data[ptr++];
2432                                 datetime[1] = data[ptr++];
2433                                 int tmp_len = data[ptr++];
2434                                 descr_len -= 3;
2435                                 while( tmp_len > 0 )
2436                                 {
2437                                         memcpy(datetime+2, data+ptr, 3);
2438                                         ptr+=3;
2439                                         descr_len -= 3;
2440                                         tmp_len -= 3;
2441                                         start_times[datetime].push_back(service);
2442                                 }
2443                         }
2444                 }
2445                 else
2446                 {
2447                         *pdescr++=data+ptr;
2448                         ptr += 2;
2449                         ptr += descr_len;
2450                 }
2451         }
2452         ASSERT(pdescr <= &descriptors[65])
2453         __u8 event[4098];
2454         eit_event_struct *ev_struct = (eit_event_struct*) event;
2455         ev_struct->running_status = 0;
2456         ev_struct->free_CA_mode = 1;
2457         memcpy(event+7, duration, 3);
2458         ptr = 12;
2459         const __u8 **d=descriptors;
2460         while ( d < pdescr )
2461         {
2462                 memcpy(event+ptr, *d, ((*d)[1])+2);
2463                 ptr+=(*d++)[1];
2464                 ptr+=2;
2465         }
2466         ASSERT(ptr <= 4098);
2467         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2468         {
2469                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2470                 if ( (it->first.tm + duration_sec) < now )
2471                         continue;
2472                 memcpy(event+2, it->first.data, 5);
2473                 int bptr = ptr;
2474                 int cnt=0;
2475                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2476                 {
2477                         event[bptr++] = 0x4A;
2478                         __u8 *len = event+(bptr++);
2479                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
2480                         event[bptr++] = (i->tsid & 0xFF);
2481                         event[bptr++] = (i->onid & 0xFF00) >> 8;
2482                         event[bptr++] = (i->onid & 0xFF);
2483                         event[bptr++] = (i->sid & 0xFF00) >> 8;
2484                         event[bptr++] = (i->sid & 0xFF);
2485                         event[bptr++] = 0xB0;
2486                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2487                         *len = ((event+bptr) - len)-1;
2488                 }
2489                 int llen = bptr - 12;
2490                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2491                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2492
2493                 time_t stime = it->first.tm;
2494                 while( tmMap.find(stime) != tmMap.end() )
2495                         ++stime;
2496                 event[6] += (stime - it->first.tm);
2497                 __u16 event_id = 0;
2498                 while( evMap.find(event_id) != evMap.end() )
2499                         ++event_id;
2500                 event[0] = (event_id & 0xFF00) >> 8;
2501                 event[1] = (event_id & 0xFF);
2502                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2503                 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2504                 evMap[event_id] = d;
2505                 tmMap[stime] = d;
2506         }
2507 }
2508
2509 void eEPGCache::channel_data::startPrivateReader()
2510 {
2511         eDVBSectionFilterMask mask;
2512         memset(&mask, 0, sizeof(mask));
2513         mask.pid = m_PrivatePid;
2514         mask.flags = eDVBSectionFilterMask::rfCRC;
2515         mask.data[0] = 0xA0;
2516         mask.mask[0] = 0xFF;
2517         eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2518         if (m_PrevVersion != -1)
2519         {
2520                 mask.data[3] = m_PrevVersion << 1;
2521                 mask.mask[3] = 0x3E;
2522                 mask.mode[3] = 0x3E;
2523         }
2524         seenPrivateSections.clear();
2525         if (!m_PrivateConn)
2526                 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2527         m_PrivateReader->start(mask);
2528 }
2529
2530 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2531 {
2532         if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2533         {
2534                 cache->privateSectionRead(m_PrivateService, data);
2535                 seenPrivateSections.insert(data[6]);
2536         }
2537         if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2538         {
2539                 eDebug("[EPGC] private finished");
2540                 eDVBChannelID chid = channel->getChannelID();
2541                 int tmp = chid.original_network_id.get();
2542                 tmp |= 0x80000000; // we use highest bit as private epg indicator
2543                 chid.original_network_id = tmp;
2544                 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2545                 m_PrevVersion = (data[5] & 0x3E) >> 1;
2546                 startPrivateReader();
2547         }
2548 }
2549
2550 #endif // ENABLE_PRIVATE_EPG
2551
2552 #ifdef ENABLE_MHW_EPG
2553 void eEPGCache::channel_data::cleanup()
2554 {
2555         m_channels.clear();
2556         m_themes.clear();
2557         m_titles.clear();
2558         m_program_ids.clear();
2559 }
2560
2561 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2562 {
2563         // Names in mhw structs are not strings as they are not '\0' terminated.
2564         // This function converts the mhw name into a string.
2565         // Constraint: "length of out" = "length of in" + 1.
2566         int i;
2567         for ( i=0; i < len_in; i++ )
2568                 out[i] = in[i];
2569
2570         i = len_in - 1;
2571         while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2572                 i--;
2573
2574         out[i+1] = 0;
2575         return out;
2576 }
2577
2578 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2579 // For time of day
2580 {
2581         return_time[0] = toBCD( hours );
2582         return_time[1] = toBCD( minutes );
2583         return_time[2] = 0;
2584 }
2585
2586 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2587 {
2588         timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2589 }
2590
2591 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2592 // For date plus time of day
2593 {
2594         // Remove offset in mhw time.
2595         __u8 local_hours = hours;
2596         if ( hours >= 16 )
2597                 local_hours -= 4;
2598         else if ( hours >= 8 )
2599                 local_hours -= 2;
2600
2601         // As far as we know all mhw time data is sent in central Europe time zone.
2602         // So, temporarily set timezone to western europe
2603         time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2604
2605         char *old_tz = getenv( "TZ" );
2606         putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2607         tzset();
2608
2609         tm localnow;
2610         localtime_r(&dt, &localnow);
2611
2612         if (day == 7)
2613                 day = 0;
2614         if ( day + 1 < localnow.tm_wday )               // day + 1 to prevent old events to show for next week.
2615                 day += 7;
2616         if (local_hours <= 5)
2617                 day++;
2618
2619         dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2620         dt += 3600*(local_hours - localnow.tm_hour);  // Shift dt to the recording hour.
2621
2622         tm recdate;
2623         gmtime_r( &dt, &recdate );   // This will also take care of DST.
2624
2625         if ( old_tz == NULL )
2626                 unsetenv( "TZ" );
2627         else
2628                 putenv( old_tz );
2629         tzset();
2630
2631         // Calculate MJD according to annex in ETSI EN 300 468
2632         int l=0;
2633         if ( recdate.tm_mon <= 1 )      // Jan or Feb
2634                 l=1;
2635         int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2636                 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2637
2638         return_time[0] = (mjd & 0xFF00)>>8;
2639         return_time[1] = mjd & 0xFF;
2640
2641         timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2642 }
2643
2644 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2645 // data is borrowed from calling proc to save memory space.
2646 {
2647         __u8 name[34];
2648         // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2649         bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2650                 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2651
2652         eit_t *packet = (eit_t *) data;
2653         packet->table_id = 0x50;
2654         packet->section_syntax_indicator = 1;
2655         packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2656         packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2657         packet->version_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2658         packet->current_next_indicator = 0;
2659         packet->section_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2660         packet->last_section_number = 0;        // eEPGCache::sectionRead() will dig this for the moment
2661         packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2662         packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2663         packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2664         packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2665         packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2666         packet->segment_last_table_id = 0x50;
2667
2668         __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2669         std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2670         int prog_title_length = prog_title.length();
2671
2672         int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2673                 prog_title_length + 1;
2674
2675         eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2676         event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2677         event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2678
2679         if (isMHW2)
2680         {
2681                 u_char *data = (u_char*) event_data;
2682                 data[2] = itTitle->second.mhw2_mjd_hi;
2683                 data[3] = itTitle->second.mhw2_mjd_lo;
2684                 data[4] = itTitle->second.mhw2_hours;
2685                 data[5] = itTitle->second.mhw2_minutes;
2686                 data[6] = itTitle->second.mhw2_seconds;
2687                 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2688         }
2689         else
2690         {
2691                 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2692                 (u_char *) event_data + 2 );
2693                 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2694         }
2695
2696         event_data->running_status = 0;
2697         event_data->free_CA_mode = 0;
2698         int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2699
2700         eit_short_event_descriptor_struct *short_event_descriptor =
2701                 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2702         short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2703         short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2704                 prog_title_length - 1;
2705         short_event_descriptor->language_code_1 = 'e';
2706         short_event_descriptor->language_code_2 = 'n';
2707         short_event_descriptor->language_code_3 = 'g';
2708         short_event_descriptor->event_name_length = prog_title_length;
2709         u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2710         memcpy(event_name, prog_title.c_str(), prog_title_length);
2711
2712         // Set text length
2713         event_name[prog_title_length] = 0;
2714
2715         if ( sumText.length() > 0 )
2716         // There is summary info
2717         {
2718                 unsigned int sum_length = sumText.length();
2719                 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2720                 // Store summary in short event descriptor
2721                 {
2722                         // Increase all relevant lengths
2723                         event_name[prog_title_length] = sum_length;
2724                         short_event_descriptor->descriptor_length += sum_length;
2725                         packet_length += sum_length;
2726                         descr_ll += sum_length;
2727                         sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2728                 }
2729                 else
2730                 // Store summary in extended event descriptors
2731                 {
2732                         int remaining_sum_length = sumText.length();
2733                         int nbr_descr = int(remaining_sum_length/247) + 1;
2734                         for ( int i=0; i < nbr_descr; i++)
2735                         // Loop once per extended event descriptor
2736                         {
2737                                 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2738                                 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2739                                 remaining_sum_length -= sum_length;
2740                                 packet_length += 8 + sum_length;
2741                                 descr_ll += 8 + sum_length;
2742
2743                                 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2744                                 ext_event_descriptor->descriptor_length = sum_length + 6;
2745                                 ext_event_descriptor->descriptor_number = i;
2746                                 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2747                                 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2748                                 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2749                                 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2750                                 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2751                                 the_text[-2] = 0;
2752                                 the_text[-1] = sum_length;
2753                                 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2754                         }
2755                 }
2756         }
2757
2758         if (!isMHW2)
2759         {
2760                 // Add content descriptor
2761                 u_char *descriptor = (u_char *) data + packet_length;
2762                 packet_length += 4;
2763                 descr_ll += 4;
2764
2765                 int content_id = 0;
2766                 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2767                 if ( content_descr.find( "FILM" ) != std::string::npos )
2768                         content_id = 0x10;
2769                 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2770                         content_id = 0x40;
2771
2772                 descriptor[0] = 0x54;
2773                 descriptor[1] = 2;
2774                 descriptor[2] = content_id;
2775                 descriptor[3] = 0;
2776         }
2777
2778         event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2779         event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2780
2781         packet->section_length_hi =  ((packet_length - 3)&0xf00)>>8;
2782         packet->section_length_lo =  (packet_length - 3)&0xff;
2783
2784         // Feed the data to eEPGCache::sectionRead()
2785         cache->sectionRead( data, MHW, this );
2786 }
2787
2788 void eEPGCache::channel_data::startTimeout(int msec)
2789 {
2790         m_MHWTimeoutTimer.start(msec,true);
2791         m_MHWTimeoutet=false;
2792 }
2793
2794 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2795 {
2796         m_MHWFilterMask.pid = pid;
2797         m_MHWFilterMask.data[0] = tid;
2798         m_MHWReader->start(m_MHWFilterMask);
2799 //      eDebug("start 0x%02x 0x%02x", pid, tid);
2800 }
2801
2802 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2803 {
2804         m_MHWFilterMask2.pid = pid;
2805         m_MHWFilterMask2.data[0] = tid;
2806         if (ext != -1)
2807         {
2808                 m_MHWFilterMask2.data[1] = ext;
2809                 m_MHWFilterMask2.mask[1] = 0xFF;
2810 //              eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2811         }
2812         else
2813         {
2814                 m_MHWFilterMask2.data[1] = 0;
2815                 m_MHWFilterMask2.mask[1] = 0;
2816 //              eDebug("start 0x%02x 0x%02x", pid, tid);
2817         }
2818         m_MHWReader2->start(m_MHWFilterMask2);
2819 }
2820
2821 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2822 {
2823         if ( m_MHWReader2 )
2824                 m_MHWReader2->stop();
2825
2826         if ( state > 1 || // aborted
2827                 // have si data.. so we dont read mhw data
2828                 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2829         {
2830                 eDebug("[EPGC] mhw aborted %d", state);
2831         }
2832         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2833         // Channels table
2834         {
2835                 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2836                 int record_size = sizeof( mhw_channel_name_t );
2837                 int nbr_records = int (len/record_size);
2838
2839                 for ( int i = 0; i < nbr_records; i++ )
2840                 {
2841                         mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2842                         m_channels.push_back( *channel );
2843                 }
2844                 haveData |= MHW;
2845
2846                 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2847
2848                 // Channels table has been read, start reading the themes table.
2849                 startMHWReader(0xD3, 0x92);
2850                 return;
2851         }
2852         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2853         // Themes table
2854         {
2855                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2856                 int record_size = sizeof( mhw_theme_name_t );
2857                 int nbr_records = int (len/record_size);
2858                 int idx_ptr = 0;
2859                 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2860                 __u8 idx = 0;
2861                 __u8 sub_idx = 0;
2862                 for ( int i = 0; i < nbr_records; i++ )
2863                 {
2864                         mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2865                         if ( i >= next_idx )
2866                         {
2867                                 idx = (idx_ptr<<4);
2868                                 idx_ptr++;
2869                                 next_idx = (__u8) *(data + 3 + idx_ptr);
2870                                 sub_idx = 0;
2871                         }
2872                         else
2873                                 sub_idx++;
2874
2875                         m_themes[idx+sub_idx] = *theme;
2876                 }
2877                 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2878                 // Themes table has been read, start reading the titles table.
2879                 startMHWReader(0xD2, 0x90);
2880                 startTimeout(4000);
2881                 return;
2882         }
2883         else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2884         // Titles table
2885         {
2886                 mhw_title_t *title = (mhw_title_t*) data;
2887
2888                 if ( title->channel_id == 0xFF )        // Separator
2889                         return; // Continue reading of the current table.
2890                 else
2891                 {
2892                         // Create unique key per title
2893                         __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2894                                 (title->ms.minutes);
2895                         __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2896                                 ((title->program_id_ml)<<8)|(title->program_id_lo);
2897
2898                         if ( m_titles.find( title_id ) == m_titles.end() )
2899                         {
2900                                 startTimeout(4000);
2901                                 title->mhw2_mjd_hi = 0;
2902                                 title->mhw2_mjd_lo = 0;
2903                                 title->mhw2_duration_hi = 0;
2904                                 title->mhw2_duration_lo = 0;
2905                                 m_titles[ title_id ] = *title;
2906                                 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2907                                         // program_ids will be used to gather summaries.
2908                                         m_program_ids[ program_id ] = title_id;
2909                                 return; // Continue reading of the current table.
2910                         }
2911                         else if (!checkTimeout())
2912                                 return;
2913                 }
2914                 if ( !m_program_ids.empty())
2915                 {
2916                         // Titles table has been read, there are summaries to read.
2917                         // Start reading summaries, store corresponding titles on the fly.
2918                         startMHWReader(0xD3, 0x90);
2919                         eDebug("[EPGC] mhw %d titles(%d with summary) found",
2920                                 m_titles.size(),
2921                                 m_program_ids.size());
2922                         startTimeout(4000);
2923                         return;
2924                 }
2925         }
2926         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2927         // Summaries table
2928         {
2929                 mhw_summary_t *summary = (mhw_summary_t*) data;
2930
2931                 // Create unique key per record
2932                 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2933                         ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2934                 int len = ((data[1]&0xf)<<8) + data[2];
2935
2936                 // ugly workaround to convert const __u8* to char*
2937                 char *tmp=0;
2938                 memcpy(&tmp, &data, sizeof(void*));
2939                 tmp[len+3] = 0; // Terminate as a string.
2940
2941                 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2942                 if ( itProgid == m_program_ids.end() )
2943                 { /*    This part is to prevent to looping forever if some summaries are not received yet.
2944                         There is a timeout of 4 sec. after the last successfully read summary. */
2945                         if (!m_program_ids.empty() && !checkTimeout())
2946                                 return; // Continue reading of the current table.
2947                 }
2948                 else
2949                 {
2950                         std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2951
2952                         unsigned int pos=0;
2953                         while((pos = the_text.find("\r\n")) != std::string::npos)
2954                                 the_text.replace(pos, 2, " ");
2955
2956                         // Find corresponding title, store title and summary in epgcache.
2957                         std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2958                         if ( itTitle != m_titles.end() )
2959                         {
2960                                 startTimeout(4000);
2961                                 storeTitle( itTitle, the_text, data );
2962                                 m_titles.erase( itTitle );
2963                         }
2964                         m_program_ids.erase( itProgid );
2965                         if ( !m_program_ids.empty() )
2966                                 return; // Continue reading of the current table.
2967                 }
2968         }
2969         eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
2970                 eDVBLocalTimeHandler::getInstance()->nowTime(),
2971                 m_program_ids.size());
2972         // Summaries have been read, titles that have summaries have been stored.
2973         // Now store titles that do not have summaries.
2974         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
2975                 storeTitle( itTitle, "", data );
2976         isRunning &= ~MHW;
2977         m_MHWConn=0;
2978         if ( m_MHWReader )
2979                 m_MHWReader->stop();
2980         if (haveData)
2981                 finishEPG();
2982 }
2983
2984 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
2985 {
2986         int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
2987
2988         if ( m_MHWReader )
2989                 m_MHWReader->stop();
2990
2991         if ( state > 1 || // aborted
2992                 // have si data.. so we dont read mhw data
2993                 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
2994         {
2995                 eDebug("[EPGC] mhw2 aborted %d", state);
2996         }
2997         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
2998         // Channels table
2999         {
3000                 int num_channels = data[120];
3001                 if(dataLen > 120)
3002                 {
3003                         int ptr = 121 + 6 * num_channels;
3004                         if( dataLen > ptr )
3005                         {
3006                                 for( int chid = 0; chid < num_channels; ++chid )
3007                                 {
3008                                         ptr += ( data[ptr] & 0x0f ) + 1;
3009                                         if( dataLen < ptr )
3010                                                 goto abort;
3011                                 }
3012                         }
3013                         else
3014                                 goto abort;
3015                 }
3016                 else
3017                         goto abort;
3018                 // data seems consistent...
3019                 const __u8 *tmp = data+121;
3020                 for (int i=0; i < num_channels; ++i)
3021                 {
3022                         mhw_channel_name_t channel;
3023                         channel.transport_stream_id_hi = *(tmp++);
3024                         channel.transport_stream_id_lo = *(tmp++);
3025                         channel.channel_id_hi = *(tmp++);
3026                         channel.channel_id_lo = *(tmp++);
3027 #warning FIXME hardcoded network_id in mhw2 epg
3028                         channel.network_id_hi = 0; // hardcoded astra 19.2
3029                         channel.network_id_lo = 1;
3030                         m_channels.push_back(channel);
3031                         tmp+=2;
3032                 }
3033                 for (int i=0; i < num_channels; ++i)
3034                 {
3035                         mhw_channel_name_t &channel = m_channels[i];
3036                         int channel_name_len=*(tmp++)&0x0f;
3037                         int x=0;
3038                         for (; x < channel_name_len; ++x)
3039                                 channel.name[x]=*(tmp++);
3040                         channel.name[x+1]=0;
3041                 }
3042                 haveData |= MHW;
3043                 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3044         }
3045         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3046         {
3047                 // Themes table
3048                 eDebug("[EPGC] mhw2 themes nyi");
3049         }
3050         else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3051         // Titles table
3052         {
3053                 int pos=18;
3054                 bool valid=true;
3055                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3056                 bool finish=false;
3057                 if(data[dataLen-1] != 0xff)
3058                         return;
3059                 while( pos < dataLen )
3060                 {
3061                         valid = false;
3062                         pos += 7;
3063                         if( pos < dataLen )
3064                         {
3065                                 pos += 3;
3066                                 if( pos < dataLen )
3067                                 {
3068                                         if( data[pos] > 0xc0 )
3069                                         {
3070                                                 pos += ( data[pos] - 0xc0 );
3071                                                 pos += 4;
3072                                                 if( pos < dataLen )
3073                                                 {
3074                                                         if( data[pos] == 0xff )
3075                                                         {
3076                                                                 ++pos;
3077                                                                 valid = true;
3078                                                         }
3079                                                 }
3080                                         }
3081                                 }
3082                         }
3083                         if( !valid )
3084                         {
3085                                 if (checkTimeout())
3086                                         goto start_summary;
3087                                 return;
3088                         }
3089                 }
3090                 // data seems consistent...
3091                 mhw_title_t title;
3092                 pos = 18;
3093                 while (pos < len)
3094                 {
3095                         title.channel_id = data[pos]+1;
3096                         title.program_id_ml = data[pos+1];
3097                         title.program_id_lo = data[pos+2];
3098                         title.mhw2_mjd_hi = data[pos+3];
3099                         title.mhw2_mjd_lo = data[pos+4];
3100                         title.mhw2_hours = data[pos+5];
3101                         title.mhw2_minutes = data[pos+6];
3102                         title.mhw2_seconds = data[pos+7];
3103                         int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3104                         title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3105                         title.mhw2_duration_lo = duration&0xFF;
3106                         __u8 slen = data[pos+10] & 0x3f;
3107                         __u8 *dest = ((__u8*)title.title)-4;
3108                         memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3109                         memset(dest+slen, 0x20, 33-slen);
3110                         pos += 11 + slen;
3111 //                      not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3112                         __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3113
3114                         // Create unique key per title
3115                         __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3116
3117 //                      eDebug("program_id: %08x, %s", program_id,
3118 //                              std::string((const char *)title.title, (int)(slen > 23 ? 23 : slen)).c_str());
3119
3120                         pos += 4;
3121
3122                         if ( m_titles.find( title_id ) == m_titles.end() )
3123                         {
3124                                 startTimeout(4000);
3125                                 m_titles[ title_id ] = title;
3126                                 if (summary_id != 0xFFFF &&  // no summary avail
3127                                         m_program_ids.find(summary_id) == m_program_ids.end())
3128                                 {
3129                                         m_program_ids[ summary_id ] = title_id;
3130                                 }
3131                         }
3132                         else
3133                         {
3134                                 if ( !checkTimeout() )
3135                                         continue;       // Continue reading of the current table.
3136                                 finish=true;
3137                                 break;
3138                         }
3139                 }
3140 start_summary:
3141                 if (finish)
3142                 {
3143                         eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3144                         if (!m_program_ids.empty())
3145                         {
3146                                 // Titles table has been read, there are summaries to read.
3147                                 // Start reading summaries, store corresponding titles on the fly.
3148                                 startMHWReader2(0x236, 0x96);
3149                                 startTimeout(4000);
3150                                 return;
3151                         }
3152                 }
3153                 else
3154                         return;
3155         }
3156         else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3157         // Summaries table
3158         {
3159                 int len, loop, pos, lenline;
3160                 bool valid;
3161                 valid = true;
3162                 if( dataLen > 18 )
3163                 {
3164                         loop = data[12];
3165                         pos = 13 + loop;
3166                         if( dataLen > pos )
3167                         {
3168                                 loop = data[pos] & 0x0f;
3169                                 pos += 1;
3170                                 if( dataLen > pos )
3171                                 {
3172                                         len = 0;
3173                                         for( ; loop > 0; --loop )
3174                                         {
3175                                                 if( dataLen > (pos+len) )
3176                                                 {
3177                                                         lenline = data[pos+len];
3178                                                         len += lenline + 1;
3179                                                 }
3180                                                 else
3181                                                         valid=false;
3182                                         }
3183                                 }
3184                         }
3185                 }
3186                 else if (!checkTimeout())
3187                         return;  // continue reading
3188                 if (valid && !checkTimeout())
3189                 {
3190                         // data seems consistent...
3191                         __u32 summary_id = (data[3]<<8)|data[4];
3192
3193                         // ugly workaround to convert const __u8* to char*
3194                         char *tmp=0;
3195                         memcpy(&tmp, &data, sizeof(void*));
3196
3197                         len = 0;
3198                         loop = data[12];
3199                         pos = 13 + loop;
3200                         loop = tmp[pos] & 0x0f;
3201                         pos += 1;
3202                         for( ; loop > 0; loop -- )
3203                         {
3204                                 lenline = tmp[pos+len];
3205                                 tmp[pos+len] = ' ';
3206                                 len += lenline + 1;
3207                         }
3208                         if( len > 0 )
3209                             tmp[pos+len] = 0;
3210                         else
3211                                 tmp[pos+1] = 0;
3212
3213                         std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( summary_id ) );
3214                         if ( itProgid == m_program_ids.end() )
3215                         { /*    This part is to prevent to looping forever if some summaries are not received yet.
3216                                 There is a timeout of 4 sec. after the last successfully read summary. */
3217         
3218                                 if ( !m_program_ids.empty() && !checkTimeout() )
3219                                         return; // Continue reading of the current table.
3220                         }
3221                         else
3222                         {
3223                                 startTimeout(4000);
3224                                 std::string the_text = (char *) (data + pos + 1);
3225
3226                                 // Find corresponding title, store title and summary in epgcache.
3227                                 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3228                                 if ( itTitle != m_titles.end() )
3229                                 {
3230                                         storeTitle( itTitle, the_text, data );
3231                                         m_titles.erase( itTitle );
3232                                 }
3233                                 m_program_ids.erase( itProgid );
3234                                 if ( !m_program_ids.empty() )
3235                                         return; // Continue reading of the current table.
3236                         }
3237                 }
3238         }
3239         if (isRunning & eEPGCache::MHW)
3240         {
3241                 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3242                 {
3243                         // Channels table has been read, start reading the themes table.
3244                         startMHWReader2(0x231, 0xC8, 1);
3245                         return;
3246                 }
3247                 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3248                 {
3249                         // Themes table has been read, start reading the titles table.
3250                         startMHWReader2(0x234, 0xe6);
3251                         return;
3252                 }
3253                 else
3254                 {
3255                         // Summaries have been read, titles that have summaries have been stored.
3256                         // Now store titles that do not have summaries.
3257                         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3258                                 storeTitle( itTitle, "", data );
3259                         eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3260                                 eDVBLocalTimeHandler::getInstance()->nowTime(),
3261                                 m_program_ids.size());
3262                 }
3263         }
3264 abort:
3265         isRunning &= ~MHW;
3266         m_MHWConn2=0;
3267         if ( m_MHWReader2 )
3268                 m_MHWReader2->stop();
3269         if (haveData)
3270                 finishEPG();
3271 }
3272 #endif