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