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