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