fix eEPGCache::search
[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                                         int onid = chid.original_network_id.get();
770                                         onid |= 0x80000000;  // we use highest bit as private epg indicator
771                                         chid.original_network_id = onid;
772                                         updateMap::iterator It = channelLastUpdated.find( chid );
773                                         int update = ( It != channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
774                                         if (update < ZAP_DELAY)
775                                                 update = ZAP_DELAY;
776                                         data->startPrivateTimer.start(update, 1);
777                                         if (update >= 60000)
778                                                 eDebug("[EPGC] next private update in %i min", update/60000);
779                                         else if (update >= 1000)
780                                                 eDebug("[EPGC] next private update in %i sec", update/1000);
781                                         break;
782                                 }
783                         }
784                         break;
785                 }
786 #endif
787                 case Message::timeChanged:
788                         cleanLoop();
789                         break;
790                 default:
791                         eDebug("unhandled EPGCache Message!!");
792                         break;
793         }
794 }
795
796 void eEPGCache::thread()
797 {
798         hasStarted();
799         nice(4);
800         load();
801         cleanLoop();
802         runLoop();
803         save();
804 }
805
806 void eEPGCache::load()
807 {
808         singleLock s(cache_lock);
809         FILE *f = fopen("/hdd/epg.dat", "r");
810         if (f)
811         {
812                 int size=0;
813                 int cnt=0;
814 #if 0
815                 unsigned char md5_saved[16];
816                 unsigned char md5[16];
817                 bool md5ok=false;
818
819                 if (!md5_file("/hdd/epg.dat", 1, md5))
820                 {
821                         FILE *f = fopen("/hdd/epg.dat.md5", "r");
822                         if (f)
823                         {
824                                 fread( md5_saved, 16, 1, f);
825                                 fclose(f);
826                                 if ( !memcmp(md5_saved, md5, 16) )
827                                         md5ok=true;
828                         }
829                 }
830                 if ( md5ok )
831 #endif
832                 {
833                         unsigned int magic=0;
834                         fread( &magic, sizeof(int), 1, f);
835                         if (magic != 0x98765432)
836                         {
837                                 eDebug("[EPGC] epg file has incorrect byte order.. dont read it");
838                                 fclose(f);
839                                 return;
840                         }
841                         char text1[13];
842                         fread( text1, 13, 1, f);
843                         if ( !strncmp( text1, "ENIGMA_EPG_V5", 13) )
844                         {
845                                 fread( &size, sizeof(int), 1, f);
846                                 while(size--)
847                                 {
848                                         uniqueEPGKey key;
849                                         eventMap evMap;
850                                         timeMap tmMap;
851                                         int size=0;
852                                         fread( &key, sizeof(uniqueEPGKey), 1, f);
853                                         fread( &size, sizeof(int), 1, f);
854                                         while(size--)
855                                         {
856                                                 __u8 len=0;
857                                                 __u8 type=0;
858                                                 eventData *event=0;
859                                                 fread( &type, sizeof(__u8), 1, f);
860                                                 fread( &len, sizeof(__u8), 1, f);
861                                                 event = new eventData(0, len, type);
862                                                 event->EITdata = new __u8[len];
863                                                 eventData::CacheSize+=len;
864                                                 fread( event->EITdata, len, 1, f);
865                                                 evMap[ event->getEventID() ]=event;
866                                                 tmMap[ event->getStartTime() ]=event;
867                                                 ++cnt;
868                                         }
869                                         eventDB[key]=std::pair<eventMap,timeMap>(evMap,tmMap);
870                                 }
871                                 eventData::load(f);
872                                 eDebug("[EPGC] %d events read from /hdd/epg.dat", cnt);
873 #ifdef ENABLE_PRIVATE_EPG
874                                 char text2[11];
875                                 fread( text2, 11, 1, f);
876                                 if ( !strncmp( text2, "PRIVATE_EPG", 11) )
877                                 {
878                                         size=0;
879                                         fread( &size, sizeof(int), 1, f);
880                                         while(size--)
881                                         {
882                                                 int size=0;
883                                                 uniqueEPGKey key;
884                                                 fread( &key, sizeof(uniqueEPGKey), 1, f);
885                                                 eventMap &evMap=eventDB[key].first;
886                                                 fread( &size, sizeof(int), 1, f);
887                                                 while(size--)
888                                                 {
889                                                         int size;
890                                                         int content_id;
891                                                         fread( &content_id, sizeof(int), 1, f);
892                                                         fread( &size, sizeof(int), 1, f);
893                                                         while(size--)
894                                                         {
895                                                                 time_t time1, time2;
896                                                                 __u16 event_id;
897                                                                 fread( &time1, sizeof(time_t), 1, f);
898                                                                 fread( &time2, sizeof(time_t), 1, f);
899                                                                 fread( &event_id, sizeof(__u16), 1, f);
900                                                                 content_time_tables[key][content_id][time1]=std::pair<time_t, __u16>(time2, event_id);
901                                                                 eventMap::iterator it =
902                                                                         evMap.find(event_id);
903                                                                 if (it != evMap.end())
904                                                                         it->second->type = PRIVATE;
905                                                         }
906                                                 }
907                                         }
908                                 }
909 #endif // ENABLE_PRIVATE_EPG
910                         }
911                         else
912                                 eDebug("[EPGC] don't read old epg database");
913                         fclose(f);
914                 }
915         }
916 }
917
918 void eEPGCache::save()
919 {
920         struct statfs s;
921         off64_t tmp;
922         if (statfs("/hdd", &s)<0)
923                 tmp=0;
924         else
925         {
926                 tmp=s.f_blocks;
927                 tmp*=s.f_bsize;
928         }
929
930         // prevent writes to builtin flash
931         if ( tmp < 1024*1024*50 ) // storage size < 50MB
932                 return;
933
934         // check for enough free space on storage
935         tmp=s.f_bfree;
936         tmp*=s.f_bsize;
937         if ( tmp < (eventData::CacheSize*12)/10 ) // 20% overhead
938                 return;
939
940         FILE *f = fopen("/hdd/epg.dat", "w");
941         int cnt=0;
942         if ( f )
943         {
944                 unsigned int magic = 0x98765432;
945                 fwrite( &magic, sizeof(int), 1, f);
946                 const char *text = "ENIGMA_EPG_V5";
947                 fwrite( text, 13, 1, f );
948                 int size = eventDB.size();
949                 fwrite( &size, sizeof(int), 1, f );
950                 for (eventCache::iterator service_it(eventDB.begin()); service_it != eventDB.end(); ++service_it)
951                 {
952                         timeMap &timemap = service_it->second.second;
953                         fwrite( &service_it->first, sizeof(uniqueEPGKey), 1, f);
954                         size = timemap.size();
955                         fwrite( &size, sizeof(int), 1, f);
956                         for (timeMap::iterator time_it(timemap.begin()); time_it != timemap.end(); ++time_it)
957                         {
958                                 __u8 len = time_it->second->ByteSize;
959                                 fwrite( &time_it->second->type, sizeof(__u8), 1, f );
960                                 fwrite( &len, sizeof(__u8), 1, f);
961                                 fwrite( time_it->second->EITdata, len, 1, f);
962                                 ++cnt;
963                         }
964                 }
965                 eDebug("[EPGC] %d events written to /hdd/epg.dat", cnt);
966                 eventData::save(f);
967 #ifdef ENABLE_PRIVATE_EPG
968                 const char* text3 = "PRIVATE_EPG";
969                 fwrite( text3, 11, 1, f );
970                 size = content_time_tables.size();
971                 fwrite( &size, sizeof(int), 1, f);
972                 for (contentMaps::iterator a = content_time_tables.begin(); a != content_time_tables.end(); ++a)
973                 {
974                         contentMap &content_time_table = a->second;
975                         fwrite( &a->first, sizeof(uniqueEPGKey), 1, f);
976                         int size = content_time_table.size();
977                         fwrite( &size, sizeof(int), 1, f);
978                         for (contentMap::iterator i = content_time_table.begin(); i != content_time_table.end(); ++i )
979                         {
980                                 int size = i->second.size();
981                                 fwrite( &i->first, sizeof(int), 1, f);
982                                 fwrite( &size, sizeof(int), 1, f);
983                                 for ( contentTimeMap::iterator it(i->second.begin());
984                                         it != i->second.end(); ++it )
985                                 {
986                                         fwrite( &it->first, sizeof(time_t), 1, f);
987                                         fwrite( &it->second.first, sizeof(time_t), 1, f);
988                                         fwrite( &it->second.second, sizeof(__u16), 1, f);
989                                 }
990                         }
991                 }
992 #endif
993                 fclose(f);
994 #if 0
995                 unsigned char md5[16];
996                 if (!md5_file("/hdd/epg.dat", 1, md5))
997                 {
998                         FILE *f = fopen("/hdd/epg.dat.md5", "w");
999                         if (f)
1000                         {
1001                                 fwrite( md5, 16, 1, f);
1002                                 fclose(f);
1003                         }
1004                 }
1005 #endif
1006         }
1007 }
1008
1009 eEPGCache::channel_data::channel_data(eEPGCache *ml)
1010         :cache(ml)
1011         ,abortTimer(ml), zapTimer(ml), state(0)
1012         ,isRunning(0), haveData(0)
1013 #ifdef ENABLE_PRIVATE_EPG
1014         ,startPrivateTimer(ml)
1015 #endif
1016 #ifdef ENABLE_MHW_EPG
1017         ,m_MHWTimeoutTimer(ml)
1018 #endif
1019 {
1020 #ifdef ENABLE_MHW_EPG
1021         CONNECT(m_MHWTimeoutTimer.timeout, eEPGCache::channel_data::MHWTimeout);
1022 #endif
1023         CONNECT(zapTimer.timeout, eEPGCache::channel_data::startEPG);
1024         CONNECT(abortTimer.timeout, eEPGCache::channel_data::abortNonAvail);
1025 #ifdef ENABLE_PRIVATE_EPG
1026         CONNECT(startPrivateTimer.timeout, eEPGCache::channel_data::startPrivateReader);
1027 #endif
1028         pthread_mutex_init(&channel_active, 0);
1029 }
1030
1031 bool eEPGCache::channel_data::finishEPG()
1032 {
1033         if (!isRunning)  // epg ready
1034         {
1035                 eDebug("[EPGC] stop caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1036                 zapTimer.start(UPDATE_INTERVAL, 1);
1037                 eDebug("[EPGC] next update in %i min", UPDATE_INTERVAL / 60000);
1038                 for (int i=0; i < 3; ++i)
1039                 {
1040                         seenSections[i].clear();
1041                         calcedSections[i].clear();
1042                 }
1043                 singleLock l(cache->cache_lock);
1044                 cache->channelLastUpdated[channel->getChannelID()] = eDVBLocalTimeHandler::getInstance()->nowTime();
1045 #ifdef ENABLE_MHW_EPG
1046                 cleanup();
1047 #endif
1048                 return true;
1049         }
1050         return false;
1051 }
1052
1053 void eEPGCache::channel_data::startEPG()
1054 {
1055         eDebug("[EPGC] start caching events(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1056         state=0;
1057         haveData=0;
1058         for (int i=0; i < 3; ++i)
1059         {
1060                 seenSections[i].clear();
1061                 calcedSections[i].clear();
1062         }
1063
1064         eDVBSectionFilterMask mask;
1065         memset(&mask, 0, sizeof(mask));
1066
1067 #ifdef ENABLE_MHW_EPG
1068         mask.pid = 0xD3;
1069         mask.data[0] = 0x91;
1070         mask.mask[0] = 0xFF;
1071         m_MHWReader->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData), m_MHWConn);
1072         m_MHWReader->start(mask);
1073         isRunning |= MHW;
1074         memcpy(&m_MHWFilterMask, &mask, sizeof(eDVBSectionFilterMask));
1075
1076         mask.pid = 0x231;
1077         mask.data[0] = 0xC8;
1078         mask.mask[0] = 0xFF;
1079         mask.data[1] = 0;
1080         mask.mask[1] = 0xFF;
1081         m_MHWReader2->connectRead(slot(*this, &eEPGCache::channel_data::readMHWData2), m_MHWConn2);
1082         m_MHWReader2->start(mask);
1083         isRunning |= MHW;
1084         memcpy(&m_MHWFilterMask2, &mask, sizeof(eDVBSectionFilterMask));
1085         mask.data[1] = 0;
1086         mask.mask[1] = 0;
1087 #endif
1088
1089         mask.pid = 0x12;
1090         mask.flags = eDVBSectionFilterMask::rfCRC;
1091
1092         mask.data[0] = 0x4E;
1093         mask.mask[0] = 0xFE;
1094         m_NowNextReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_NowNextConn);
1095         m_NowNextReader->start(mask);
1096         isRunning |= NOWNEXT;
1097
1098         mask.data[0] = 0x50;
1099         mask.mask[0] = 0xF0;
1100         m_ScheduleReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleConn);
1101         m_ScheduleReader->start(mask);
1102         isRunning |= SCHEDULE;
1103
1104         mask.data[0] = 0x60;
1105         m_ScheduleOtherReader->connectRead(slot(*this, &eEPGCache::channel_data::readData), m_ScheduleOtherConn);
1106         m_ScheduleOtherReader->start(mask);
1107         isRunning |= SCHEDULE_OTHER;
1108
1109         abortTimer.start(7000,true);
1110 }
1111
1112 void eEPGCache::channel_data::abortNonAvail()
1113 {
1114         if (!state)
1115         {
1116                 if ( !(haveData&NOWNEXT) && (isRunning&NOWNEXT) )
1117                 {
1118                         eDebug("[EPGC] abort non avail nownext reading");
1119                         isRunning &= ~NOWNEXT;
1120                         m_NowNextReader->stop();
1121                         m_NowNextConn=0;
1122                 }
1123                 if ( !(haveData&SCHEDULE) && (isRunning&SCHEDULE) )
1124                 {
1125                         eDebug("[EPGC] abort non avail schedule reading");
1126                         isRunning &= ~SCHEDULE;
1127                         m_ScheduleReader->stop();
1128                         m_ScheduleConn=0;
1129                 }
1130                 if ( !(haveData&SCHEDULE_OTHER) && (isRunning&SCHEDULE_OTHER) )
1131                 {
1132                         eDebug("[EPGC] abort non avail schedule_other reading");
1133                         isRunning &= ~SCHEDULE_OTHER;
1134                         m_ScheduleOtherReader->stop();
1135                         m_ScheduleOtherConn=0;
1136                 }
1137 #ifdef ENABLE_MHW_EPG
1138                 if ( !(haveData&MHW) && (isRunning&MHW) )
1139                 {
1140                         eDebug("[EPGC] abort non avail mhw reading");
1141                         isRunning &= ~MHW;
1142                         m_MHWReader->stop();
1143                         m_MHWConn=0;
1144                         m_MHWReader2->stop();
1145                         m_MHWConn2=0;
1146                 }
1147 #endif
1148                 if ( isRunning )
1149                         abortTimer.start(90000, true);
1150                 else
1151                 {
1152                         ++state;
1153                         for (int i=0; i < 3; ++i)
1154                         {
1155                                 seenSections[i].clear();
1156                                 calcedSections[i].clear();
1157                         }
1158                 }
1159         }
1160         ++state;
1161 }
1162
1163 void eEPGCache::channel_data::startChannel()
1164 {
1165         pthread_mutex_lock(&channel_active);
1166         updateMap::iterator It = cache->channelLastUpdated.find( channel->getChannelID() );
1167
1168         int update = ( It != cache->channelLastUpdated.end() ? ( UPDATE_INTERVAL - ( (eDVBLocalTimeHandler::getInstance()->nowTime()-It->second) * 1000 ) ) : ZAP_DELAY );
1169
1170         if (update < ZAP_DELAY)
1171                 update = ZAP_DELAY;
1172
1173         zapTimer.start(update, 1);
1174         if (update >= 60000)
1175                 eDebug("[EPGC] next update in %i min", update/60000);
1176         else if (update >= 1000)
1177                 eDebug("[EPGC] next update in %i sec", update/1000);
1178 }
1179
1180 void eEPGCache::channel_data::abortEPG()
1181 {
1182         for (int i=0; i < 3; ++i)
1183         {
1184                 seenSections[i].clear();
1185                 calcedSections[i].clear();
1186         }
1187         abortTimer.stop();
1188         zapTimer.stop();
1189         if (isRunning)
1190         {
1191                 eDebug("[EPGC] abort caching events !!");
1192                 if (isRunning & SCHEDULE)
1193                 {
1194                         isRunning &= ~SCHEDULE;
1195                         m_ScheduleReader->stop();
1196                         m_ScheduleConn=0;
1197                 }
1198                 if (isRunning & NOWNEXT)
1199                 {
1200                         isRunning &= ~NOWNEXT;
1201                         m_NowNextReader->stop();
1202                         m_NowNextConn=0;
1203                 }
1204                 if (isRunning & SCHEDULE_OTHER)
1205                 {
1206                         isRunning &= ~SCHEDULE_OTHER;
1207                         m_ScheduleOtherReader->stop();
1208                         m_ScheduleOtherConn=0;
1209                 }
1210 #ifdef ENABLE_MHW_EPG
1211                 if (isRunning & MHW)
1212                 {
1213                         isRunning &= ~MHW;
1214                         m_MHWReader->stop();
1215                         m_MHWConn=0;
1216                         m_MHWReader2->stop();
1217                         m_MHWConn2=0;
1218                 }
1219 #endif
1220         }
1221 #ifdef ENABLE_PRIVATE_EPG
1222         if (m_PrivateReader)
1223                 m_PrivateReader->stop();
1224         if (m_PrivateConn)
1225                 m_PrivateConn=0;
1226 #endif
1227         pthread_mutex_unlock(&channel_active);
1228 }
1229
1230 void eEPGCache::channel_data::readData( const __u8 *data)
1231 {
1232         int source;
1233         int map;
1234         iDVBSectionReader *reader=NULL;
1235         switch(data[0])
1236         {
1237                 case 0x4E ... 0x4F:
1238                         reader=m_NowNextReader;
1239                         source=NOWNEXT;
1240                         map=0;
1241                         break;
1242                 case 0x50 ... 0x5F:
1243                         reader=m_ScheduleReader;
1244                         source=SCHEDULE;
1245                         map=1;
1246                         break;
1247                 case 0x60 ... 0x6F:
1248                         reader=m_ScheduleOtherReader;
1249                         source=SCHEDULE_OTHER;
1250                         map=2;
1251                         break;
1252                 default:
1253                         eDebug("[EPGC] unknown table_id !!!");
1254                         return;
1255         }
1256         tidMap &seenSections = this->seenSections[map];
1257         tidMap &calcedSections = this->calcedSections[map];
1258         if ( state == 1 && calcedSections == seenSections || state > 1 )
1259         {
1260                 eDebugNoNewLine("[EPGC] ");
1261                 switch (source)
1262                 {
1263                         case NOWNEXT:
1264                                 m_NowNextConn=0;
1265                                 eDebugNoNewLine("nownext");
1266                                 break;
1267                         case SCHEDULE:
1268                                 m_ScheduleConn=0;
1269                                 eDebugNoNewLine("schedule");
1270                                 break;
1271                         case SCHEDULE_OTHER:
1272                                 m_ScheduleOtherConn=0;
1273                                 eDebugNoNewLine("schedule other");
1274                                 break;
1275                         default: eDebugNoNewLine("unknown");break;
1276                 }
1277                 eDebug(" finished(%ld)", eDVBLocalTimeHandler::getInstance()->nowTime());
1278                 if ( reader )
1279                         reader->stop();
1280                 isRunning &= ~source;
1281                 if (!isRunning)
1282                         finishEPG();
1283         }
1284         else
1285         {
1286                 eit_t *eit = (eit_t*) data;
1287                 __u32 sectionNo = data[0] << 24;
1288                 sectionNo |= data[3] << 16;
1289                 sectionNo |= data[4] << 8;
1290                 sectionNo |= eit->section_number;
1291
1292                 tidMap::iterator it =
1293                         seenSections.find(sectionNo);
1294
1295                 if ( it == seenSections.end() )
1296                 {
1297                         seenSections.insert(sectionNo);
1298                         calcedSections.insert(sectionNo);
1299                         __u32 tmpval = sectionNo & 0xFFFFFF00;
1300                         __u8 incr = source == NOWNEXT ? 1 : 8;
1301                         for ( int i = 0; i <= eit->last_section_number; i+=incr )
1302                         {
1303                                 if ( i == eit->section_number )
1304                                 {
1305                                         for (int x=i; x <= eit->segment_last_section_number; ++x)
1306                                                 calcedSections.insert(tmpval|(x&0xFF));
1307                                 }
1308                                 else
1309                                         calcedSections.insert(tmpval|(i&0xFF));
1310                         }
1311                         cache->sectionRead(data, source, this);
1312                 }
1313         }
1314 }
1315
1316 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1317 // if t == -1 we search the current event...
1318 {
1319         singleLock s(cache_lock);
1320         uniqueEPGKey key(service);
1321
1322         // check if EPG for this service is ready...
1323         eventCache::iterator It = eventDB.find( key );
1324         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1325         {
1326                 if (t==-1)
1327                         t = eDVBLocalTimeHandler::getInstance()->nowTime();
1328                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1329                         It->second.second.upper_bound(t); // just >
1330                 if ( i != It->second.second.end() )
1331                 {
1332                         if ( direction < 0 || (direction == 0 && i->second->getStartTime() > t) )
1333                         {
1334                                 timeMap::iterator x = i;
1335                                 --x;
1336                                 if ( x != It->second.second.end() )
1337                                 {
1338                                         time_t start_time = x->second->getStartTime();
1339                                         if (direction >= 0)
1340                                         {
1341                                                 if (t < start_time)
1342                                                         return -1;
1343                                                 if (t > (start_time+x->second->getDuration()))
1344                                                         return -1;
1345                                         }
1346                                         i = x;
1347                                 }
1348                                 else
1349                                         return -1;
1350                         }
1351                         result = i->second;
1352                         return 0;
1353                 }
1354         }
1355         return -1;
1356 }
1357
1358 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1359 {
1360         singleLock s(cache_lock);
1361         const eventData *data=0;
1362         RESULT ret = lookupEventTime(service, t, data, direction);
1363         if ( !ret && data )
1364                 result = data->get();
1365         return ret;
1366 }
1367
1368 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1369 {
1370         singleLock s(cache_lock);
1371         const eventData *data=0;
1372         RESULT ret = lookupEventTime(service, t, data, direction);
1373         if ( !ret && data )
1374                 result = new Event((uint8_t*)data->get());
1375         return ret;
1376 }
1377
1378 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1379 {
1380         singleLock s(cache_lock);
1381         const eventData *data=0;
1382         RESULT ret = lookupEventTime(service, t, data, direction);
1383         if ( !ret && data )
1384         {
1385                 Event ev((uint8_t*)data->get());
1386                 result = new eServiceEvent();
1387                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1388                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1389         }
1390         return ret;
1391 }
1392
1393 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1394 {
1395         singleLock s(cache_lock);
1396         uniqueEPGKey key( service );
1397
1398         eventCache::iterator It = eventDB.find( key );
1399         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1400         {
1401                 eventMap::iterator i( It->second.first.find( event_id ));
1402                 if ( i != It->second.first.end() )
1403                 {
1404                         result = i->second;
1405                         return 0;
1406                 }
1407                 else
1408                 {
1409                         result = 0;
1410                         eDebug("[EPGC] event %04x not found in epgcache", event_id);
1411                 }
1412         }
1413         return -1;
1414 }
1415
1416 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1417 {
1418         singleLock s(cache_lock);
1419         const eventData *data=0;
1420         RESULT ret = lookupEventId(service, event_id, data);
1421         if ( !ret && data )
1422                 result = data->get();
1423         return ret;
1424 }
1425
1426 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1427 {
1428         singleLock s(cache_lock);
1429         const eventData *data=0;
1430         RESULT ret = lookupEventId(service, event_id, data);
1431         if ( !ret && data )
1432                 result = new Event((uint8_t*)data->get());
1433         return ret;
1434 }
1435
1436 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1437 {
1438         singleLock s(cache_lock);
1439         const eventData *data=0;
1440         RESULT ret = lookupEventId(service, event_id, data);
1441         if ( !ret && data )
1442         {
1443                 Event ev((uint8_t*)data->get());
1444                 result = new eServiceEvent();
1445                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1446                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1447         }
1448         return ret;
1449 }
1450
1451 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1452 {
1453         eventCache::iterator It = eventDB.find( service );
1454         if ( It != eventDB.end() && It->second.second.size() )
1455         {
1456                 m_timemap_end = minutes != -1 ? It->second.second.upper_bound(begin+minutes*60) : It->second.second.end();
1457                 if ( begin != -1 )
1458                 {
1459                         m_timemap_cursor = It->second.second.lower_bound(begin);
1460                         if ( m_timemap_cursor != It->second.second.end() )
1461                         {
1462                                 if ( m_timemap_cursor->second->getStartTime() != begin )
1463                                 {
1464                                         timeMap::iterator x = m_timemap_cursor;
1465                                         --x;
1466                                         if ( x != It->second.second.end() )
1467                                         {
1468                                                 time_t start_time = x->second->getStartTime();
1469                                                 if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1470                                                         m_timemap_cursor = x;
1471                                         }
1472                                 }
1473                         }
1474                 }
1475                 else
1476                         m_timemap_cursor = It->second.second.begin();
1477                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1478                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1479                 return 0;
1480         }
1481         return -1;
1482 }
1483
1484 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1485 {
1486         if ( m_timemap_cursor != m_timemap_end )
1487         {
1488                 result = m_timemap_cursor++->second;
1489                 return 0;
1490         }
1491         return -1;
1492 }
1493
1494 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1495 {
1496         if ( m_timemap_cursor != m_timemap_end )
1497         {
1498                 result = m_timemap_cursor++->second->get();
1499                 return 0;
1500         }
1501         return -1;
1502 }
1503
1504 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1505 {
1506         if ( m_timemap_cursor != m_timemap_end )
1507         {
1508                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1509                 return 0;
1510         }
1511         return -1;
1512 }
1513
1514 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1515 {
1516         if ( m_timemap_cursor != m_timemap_end )
1517         {
1518                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1519                 result = new eServiceEvent();
1520                 return result->parseFrom(&ev, currentQueryTsidOnid);
1521         }
1522         return -1;
1523 }
1524
1525 void fillTuple(PyObject *tuple, char *argstring, int argcount, PyObject *service, ePtr<eServiceEvent> &ptr, PyObject *nowTime, PyObject *service_name )
1526 {
1527         PyObject *tmp=NULL;
1528         int pos=0;
1529         while(pos < argcount)
1530         {
1531                 bool inc_refcount=false;
1532                 switch(argstring[pos])
1533                 {
1534                         case '0': // PyLong 0
1535                                 tmp = PyLong_FromLong(0);
1536                                 break;
1537                         case 'I': // Event Id
1538                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : NULL;
1539                                 break;
1540                         case 'B': // Event Begin Time
1541                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1542                                 break;
1543                         case 'D': // Event Duration
1544                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1545                                 break;
1546                         case 'T': // Event Title
1547                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1548                                 break;
1549                         case 'S': // Event Short Description
1550                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1551                                 break;
1552                         case 'E': // Event Extended Description
1553                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1554                                 break;
1555                         case 'C': // Current Time
1556                                 tmp = nowTime;
1557                                 inc_refcount = true;
1558                                 break;
1559                         case 'R': // service reference string
1560                                 tmp = service;
1561                                 inc_refcount = true;
1562                                 break;
1563                         case 'N': // service name
1564                                 tmp = service_name;
1565                                 inc_refcount = true;
1566                 }
1567                 if (!tmp)
1568                 {
1569                         tmp = Py_None;
1570                         inc_refcount = true;
1571                 }
1572                 if (inc_refcount)
1573                         Py_INCREF(tmp);
1574                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1575         }
1576 }
1577
1578 PyObject *handleEvent(ePtr<eServiceEvent> &ptr, PyObject *dest_list, char* argstring, int argcount, PyObject *service, PyObject *nowTime, PyObject *service_name, PyObject *convertFunc, PyObject *convertFuncArgs)
1579 {
1580         if (convertFunc)
1581         {
1582                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1583                 PyObject *result = PyObject_CallObject(convertFunc, convertFuncArgs);
1584                 if (result == NULL)
1585                 {
1586                         if (service_name)
1587                                 Py_DECREF(service_name);
1588                         if (nowTime)
1589                                 Py_DECREF(nowTime);
1590                         Py_DECREF(convertFuncArgs);
1591                         Py_DECREF(dest_list);
1592                         return result;
1593                 }
1594                 PyList_Append(dest_list, result);
1595                 Py_DECREF(result);
1596         }
1597         else
1598         {
1599                 PyObject *tuple = PyTuple_New(argcount);
1600                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1601                 PyList_Append(dest_list, tuple);
1602                 Py_DECREF(tuple);
1603         }
1604         return 0;
1605 }
1606
1607 // here we get a python list
1608 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1609 //   0 = PyLong(0)
1610 //   I = Event Id
1611 //   B = Event Begin Time
1612 //   D = Event Duration
1613 //   T = Event Title
1614 //   S = Event Short Description
1615 //   E = Event Extended Description
1616 //   C = Current Time
1617 //   R = Service Reference
1618 //   N = Service Name
1619 // then for each service follows a tuple
1620 //   first tuple entry is the servicereference (as string... use the ref.toString() function)
1621 //   the second is the type of query
1622 //     2 = event_id
1623 //    -1 = event before given start_time
1624 //     0 = event intersects given start_time
1625 //    +1 = event after given start_time
1626 //   the third
1627 //      when type is eventid it is the event_id
1628 //      when type is time then it is the start_time ( 0 for now_time )
1629 //   the fourth is the end_time .. ( optional .. for query all events in time range)
1630
1631 PyObject *eEPGCache::lookupEvent(PyObject *list, PyObject *convertFunc)
1632 {
1633         PyObject *convertFuncArgs=NULL;
1634         int argcount=0;
1635         char *argstring=NULL;
1636         if (!PyList_Check(list))
1637         {
1638                 PyErr_SetString(PyExc_StandardError,
1639                         "type error");
1640                 eDebug("no list");
1641                 return NULL;
1642         }
1643         int listIt=0;
1644         int listSize=PyList_Size(list);
1645         if (!listSize)
1646         {
1647                 PyErr_SetString(PyExc_StandardError,
1648                         "not params given");
1649                 eDebug("not params given");
1650                 return NULL;
1651         }
1652         else 
1653         {
1654                 PyObject *argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1655                 if (PyString_Check(argv))
1656                 {
1657                         argstring = PyString_AS_STRING(argv);
1658                         ++listIt;
1659                 }
1660                 else
1661                         argstring = "I"; // just event id as default
1662                 argcount = strlen(argstring);
1663 //              eDebug("have %d args('%s')", argcount, argstring);
1664         }
1665         if (convertFunc)
1666         {
1667                 if (!PyCallable_Check(convertFunc))
1668                 {
1669                         PyErr_SetString(PyExc_StandardError,
1670                                 "convertFunc must be callable");
1671                         eDebug("convertFunc is not callable");
1672                         return NULL;
1673                 }
1674                 convertFuncArgs = PyTuple_New(argcount);
1675         }
1676
1677         PyObject *nowTime = strchr(argstring, 'C') ?
1678                 PyLong_FromLong(eDVBLocalTimeHandler::getInstance()->nowTime()) :
1679                 NULL;
1680
1681         bool must_get_service_name = strchr(argstring, 'N') ? true : false;
1682
1683         // create dest list
1684         PyObject *dest_list=PyList_New(0);
1685         while(listSize > listIt)
1686         {
1687                 PyObject *item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1688                 if (PyTuple_Check(item))
1689                 {
1690                         bool service_changed=false;
1691                         int type=0;
1692                         long event_id=-1;
1693                         time_t stime=-1;
1694                         int minutes=0;
1695                         int tupleSize=PyTuple_Size(item);
1696                         int tupleIt=0;
1697                         PyObject *service=NULL;
1698                         while(tupleSize > tupleIt)  // parse query args
1699                         {
1700                                 PyObject *entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1701                                 switch(tupleIt++)
1702                                 {
1703                                         case 0:
1704                                         {
1705                                                 if (!PyString_Check(entry))
1706                                                 {
1707                                                         eDebug("tuple entry 0 is no a string");
1708                                                         goto skip_entry;
1709                                                 }
1710                                                 service = entry;
1711                                                 break;
1712                                         }
1713                                         case 1:
1714                                                 type=PyInt_AsLong(entry);
1715                                                 if (type < -1 || type > 2)
1716                                                 {
1717                                                         eDebug("unknown type %d", type);
1718                                                         goto skip_entry;
1719                                                 }
1720                                                 break;
1721                                         case 2:
1722                                                 event_id=stime=PyInt_AsLong(entry);
1723                                                 break;
1724                                         case 3:
1725                                                 minutes=PyInt_AsLong(entry);
1726                                                 break;
1727                                         default:
1728                                                 eDebug("unneeded extra argument");
1729                                                 break;
1730                                 }
1731                         }
1732                         eServiceReference ref(PyString_AS_STRING(service));
1733                         if (ref.type != eServiceReference::idDVB)
1734                         {
1735                                 eDebug("service reference for epg query is not valid");
1736                                 continue;
1737                         }
1738
1739                         // redirect subservice querys to parent service
1740                         eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1741                         if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1742                         {
1743                                 eServiceCenterPtr service_center;
1744                                 if (!eServiceCenter::getPrivInstance(service_center))
1745                                 {
1746                                         dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1747                                         dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1748                                         dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1749                                         dvb_ref.setParentServiceID(eServiceID(0));
1750                                         dvb_ref.name="";
1751                                         service = PyString_FromString(dvb_ref.toString().c_str());
1752                                         service_changed = true;
1753                                 }
1754                         }
1755
1756                         PyObject *service_name=NULL;
1757                         if (must_get_service_name)
1758                         {
1759                                 ePtr<iStaticServiceInformation> sptr;
1760                                 eServiceCenterPtr service_center;
1761                                 eServiceCenter::getPrivInstance(service_center);
1762                                 if (service_center)
1763                                 {
1764                                         service_center->info(ref, sptr);
1765                                         if (sptr)
1766                                         {
1767                                                 std::string name;
1768                                                 sptr->getName(ref, name);
1769                                                 if (name.length())
1770                                                         service_name = PyString_FromString(name.c_str());
1771                                         }
1772                                 }
1773                                 if (!service_name)
1774                                         service_name = PyString_FromString("<n/a>");
1775                         }
1776                         if (minutes)
1777                         {
1778                                 Lock();
1779                                 if (!startTimeQuery(ref, stime, minutes))
1780                                 {
1781                                         ePtr<eServiceEvent> ptr;
1782                                         while (!getNextTimeEntry(ptr))
1783                                         {
1784                                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1785                                                 if (ret)
1786                                                         return ret;
1787                                         }
1788                                 }
1789                                 Unlock();
1790                         }
1791                         else
1792                         {
1793                                 ePtr<eServiceEvent> ptr;
1794                                 if (stime)
1795                                 {
1796                                         if (type == 2)
1797                                                 lookupEventId(ref, event_id, ptr);
1798                                         else
1799                                                 lookupEventTime(ref, stime, ptr, type);
1800                                 }
1801                                 PyObject *ret = handleEvent(ptr, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs);
1802                                 if (ret)
1803                                         return ret;
1804                         }
1805                         if (service_changed)
1806                                 Py_DECREF(service);
1807                         if (service_name)
1808                                 Py_DECREF(service_name);
1809                 }
1810 skip_entry:
1811                 ;
1812         }
1813         if (convertFuncArgs)
1814                 Py_DECREF(convertFuncArgs);
1815         if (nowTime)
1816                 Py_DECREF(nowTime);
1817         return dest_list;
1818 }
1819
1820 void fillTuple2(PyObject *tuple, const char *argstring, int argcount, eventData *evData, ePtr<eServiceEvent> &ptr, PyObject *service_name, PyObject *service_reference)
1821 {
1822         PyObject *tmp=NULL;
1823         int pos=0;
1824         while(pos < argcount)
1825         {
1826                 bool inc_refcount=false;
1827                 switch(argstring[pos])
1828                 {
1829                         case '0': // PyLong 0
1830                                 tmp = PyLong_FromLong(0);
1831                                 break;
1832                         case 'I': // Event Id
1833                                 tmp = PyLong_FromLong(evData->getEventID());
1834                                 break;
1835                         case 'B': // Event Begin Time
1836                                 if (ptr)
1837                                         tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : NULL;
1838                                 else
1839                                         tmp = PyLong_FromLong(evData->getStartTime());
1840                                 break;
1841                         case 'D': // Event Duration
1842                                 if (ptr)
1843                                         tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : NULL;
1844                                 else
1845                                         tmp = PyLong_FromLong(evData->getDuration());
1846                                 break;
1847                         case 'T': // Event Title
1848                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : NULL;
1849                                 break;
1850                         case 'S': // Event Short Description
1851                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : NULL;
1852                                 break;
1853                         case 'E': // Event Extended Description
1854                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : NULL;
1855                                 break;
1856                         case 'R': // service reference string
1857                                 tmp = service_reference;
1858                                 inc_refcount = true;
1859                                 break;
1860                         case 'N': // service name
1861                                 tmp = service_name;
1862                                 inc_refcount = true;
1863                                 break;
1864                 }
1865                 if (!tmp)
1866                 {
1867                         tmp = Py_None;
1868                         inc_refcount = true;
1869                 }
1870                 if (inc_refcount)
1871                         Py_INCREF(tmp);
1872                 PyTuple_SET_ITEM(tuple, pos++, tmp);
1873         }
1874 }
1875
1876 // here we get a python tuple
1877 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
1878 //   I = Event Id
1879 //   B = Event Begin Time
1880 //   D = Event Duration
1881 //   T = Event Title
1882 //   S = Event Short Description
1883 //   E = Event Extended Description
1884 //   R = Service Reference
1885 //   N = Service Name
1886 //  the second tuple entry is the MAX matches value
1887 //  the third tuple entry is the type of query
1888 //     0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
1889 //     1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
1890 //     2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
1891 //  when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
1892 //   the fourth is the servicereference string
1893 //   the fifth is the eventid
1894 //  when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
1895 //   the fourth is the search text
1896 //   the fifth is
1897 //     0 = case sensitive (CASE_CHECK)
1898 //     1 = case insensitive (NO_CASECHECK)
1899
1900 PyObject *eEPGCache::search(PyObject *arg)
1901 {
1902         PyObject *ret = 0;
1903         int descridx = -1;
1904         __u32 descr[512];
1905         int eventid = -1;
1906         const char *argstring=0;
1907         char *refstr=0;
1908         int argcount=0;
1909         int querytype=-1;
1910         bool needServiceEvent=false;
1911         int maxmatches=0;
1912
1913         if (PyTuple_Check(arg))
1914         {
1915                 int tuplesize=PyTuple_Size(arg);
1916                 if (tuplesize > 0)
1917                 {
1918                         PyObject *obj = PyTuple_GET_ITEM(arg,0);
1919                         if (PyString_Check(obj))
1920                         {
1921                                 argcount = PyString_GET_SIZE(obj);
1922                                 argstring = PyString_AS_STRING(obj);
1923                                 for (int i=0; i < argcount; ++i)
1924                                         switch(argstring[i])
1925                                         {
1926                                         case 'S':
1927                                         case 'E':
1928                                         case 'T':
1929                                                 needServiceEvent=true;
1930                                         default:
1931                                                 break;
1932                                         }
1933                         }
1934                         else
1935                         {
1936                                 PyErr_SetString(PyExc_StandardError,
1937                                         "type error");
1938                                 eDebug("tuple arg 0 is not a string");
1939                                 return NULL;
1940                         }
1941                 }
1942                 if (tuplesize > 1)
1943                         maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
1944                 if (tuplesize > 2)
1945                 {
1946                         querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
1947                         if (tuplesize > 4 && querytype == 0)
1948                         {
1949                                 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
1950                                 if (PyString_Check(obj))
1951                                 {
1952                                         refstr = PyString_AS_STRING(obj);
1953                                         eServiceReferenceDVB ref(refstr);
1954                                         if (ref.valid())
1955                                         {
1956                                                 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
1957                                                 singleLock s(cache_lock);
1958                                                 const eventData *evData = 0;
1959                                                 lookupEventId(ref, eventid, evData);
1960                                                 if (evData)
1961                                                 {
1962                                                         __u8 *data = evData->EITdata;
1963                                                         int tmp = evData->ByteSize-12;
1964                                                         __u32 *p = (__u32*)(data+12);
1965                                                                 // search short and extended event descriptors
1966                                                         while(tmp>0)
1967                                                         {
1968                                                                 __u32 crc = *p++;
1969                                                                 descriptorMap::iterator it =
1970                                                                         eventData::descriptors.find(crc);
1971                                                                 if (it != eventData::descriptors.end())
1972                                                                 {
1973                                                                         __u8 *descr_data = it->second.second;
1974                                                                         switch(descr_data[0])
1975                                                                         {
1976                                                                         case 0x4D ... 0x4E:
1977                                                                                 descr[++descridx]=crc;
1978                                                                         default:
1979                                                                                 break;
1980                                                                         }
1981                                                                 }
1982                                                                 tmp-=4;
1983                                                         }
1984                                                 }
1985                                                 if (descridx<0)
1986                                                         eDebug("event not found");
1987                                         }
1988                                         else
1989                                         {
1990                                                 PyErr_SetString(PyExc_StandardError,
1991                                                         "type error");
1992                                                 eDebug("tuple arg 4 is not a valid service reference string");
1993                                                 return NULL;
1994                                         }
1995                                 }
1996                                 else
1997                                 {
1998                                         PyErr_SetString(PyExc_StandardError,
1999                                         "type error");
2000                                         eDebug("tuple arg 4 is not a string");
2001                                         return NULL;
2002                                 }
2003                         }
2004                         else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2005                         {
2006                                 PyObject *obj = PyTuple_GET_ITEM(arg, 3);
2007                                 if (PyString_Check(obj))
2008                                 {
2009                                         int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2010                                         const char *str = PyString_AS_STRING(obj);
2011                                         int textlen = PyString_GET_SIZE(obj);
2012                                         if (querytype == 1)
2013                                                 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2014                                         else
2015                                                 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2016                                         singleLock s(cache_lock);
2017                                         for (descriptorMap::iterator it(eventData::descriptors.begin());
2018                                                 it != eventData::descriptors.end() && descridx < 511; ++it)
2019                                         {
2020                                                 __u8 *data = it->second.second;
2021                                                 if ( data[0] == 0x4D ) // short event descriptor
2022                                                 {
2023                                                         int title_len = data[5];
2024                                                         if ( querytype == 1 )
2025                                                         {
2026                                                                 if (title_len > textlen)
2027                                                                         continue;
2028                                                                 else if (title_len < textlen)
2029                                                                         continue;
2030                                                                 if ( casetype )
2031                                                                 {
2032                                                                         if ( !strncasecmp((const char*)data+6, str, title_len) )
2033                                                                         {
2034 //                                                                              std::string s((const char*)data+6, title_len);
2035 //                                                                              eDebug("match1 %s %s", str, s.c_str() );
2036                                                                                 descr[++descridx] = it->first;
2037                                                                         }
2038                                                                 }
2039                                                                 else if ( !strncmp((const char*)data+6, str, title_len) )
2040                                                                 {
2041 //                                                                      std::string s((const char*)data+6, title_len);
2042 //                                                                      eDebug("match2 %s %s", str, s.c_str() );
2043                                                                         descr[++descridx] = it->first;
2044                                                                 }
2045                                                         }
2046                                                         else
2047                                                         {
2048                                                                 int idx=0;
2049                                                                 while((title_len-idx) >= textlen)
2050                                                                 {
2051                                                                         if (casetype)
2052                                                                         {
2053                                                                                 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2054                                                                                 {
2055                                                                                         descr[++descridx] = it->first;
2056 //                                                                                      std::string s((const char*)data+6, title_len);
2057 //                                                                                      eDebug("match 3 %s %s", str, s.c_str() );
2058                                                                                         break;
2059                                                                                 }
2060                                                                                 else if (!strncmp((const char*)data+6+idx, str, textlen) )
2061                                                                                 {
2062                                                                                         descr[++descridx] = it->first;
2063 //                                                                                      std::string s((const char*)data+6, title_len);
2064 //                                                                                      eDebug("match 4 %s %s", str, s.c_str() );
2065                                                                                         break;
2066                                                                                 }
2067                                                                         }
2068                                                                         ++idx;
2069                                                                 }
2070                                                         }
2071                                                 }
2072                                         }
2073                                 }
2074                                 else
2075                                 {
2076                                         PyErr_SetString(PyExc_StandardError,
2077                                                 "type error");
2078                                         eDebug("tuple arg 4 is not a string");
2079                                         return NULL;
2080                                 }
2081                         }
2082                         else
2083                         {
2084                                 PyErr_SetString(PyExc_StandardError,
2085                                         "type error");
2086                                 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2087                                 return NULL;
2088                         }
2089                 }
2090                 else
2091                 {
2092                         PyErr_SetString(PyExc_StandardError,
2093                                 "type error");
2094                         eDebug("not enough args in tuple");
2095                         return NULL;
2096                 }
2097         }
2098         else
2099         {
2100                 PyErr_SetString(PyExc_StandardError,
2101                         "type error");
2102                 eDebug("arg 0 is not a tuple");
2103                 return NULL;
2104         }
2105
2106         if (descridx > -1)
2107         {
2108                 int maxcount=maxmatches;
2109                 eServiceReferenceDVB ref(refstr?refstr:"");
2110                 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2111                 // in this case we start searching with the base service
2112                 bool first = ref.valid() ? true : false;
2113                 singleLock s(cache_lock);
2114                 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2115                 while(cit != eventDB.end() && maxcount)
2116                 {
2117                         if ( ref.valid() && !first && cit->first == ref )
2118                         {
2119                                 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2120                                 ++cit;
2121                                 continue;
2122                         }
2123                         PyObject *service_name=0;
2124                         PyObject *service_reference=0;
2125                         timeMap &evmap = cit->second.second;
2126                         // check all events
2127                         for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2128                         {
2129                                 int evid = evit->second->getEventID();
2130                                 if ( evid == eventid)
2131                                         continue;
2132                                 __u8 *data = evit->second->EITdata;
2133                                 int tmp = evit->second->ByteSize-12;
2134                                 __u32 *p = (__u32*)(data+12);
2135                                 // check if any of our descriptor used by this event
2136                                 int cnt=-1;
2137                                 while(tmp>0)
2138                                 {
2139                                         __u32 crc32 = *p++;
2140                                         for ( int i=0; i <= descridx; ++i)
2141                                         {
2142                                                 if (descr[i] == crc32)  // found...
2143                                                         ++cnt;
2144                                         }
2145                                         tmp-=4;
2146                                 }
2147                                 if ( (querytype == 0 && cnt == descridx) ||
2148                                          ((querytype == 1 || querytype == 2) && cnt != -1) )
2149                                 {
2150                                         const uniqueEPGKey &service = cit->first;
2151                                         eServiceReference ref =
2152                                                 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2153                                         if (ref.valid())
2154                                         {
2155                                         // create servive event
2156                                                 ePtr<eServiceEvent> ptr;
2157                                                 if (needServiceEvent)
2158                                                 {
2159                                                         lookupEventId(ref, evid, ptr);
2160                                                         if (!ptr)
2161                                                                 eDebug("event not found !!!!!!!!!!!");
2162                                                 }
2163                                         // create service name
2164                                                 if (!service_name && strchr(argstring,'N'))
2165                                                 {
2166                                                         ePtr<iStaticServiceInformation> sptr;
2167                                                         eServiceCenterPtr service_center;
2168                                                         eServiceCenter::getPrivInstance(service_center);
2169                                                         if (service_center)
2170                                                         {
2171                                                                 service_center->info(ref, sptr);
2172                                                                 if (sptr)
2173                                                                 {
2174                                                                         std::string name;
2175                                                                         sptr->getName(ref, name);
2176                                                                         if (name.length())
2177                                                                                 service_name = PyString_FromString(name.c_str());
2178                                                                 }
2179                                                         }
2180                                                         if (!service_name)
2181                                                                 service_name = PyString_FromString("<n/a>");
2182                                                 }
2183                                         // create servicereference string
2184                                                 if (!service_reference && strchr(argstring,'R'))
2185                                                         service_reference = PyString_FromString(ref.toString().c_str());
2186                                         // create list
2187                                                 if (!ret)
2188                                                         ret = PyList_New(0);
2189                                         // create tuple
2190                                                 PyObject *tuple = PyTuple_New(argcount);
2191                                         // fill tuple
2192                                                 fillTuple2(tuple, argstring, argcount, evit->second, ptr, service_name, service_reference);
2193                                                 PyList_Append(ret, tuple);
2194                                                 Py_DECREF(tuple);
2195                                                 --maxcount;
2196                                         }
2197                                 }
2198                         }
2199                         if (service_name)
2200                                 Py_DECREF(service_name);
2201                         if (service_reference)
2202                                 Py_DECREF(service_reference);
2203                         if (first)
2204                         {
2205                                 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2206                                 first=false;
2207                                 cit=eventDB.begin();
2208                         }
2209                         else
2210                                 ++cit;
2211                 }
2212         }
2213
2214         if (!ret)
2215         {
2216                 Py_INCREF(Py_None);
2217                 ret=Py_None;
2218         }
2219
2220         return ret;
2221 }
2222
2223 #ifdef ENABLE_PRIVATE_EPG
2224 #include <dvbsi++/descriptor_tag.h>
2225 #include <dvbsi++/unknown_descriptor.h>
2226 #include <dvbsi++/private_data_specifier_descriptor.h>
2227
2228 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2229 {
2230         ePtr<eTable<ProgramMapSection> > ptr;
2231         if (!pmthandler->getPMT(ptr) && ptr)
2232         {
2233                 std::vector<ProgramMapSection*>::const_iterator i;
2234                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2235                 {
2236                         const ProgramMapSection &pmt = **i;
2237
2238                         ElementaryStreamInfoConstIterator es;
2239                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2240                         {
2241                                 int tmp=0;
2242                                 switch ((*es)->getType())
2243                                 {
2244                                 case 0x05: // private
2245                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2246                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2247                                         {
2248                                                 switch ((*desc)->getTag())
2249                                                 {
2250                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2251                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2252                                                                         tmp |= 1;
2253                                                                 break;
2254                                                         case 0x90:
2255                                                         {
2256                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2257                                                                 int descr_len = descr->getLength();
2258                                                                 if (descr_len == 4)
2259                                                                 {
2260                                                                         uint8_t data[descr_len+2];
2261                                                                         descr->writeToBuffer(data);
2262                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2263                                                                                 tmp |= 2;
2264                                                                 }
2265                                                                 break;
2266                                                         }
2267                                                         default:
2268                                                                 break;
2269                                                 }
2270                                         }
2271                                 default:
2272                                         break;
2273                                 }
2274                                 if (tmp==3)
2275                                 {
2276                                         eServiceReferenceDVB ref;
2277                                         if (!pmthandler->getServiceReference(ref))
2278                                         {
2279                                                 int pid = (*es)->getPid();
2280                                                 messages.send(Message(Message::got_private_pid, ref, pid));
2281                                                 return;
2282                                         }
2283                                 }
2284                         }
2285                 }
2286         }
2287         else
2288                 eDebug("PMTready but no pmt!!");
2289 }
2290
2291 struct date_time
2292 {
2293         __u8 data[5];
2294         time_t tm;
2295         date_time( const date_time &a )
2296         {
2297                 memcpy(data, a.data, 5);
2298                 tm = a.tm;
2299         }
2300         date_time( const __u8 data[5])
2301         {
2302                 memcpy(this->data, data, 5);
2303                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2304         }
2305         date_time()
2306         {
2307         }
2308         const __u8& operator[](int pos) const
2309         {
2310                 return data[pos];
2311         }
2312 };
2313
2314 struct less_datetime
2315 {
2316         bool operator()( const date_time &a, const date_time &b ) const
2317         {
2318                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2319         }
2320 };
2321
2322 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
2323 {
2324         contentMap &content_time_table = content_time_tables[current_service];
2325         singleLock s(cache_lock);
2326         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2327         eventMap &evMap = eventDB[current_service].first;
2328         timeMap &tmMap = eventDB[current_service].second;
2329         int ptr=8;
2330         int content_id = data[ptr++] << 24;
2331         content_id |= data[ptr++] << 16;
2332         content_id |= data[ptr++] << 8;
2333         content_id |= data[ptr++];
2334
2335         contentTimeMap &time_event_map =
2336                 content_time_table[content_id];
2337         for ( contentTimeMap::iterator it( time_event_map.begin() );
2338                 it != time_event_map.end(); ++it )
2339         {
2340                 eventMap::iterator evIt( evMap.find(it->second.second) );
2341                 if ( evIt != evMap.end() )
2342                 {
2343                         delete evIt->second;
2344                         evMap.erase(evIt);
2345                 }
2346                 tmMap.erase(it->second.first);
2347         }
2348         time_event_map.clear();
2349
2350         __u8 duration[3];
2351         memcpy(duration, data+ptr, 3);
2352         ptr+=3;
2353         int duration_sec =
2354                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2355
2356         const __u8 *descriptors[65];
2357         const __u8 **pdescr = descriptors;
2358
2359         int descriptors_length = (data[ptr++]&0x0F) << 8;
2360         descriptors_length |= data[ptr++];
2361         while ( descriptors_length > 0 )
2362         {
2363                 int descr_type = data[ptr];
2364                 int descr_len = data[ptr+1];
2365                 descriptors_length -= (descr_len+2);
2366                 if ( descr_type == 0xf2 )
2367                 {
2368                         ptr+=2;
2369                         int tsid = data[ptr++] << 8;
2370                         tsid |= data[ptr++];
2371                         int onid = data[ptr++] << 8;
2372                         onid |= data[ptr++];
2373                         int sid = data[ptr++] << 8;
2374                         sid |= data[ptr++];
2375
2376 // WORKAROUND for wrong transmitted epg data (01.08.2006)
2377                         if ( onid == 0x85 )
2378                         {
2379                                 switch( (tsid << 16) | sid )
2380                                 {
2381                                         case 0x01030b: sid = 0x1b; tsid = 4; break;  // Premiere Win
2382                                         case 0x0300f0: sid = 0xe0; tsid = 2; break;
2383                                         case 0x0300f1: sid = 0xe1; tsid = 2; break;
2384                                         case 0x0300f5: sid = 0xdc; break;
2385                                         case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2386                                         case 0x1100d3: sid = 0xe3; break;
2387                                 }
2388                         }
2389 ////////////////////////////////////////////
2390
2391                         uniqueEPGKey service( sid, onid, tsid );
2392                         descr_len -= 6;
2393                         while( descr_len > 0 )
2394                         {
2395                                 __u8 datetime[5];
2396                                 datetime[0] = data[ptr++];
2397                                 datetime[1] = data[ptr++];
2398                                 int tmp_len = data[ptr++];
2399                                 descr_len -= 3;
2400                                 while( tmp_len > 0 )
2401                                 {
2402                                         memcpy(datetime+2, data+ptr, 3);
2403                                         ptr+=3;
2404                                         descr_len -= 3;
2405                                         tmp_len -= 3;
2406                                         start_times[datetime].push_back(service);
2407                                 }
2408                         }
2409                 }
2410                 else
2411                 {
2412                         *pdescr++=data+ptr;
2413                         ptr += 2;
2414                         ptr += descr_len;
2415                 }
2416         }
2417         __u8 event[4098];
2418         eit_event_struct *ev_struct = (eit_event_struct*) event;
2419         ev_struct->running_status = 0;
2420         ev_struct->free_CA_mode = 1;
2421         memcpy(event+7, duration, 3);
2422         ptr = 12;
2423         const __u8 **d=descriptors;
2424         while ( d < pdescr )
2425         {
2426                 memcpy(event+ptr, *d, ((*d)[1])+2);
2427                 ptr+=(*d++)[1];
2428                 ptr+=2;
2429         }
2430         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2431         {
2432                 time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
2433                 if ( (it->first.tm + duration_sec) < now )
2434                         continue;
2435                 memcpy(event+2, it->first.data, 5);
2436                 int bptr = ptr;
2437                 int cnt=0;
2438                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2439                 {
2440                         event[bptr++] = 0x4A;
2441                         __u8 *len = event+(bptr++);
2442                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
2443                         event[bptr++] = (i->tsid & 0xFF);
2444                         event[bptr++] = (i->onid & 0xFF00) >> 8;
2445                         event[bptr++] = (i->onid & 0xFF);
2446                         event[bptr++] = (i->sid & 0xFF00) >> 8;
2447                         event[bptr++] = (i->sid & 0xFF);
2448                         event[bptr++] = 0xB0;
2449                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2450                         *len = ((event+bptr) - len)-1;
2451                 }
2452                 int llen = bptr - 12;
2453                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2454                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2455
2456                 time_t stime = it->first.tm;
2457                 while( tmMap.find(stime) != tmMap.end() )
2458                         ++stime;
2459                 event[6] += (stime - it->first.tm);
2460                 __u16 event_id = 0;
2461                 while( evMap.find(event_id) != evMap.end() )
2462                         ++event_id;
2463                 event[0] = (event_id & 0xFF00) >> 8;
2464                 event[1] = (event_id & 0xFF);
2465                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2466                 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2467                 evMap[event_id] = d;
2468                 tmMap[stime] = d;
2469         }
2470 }
2471
2472 void eEPGCache::channel_data::startPrivateReader()
2473 {
2474         eDVBSectionFilterMask mask;
2475         memset(&mask, 0, sizeof(mask));
2476         mask.pid = m_PrivatePid;
2477         mask.flags = eDVBSectionFilterMask::rfCRC;
2478         mask.data[0] = 0xA0;
2479         mask.mask[0] = 0xFF;
2480         eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2481         if (m_PrevVersion != -1)
2482         {
2483                 mask.data[3] = m_PrevVersion << 1;
2484                 mask.mask[3] = 0x3E;
2485                 mask.mode[3] = 0x3E;
2486         }
2487         seenPrivateSections.clear();
2488         if (!m_PrivateConn)
2489                 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2490         m_PrivateReader->start(mask);
2491 }
2492
2493 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2494 {
2495         if ( seenPrivateSections.find( data[6] ) == seenPrivateSections.end() )
2496         {
2497                 cache->privateSectionRead(m_PrivateService, data);
2498                 seenPrivateSections.insert(data[6]);
2499         }
2500         if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2501         {
2502                 eDebug("[EPGC] private finished");
2503                 eDVBChannelID chid = channel->getChannelID();
2504                 int tmp = chid.original_network_id.get();
2505                 tmp |= 0x80000000; // we use highest bit as private epg indicator
2506                 chid.original_network_id = tmp;
2507                 cache->channelLastUpdated[chid] = eDVBLocalTimeHandler::getInstance()->nowTime();
2508                 m_PrevVersion = (data[5] & 0x3E) >> 1;
2509                 startPrivateReader();
2510         }
2511 }
2512
2513 #endif // ENABLE_PRIVATE_EPG
2514
2515 #ifdef ENABLE_MHW_EPG
2516 void eEPGCache::channel_data::cleanup()
2517 {
2518         m_channels.clear();
2519         m_themes.clear();
2520         m_titles.clear();
2521         m_program_ids.clear();
2522 }
2523
2524 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2525 {
2526         // Names in mhw structs are not strings as they are not '\0' terminated.
2527         // This function converts the mhw name into a string.
2528         // Constraint: "length of out" = "length of in" + 1.
2529         int i;
2530         for ( i=0; i < len_in; i++ )
2531                 out[i] = in[i];
2532
2533         i = len_in - 1;
2534         while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2535                 i--;
2536
2537         out[i+1] = 0;
2538         return out;
2539 }
2540
2541 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2542 // For time of day
2543 {
2544         return_time[0] = toBCD( hours );
2545         return_time[1] = toBCD( minutes );
2546         return_time[2] = 0;
2547 }
2548
2549 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2550 {
2551         timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2552 }
2553
2554 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2555 // For date plus time of day
2556 {
2557         // Remove offset in mhw time.
2558         __u8 local_hours = hours;
2559         if ( hours >= 16 )
2560                 local_hours -= 4;
2561         else if ( hours >= 8 )
2562                 local_hours -= 2;
2563
2564         // As far as we know all mhw time data is sent in central Europe time zone.
2565         // So, temporarily set timezone to western europe
2566         time_t dt = eDVBLocalTimeHandler::getInstance()->nowTime();
2567
2568         char *old_tz = getenv( "TZ" );
2569         putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2570         tzset();
2571
2572         tm *localnow = localtime( &dt );
2573
2574         if (day == 7)
2575                 day = 0;
2576         if ( day + 1 < localnow->tm_wday )              // day + 1 to prevent old events to show for next week.
2577                 day += 7;
2578         if (local_hours <= 5)
2579                 day++;
2580
2581         dt += 3600*24*(day - localnow->tm_wday);        // Shift dt to the recording date (local time zone).
2582         dt += 3600*(local_hours - localnow->tm_hour);  // Shift dt to the recording hour.
2583
2584         tm *recdate = gmtime( &dt );   // This will also take care of DST.
2585
2586         if ( old_tz == NULL )
2587                 unsetenv( "TZ" );
2588         else
2589                 putenv( old_tz );
2590         tzset();
2591
2592         // Calculate MJD according to annex in ETSI EN 300 468
2593         int l=0;
2594         if ( recdate->tm_mon <= 1 )     // Jan or Feb
2595                 l=1;
2596         int mjd = 14956 + recdate->tm_mday + int( (recdate->tm_year - l) * 365.25) +
2597                 int( (recdate->tm_mon + 2 + l * 12) * 30.6001);
2598
2599         return_time[0] = (mjd & 0xFF00)>>8;
2600         return_time[1] = mjd & 0xFF;
2601
2602         timeMHW2DVB( recdate->tm_hour, minutes, return_time+2 );
2603 }
2604
2605 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2606 // data is borrowed from calling proc to save memory space.
2607 {
2608         __u8 name[34];
2609         // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2610         bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2611                 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2612
2613         eit_t *packet = (eit_t *) data;
2614         packet->table_id = 0x50;
2615         packet->section_syntax_indicator = 1;
2616         packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2617         packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2618         packet->version_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2619         packet->current_next_indicator = 0;
2620         packet->section_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2621         packet->last_section_number = 0;        // eEPGCache::sectionRead() will dig this for the moment
2622         packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2623         packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2624         packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2625         packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2626         packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2627         packet->segment_last_table_id = 0x50;
2628
2629         __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2630         std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2631         int prog_title_length = prog_title.length();
2632
2633         int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2634                 prog_title_length + 1;
2635
2636         eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2637         event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2638         event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2639
2640         if (isMHW2)
2641         {
2642                 u_char *data = (u_char*) event_data;
2643                 data[2] = itTitle->second.mhw2_mjd_hi;
2644                 data[3] = itTitle->second.mhw2_mjd_lo;
2645                 data[4] = itTitle->second.mhw2_hours;
2646                 data[5] = itTitle->second.mhw2_minutes;
2647                 data[6] = itTitle->second.mhw2_seconds;
2648                 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2649         }
2650         else
2651         {
2652                 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2653                 (u_char *) event_data + 2 );
2654                 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2655         }
2656
2657         event_data->running_status = 0;
2658         event_data->free_CA_mode = 0;
2659         int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2660
2661         eit_short_event_descriptor_struct *short_event_descriptor =
2662                 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2663         short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2664         short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2665                 prog_title_length - 1;
2666         short_event_descriptor->language_code_1 = 'e';
2667         short_event_descriptor->language_code_2 = 'n';
2668         short_event_descriptor->language_code_3 = 'g';
2669         short_event_descriptor->event_name_length = prog_title_length;
2670         u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2671         memcpy(event_name, prog_title.c_str(), prog_title_length);
2672
2673         // Set text length
2674         event_name[prog_title_length] = 0;
2675
2676         if ( sumText.length() > 0 )
2677         // There is summary info
2678         {
2679                 unsigned int sum_length = sumText.length();
2680                 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2681                 // Store summary in short event descriptor
2682                 {
2683                         // Increase all relevant lengths
2684                         event_name[prog_title_length] = sum_length;
2685                         short_event_descriptor->descriptor_length += sum_length;
2686                         packet_length += sum_length;
2687                         descr_ll += sum_length;
2688                         sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2689                 }
2690                 else
2691                 // Store summary in extended event descriptors
2692                 {
2693                         int remaining_sum_length = sumText.length();
2694                         int nbr_descr = int(remaining_sum_length/247) + 1;
2695                         for ( int i=0; i < nbr_descr; i++)
2696                         // Loop once per extended event descriptor
2697                         {
2698                                 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2699                                 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2700                                 remaining_sum_length -= sum_length;
2701                                 packet_length += 8 + sum_length;
2702                                 descr_ll += 8 + sum_length;
2703
2704                                 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2705                                 ext_event_descriptor->descriptor_length = sum_length + 6;
2706                                 ext_event_descriptor->descriptor_number = i;
2707                                 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2708                                 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2709                                 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2710                                 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2711                                 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2712                                 the_text[-2] = 0;
2713                                 the_text[-1] = sum_length;
2714                                 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2715                         }
2716                 }
2717         }
2718
2719         if (!isMHW2)
2720         {
2721                 // Add content descriptor
2722                 u_char *descriptor = (u_char *) data + packet_length;
2723                 packet_length += 4;
2724                 descr_ll += 4;
2725
2726                 int content_id = 0;
2727                 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2728                 if ( content_descr.find( "FILM" ) != std::string::npos )
2729                         content_id = 0x10;
2730                 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2731                         content_id = 0x40;
2732
2733                 descriptor[0] = 0x54;
2734                 descriptor[1] = 2;
2735                 descriptor[2] = content_id;
2736                 descriptor[3] = 0;
2737         }
2738
2739         event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2740         event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2741
2742         packet->section_length_hi =  ((packet_length - 3)&0xf00)>>8;
2743         packet->section_length_lo =  (packet_length - 3)&0xff;
2744
2745         // Feed the data to eEPGCache::sectionRead()
2746         cache->sectionRead( data, MHW, this );
2747 }
2748
2749 void eEPGCache::channel_data::startTimeout(int msec)
2750 {
2751         m_MHWTimeoutTimer.start(msec,true);
2752         m_MHWTimeoutet=false;
2753 }
2754
2755 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
2756 {
2757         m_MHWFilterMask.pid = pid;
2758         m_MHWFilterMask.data[0] = tid;
2759         m_MHWReader->start(m_MHWFilterMask);
2760 //      eDebug("start 0x%02x 0x%02x", pid, tid);
2761 }
2762
2763 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
2764 {
2765         m_MHWFilterMask2.pid = pid;
2766         m_MHWFilterMask2.data[0] = tid;
2767         if (ext != -1)
2768         {
2769                 m_MHWFilterMask2.data[1] = ext;
2770                 m_MHWFilterMask2.mask[1] = 0xFF;
2771 //              eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
2772         }
2773         else
2774         {
2775                 m_MHWFilterMask2.data[1] = 0;
2776                 m_MHWFilterMask2.mask[1] = 0;
2777 //              eDebug("start 0x%02x 0x%02x", pid, tid);
2778         }
2779         m_MHWReader2->start(m_MHWFilterMask2);
2780 }
2781
2782 void eEPGCache::channel_data::readMHWData(const __u8 *data)
2783 {
2784         if ( m_MHWReader2 )
2785                 m_MHWReader2->stop();
2786
2787         if ( state > 1 || // aborted
2788                 // have si data.. so we dont read mhw data
2789                 (haveData & (SCHEDULE|SCHEDULE_OTHER)) )
2790         {
2791                 eDebug("[EPGC] mhw aborted %d", state);
2792         }
2793         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
2794         // Channels table
2795         {
2796                 int len = ((data[1]&0xf)<<8) + data[2] - 1;
2797                 int record_size = sizeof( mhw_channel_name_t );
2798                 int nbr_records = int (len/record_size);
2799
2800                 for ( int i = 0; i < nbr_records; i++ )
2801                 {
2802                         mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
2803                         m_channels.push_back( *channel );
2804                 }
2805                 haveData |= MHW;
2806
2807                 eDebug("[EPGC] mhw %d channels found", m_channels.size());
2808
2809                 // Channels table has been read, start reading the themes table.
2810                 startMHWReader(0xD3, 0x92);
2811                 return;
2812         }
2813         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
2814         // Themes table
2815         {
2816                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
2817                 int record_size = sizeof( mhw_theme_name_t );
2818                 int nbr_records = int (len/record_size);
2819                 int idx_ptr = 0;
2820                 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
2821                 __u8 idx = 0;
2822                 __u8 sub_idx = 0;
2823                 for ( int i = 0; i < nbr_records; i++ )
2824                 {
2825                         mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
2826                         if ( i >= next_idx )
2827                         {
2828                                 idx = (idx_ptr<<4);
2829                                 idx_ptr++;
2830                                 next_idx = (__u8) *(data + 3 + idx_ptr);
2831                                 sub_idx = 0;
2832                         }
2833                         else
2834                                 sub_idx++;
2835
2836                         m_themes[idx+sub_idx] = *theme;
2837                 }
2838                 eDebug("[EPGC] mhw %d themes found", m_themes.size());
2839                 // Themes table has been read, start reading the titles table.
2840                 startMHWReader(0xD2, 0x90);
2841                 startTimeout(4000);
2842                 return;
2843         }
2844         else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
2845         // Titles table
2846         {
2847                 mhw_title_t *title = (mhw_title_t*) data;
2848
2849                 if ( title->channel_id == 0xFF )        // Separator
2850                         return; // Continue reading of the current table.
2851                 else
2852                 {
2853                         // Create unique key per title
2854                         __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
2855                                 (title->ms.minutes);
2856                         __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
2857                                 ((title->program_id_ml)<<8)|(title->program_id_lo);
2858
2859                         if ( m_titles.find( title_id ) == m_titles.end() )
2860                         {
2861                                 startTimeout(4000);
2862                                 title->mhw2_mjd_hi = 0;
2863                                 title->mhw2_mjd_lo = 0;
2864                                 title->mhw2_duration_hi = 0;
2865                                 title->mhw2_duration_lo = 0;
2866                                 m_titles[ title_id ] = *title;
2867                                 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
2868                                         // program_ids will be used to gather summaries.
2869                                         m_program_ids[ program_id ] = title_id;
2870                                 return; // Continue reading of the current table.
2871                         }
2872                         else if (!checkTimeout())
2873                                 return;
2874                 }
2875                 if ( !m_program_ids.empty())
2876                 {
2877                         // Titles table has been read, there are summaries to read.
2878                         // Start reading summaries, store corresponding titles on the fly.
2879                         startMHWReader(0xD3, 0x90);
2880                         eDebug("[EPGC] mhw %d titles(%d with summary) found",
2881                                 m_titles.size(),
2882                                 m_program_ids.size());
2883                         startTimeout(4000);
2884                         return;
2885                 }
2886         }
2887         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
2888         // Summaries table
2889         {
2890                 mhw_summary_t *summary = (mhw_summary_t*) data;
2891
2892                 // Create unique key per record
2893                 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
2894                         ((summary->program_id_ml)<<8)|(summary->program_id_lo);
2895                 int len = ((data[1]&0xf)<<8) + data[2];
2896
2897                 // ugly workaround to convert const __u8* to char*
2898                 char *tmp=0;
2899                 memcpy(&tmp, &data, sizeof(void*));
2900                 tmp[len+3] = 0; // Terminate as a string.
2901
2902                 std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
2903                 if ( itProgid == m_program_ids.end() )
2904                 { /*    This part is to prevent to looping forever if some summaries are not received yet.
2905                         There is a timeout of 4 sec. after the last successfully read summary. */
2906                         if (!m_program_ids.empty() && !checkTimeout())
2907                                 return; // Continue reading of the current table.
2908                 }
2909                 else
2910                 {
2911                         std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
2912
2913                         unsigned int pos=0;
2914                         while((pos = the_text.find("\r\n")) != std::string::npos)
2915                                 the_text.replace(pos, 2, " ");
2916
2917                         // Find corresponding title, store title and summary in epgcache.
2918                         std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
2919                         if ( itTitle != m_titles.end() )
2920                         {
2921                                 startTimeout(4000);
2922                                 storeTitle( itTitle, the_text, data );
2923                                 m_titles.erase( itTitle );
2924                         }
2925                         m_program_ids.erase( itProgid );
2926                         if ( !m_program_ids.empty() )
2927                                 return; // Continue reading of the current table.
2928                 }
2929         }
2930         eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
2931                 eDVBLocalTimeHandler::getInstance()->nowTime(),
2932                 m_program_ids.size());
2933         // Summaries have been read, titles that have summaries have been stored.
2934         // Now store titles that do not have summaries.
2935         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
2936                 storeTitle( itTitle, "", data );
2937         isRunning &= ~MHW;
2938         m_MHWConn=0;
2939         if ( m_MHWReader )
2940                 m_MHWReader->stop();
2941         if (haveData)
2942                 finishEPG();
2943 }
2944
2945 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
2946 {
2947         int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
2948
2949         if ( m_MHWReader )
2950                 m_MHWReader->stop();
2951
2952         if ( state > 1 || // aborted
2953                 // have si data.. so we dont read mhw data
2954                 (haveData & (eEPGCache::SCHEDULE|eEPGCache::SCHEDULE_OTHER)) )
2955         {
2956                 eDebug("[EPGC] mhw2 aborted %d", state);
2957         }
2958         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
2959         // Channels table
2960         {
2961                 int num_channels = data[120];
2962                 if(dataLen > 120)
2963                 {
2964                         int ptr = 121 + 6 * num_channels;
2965                         if( dataLen > ptr )
2966                         {
2967                                 for( int chid = 0; chid < num_channels; ++chid )
2968                                 {
2969                                         ptr += ( data[ptr] & 0x0f ) + 1;
2970                                         if( dataLen < ptr )
2971                                                 goto abort;
2972                                 }
2973                         }
2974                         else
2975                                 goto abort;
2976                 }
2977                 else
2978                         goto abort;
2979                 // data seems consistent...
2980                 const __u8 *tmp = data+121;
2981                 for (int i=0; i < num_channels; ++i)
2982                 {
2983                         mhw_channel_name_t channel;
2984                         channel.transport_stream_id_hi = *(tmp++);
2985                         channel.transport_stream_id_lo = *(tmp++);
2986                         channel.channel_id_hi = *(tmp++);
2987                         channel.channel_id_lo = *(tmp++);
2988 #warning FIXME hardcoded network_id in mhw2 epg
2989                         channel.network_id_hi = 0; // hardcoded astra 19.2
2990                         channel.network_id_lo = 1;
2991                         m_channels.push_back(channel);
2992                         tmp+=2;
2993                 }
2994                 for (int i=0; i < num_channels; ++i)
2995                 {
2996                         mhw_channel_name_t &channel = m_channels[i];
2997                         int channel_name_len=*(tmp++)&0x0f;
2998                         int x=0;
2999                         for (; x < channel_name_len; ++x)
3000                                 channel.name[x]=*(tmp++);
3001                         channel.name[x+1]=0;
3002                 }
3003                 haveData |= MHW;
3004                 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3005         }
3006         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3007         {
3008                 // Themes table
3009                 eDebug("[EPGC] mhw2 themes nyi");
3010         }
3011         else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3012         // Titles table
3013         {
3014                 int pos=18;
3015                 bool valid=true;
3016                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3017                 bool finish=false;
3018                 if(data[dataLen-1] != 0xff)
3019                         return;
3020                 while( pos < dataLen )
3021                 {
3022                         valid = false;
3023                         pos += 7;
3024                         if( pos < dataLen )
3025                         {
3026                                 pos += 3;
3027                                 if( pos < dataLen )
3028                                 {
3029                                         if( data[pos] > 0xc0 )
3030                                         {
3031                                                 pos += ( data[pos] - 0xc0 );
3032                                                 pos += 4;
3033                                                 if( pos < dataLen )
3034                                                 {
3035                                                         if( data[pos] == 0xff )
3036                                                         {
3037                                                                 ++pos;
3038                                                                 valid = true;
3039                                                         }
3040                                                 }
3041                                         }
3042                                 }
3043                         }
3044                         if( !valid )
3045                         {
3046                                 if (checkTimeout())
3047                                         goto start_summary;
3048                                 return;
3049                         }
3050                 }
3051                 // data seems consistent...
3052                 mhw_title_t title;
3053                 pos = 18;
3054                 while (pos < len)
3055                 {
3056                         title.channel_id = data[pos]+1;
3057                         title.program_id_ml = data[pos+1];
3058                         title.program_id_lo = data[pos+2];
3059                         title.mhw2_mjd_hi = data[pos+3];
3060                         title.mhw2_mjd_lo = data[pos+4];
3061                         title.mhw2_hours = data[pos+5];
3062                         title.mhw2_minutes = data[pos+6];
3063                         title.mhw2_seconds = data[pos+7];
3064                         int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3065                         title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3066                         title.mhw2_duration_lo = duration&0xFF;
3067                         __u8 slen = data[pos+10] & 0x3f;
3068                         __u8 *dest = ((__u8*)title.title)-4;
3069                         memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3070                         memset(dest+slen, 0x20, 33-slen);
3071                         pos += 11 + slen;
3072 //                      not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3073                         __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3074
3075                         // Create unique key per title
3076                         __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3077
3078 //                      eDebug("program_id: %08x, %s", program_id,
3079 //                              std::string((const char *)title.title, (int)(slen > 23 ? 23 : slen)).c_str());
3080
3081                         pos += 4;
3082
3083                         if ( m_titles.find( title_id ) == m_titles.end() )
3084                         {
3085                                 startTimeout(4000);
3086                                 m_titles[ title_id ] = title;
3087                                 if (summary_id != 0xFFFF &&  // no summary avail
3088                                         m_program_ids.find(summary_id) == m_program_ids.end())
3089                                 {
3090                                         m_program_ids[ summary_id ] = title_id;
3091                                 }
3092                         }
3093                         else
3094                         {
3095                                 if ( !checkTimeout() )
3096                                         continue;       // Continue reading of the current table.
3097                                 finish=true;
3098                                 break;
3099                         }
3100                 }
3101 start_summary:
3102                 if (finish)
3103                 {
3104                         eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3105                         if (!m_program_ids.empty())
3106                         {
3107                                 // Titles table has been read, there are summaries to read.
3108                                 // Start reading summaries, store corresponding titles on the fly.
3109                                 startMHWReader2(0x236, 0x96);
3110                                 startTimeout(4000);
3111                                 return;
3112                         }
3113                 }
3114                 else
3115                         return;
3116         }
3117         else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3118         // Summaries table
3119         {
3120                 int len, loop, pos, lenline;
3121                 bool valid;
3122                 valid = true;
3123                 if( dataLen > 18 )
3124                 {
3125                         loop = data[12];
3126                         pos = 13 + loop;
3127                         if( dataLen > pos )
3128                         {
3129                                 loop = data[pos] & 0x0f;
3130                                 pos += 1;
3131                                 if( dataLen > pos )
3132                                 {
3133                                         len = 0;
3134                                         for( ; loop > 0; --loop )
3135                                         {
3136                                                 if( dataLen > (pos+len) )
3137                                                 {
3138                                                         lenline = data[pos+len];
3139                                                         len += lenline + 1;
3140                                                 }
3141                                                 else
3142                                                         valid=false;
3143                                         }
3144                                 }
3145                         }
3146                 }
3147                 else if (!checkTimeout())
3148                         return;  // continue reading
3149                 if (valid && !checkTimeout())
3150                 {
3151                         // data seems consistent...
3152                         __u32 summary_id = (data[3]<<8)|data[4];
3153
3154                         // ugly workaround to convert const __u8* to char*
3155                         char *tmp=0;
3156                         memcpy(&tmp, &data, sizeof(void*));
3157
3158                         len = 0;
3159                         loop = data[12];
3160                         pos = 13 + loop;
3161                         loop = tmp[pos] & 0x0f;
3162                         pos += 1;
3163                         for( ; loop > 0; loop -- )
3164                         {
3165                                 lenline = tmp[pos+len];
3166                                 tmp[pos+len] = ' ';
3167                                 len += lenline + 1;
3168                         }
3169                         if( len > 0 )
3170                             tmp[pos+len] = 0;
3171                         else
3172                                 tmp[pos+1] = 0;
3173
3174                         std::map<__u32, __u32>::iterator itProgid( m_program_ids.find( summary_id ) );
3175                         if ( itProgid == m_program_ids.end() )
3176                         { /*    This part is to prevent to looping forever if some summaries are not received yet.
3177                                 There is a timeout of 4 sec. after the last successfully read summary. */
3178         
3179                                 if ( !m_program_ids.empty() && !checkTimeout() )
3180                                         return; // Continue reading of the current table.
3181                         }
3182                         else
3183                         {
3184                                 startTimeout(4000);
3185                                 std::string the_text = (char *) (data + pos + 1);
3186
3187                                 // Find corresponding title, store title and summary in epgcache.
3188                                 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3189                                 if ( itTitle != m_titles.end() )
3190                                 {
3191                                         storeTitle( itTitle, the_text, data );
3192                                         m_titles.erase( itTitle );
3193                                 }
3194                                 m_program_ids.erase( itProgid );
3195                                 if ( !m_program_ids.empty() )
3196                                         return; // Continue reading of the current table.
3197                         }
3198                 }
3199         }
3200         if (isRunning & eEPGCache::MHW)
3201         {
3202                 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3203                 {
3204                         // Channels table has been read, start reading the themes table.
3205                         startMHWReader2(0x231, 0xC8, 1);
3206                         return;
3207                 }
3208                 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3209                 {
3210                         // Themes table has been read, start reading the titles table.
3211                         startMHWReader2(0x234, 0xe6);
3212                         return;
3213                 }
3214                 else
3215                 {
3216                         // Summaries have been read, titles that have summaries have been stored.
3217                         // Now store titles that do not have summaries.
3218                         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3219                                 storeTitle( itTitle, "", data );
3220                         eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3221                                 eDVBLocalTimeHandler::getInstance()->nowTime(),
3222                                 m_program_ids.size());
3223                 }
3224         }
3225 abort:
3226         isRunning &= ~MHW;
3227         m_MHWConn2=0;
3228         if ( m_MHWReader2 )
3229                 m_MHWReader2->stop();
3230         if (haveData)
3231                 finishEPG();
3232 }
3233 #endif