Merge branch 'master' of git.opendreambox.org:/git/enigma2
[vuplus_dvbapp] / 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                 {
1374                         __u8 *d=0;
1375                         memcpy(&d, &data, sizeof(__u8*));
1376                         d[0] &= ~0x80;
1377                         reader=m_ViasatReader;
1378                         source=VIASAT;
1379                         map=3;
1380                         break;
1381                 }
1382                 default:
1383                         eDebug("[EPGC] unknown table_id !!!");
1384                         return;
1385         }
1386         tidMap &seenSections = this->seenSections[map];
1387         tidMap &calcedSections = this->calcedSections[map];
1388         if ( state == 1 && calcedSections == seenSections || state > 1 )
1389         {
1390                 eDebugNoNewLine("[EPGC] ");
1391                 switch (source)
1392                 {
1393                         case NOWNEXT:
1394                                 m_NowNextConn=0;
1395                                 eDebugNoNewLine("nownext");
1396                                 break;
1397                         case SCHEDULE:
1398                                 m_ScheduleConn=0;
1399                                 eDebugNoNewLine("schedule");
1400                                 break;
1401                         case SCHEDULE_OTHER:
1402                                 m_ScheduleOtherConn=0;
1403                                 eDebugNoNewLine("schedule other");
1404                                 break;
1405                         case VIASAT:
1406                                 m_ViasatConn=0;
1407                                 eDebugNoNewLine("viasat");
1408                                 break;
1409                         default: eDebugNoNewLine("unknown");break;
1410                 }
1411                 eDebug(" finished(%ld)", ::time(0));
1412                 if ( reader )
1413                         reader->stop();
1414                 isRunning &= ~source;
1415                 if (!isRunning)
1416                         finishEPG();
1417         }
1418         else
1419         {
1420                 eit_t *eit = (eit_t*) data;
1421                 __u32 sectionNo = data[0] << 24;
1422                 sectionNo |= data[3] << 16;
1423                 sectionNo |= data[4] << 8;
1424                 sectionNo |= eit->section_number;
1425
1426                 tidMap::iterator it =
1427                         seenSections.find(sectionNo);
1428
1429                 if ( it == seenSections.end() )
1430                 {
1431                         seenSections.insert(sectionNo);
1432                         calcedSections.insert(sectionNo);
1433                         __u32 tmpval = sectionNo & 0xFFFFFF00;
1434                         __u8 incr = source == NOWNEXT ? 1 : 8;
1435                         for ( int i = 0; i <= eit->last_section_number; i+=incr )
1436                         {
1437                                 if ( i == eit->section_number )
1438                                 {
1439                                         for (int x=i; x <= eit->segment_last_section_number; ++x)
1440                                                 calcedSections.insert(tmpval|(x&0xFF));
1441                                 }
1442                                 else
1443                                         calcedSections.insert(tmpval|(i&0xFF));
1444                         }
1445                         cache->sectionRead(data, source, this);
1446                 }
1447         }
1448 }
1449
1450 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eventData *&result, int direction)
1451 // if t == -1 we search the current event...
1452 {
1453         singleLock s(cache_lock);
1454         uniqueEPGKey key(handleGroup(service));
1455
1456         // check if EPG for this service is ready...
1457         eventCache::iterator It = eventDB.find( key );
1458         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached ?
1459         {
1460                 if (t==-1)
1461                         t = ::time(0);
1462                 timeMap::iterator i = direction <= 0 ? It->second.second.lower_bound(t) :  // find > or equal
1463                         It->second.second.upper_bound(t); // just >
1464                 if ( i != It->second.second.end() )
1465                 {
1466                         if ( direction < 0 || (direction == 0 && i->first > t) )
1467                         {
1468                                 timeMap::iterator x = i;
1469                                 --x;
1470                                 if ( x != It->second.second.end() )
1471                                 {
1472                                         time_t start_time = x->first;
1473                                         if (direction >= 0)
1474                                         {
1475                                                 if (t < start_time)
1476                                                         return -1;
1477                                                 if (t > (start_time+x->second->getDuration()))
1478                                                         return -1;
1479                                         }
1480                                         i = x;
1481                                 }
1482                                 else
1483                                         return -1;
1484                         }
1485                         result = i->second;
1486                         return 0;
1487                 }
1488         }
1489         return -1;
1490 }
1491
1492 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, const eit_event_struct *&result, int direction)
1493 {
1494         singleLock s(cache_lock);
1495         const eventData *data=0;
1496         RESULT ret = lookupEventTime(service, t, data, direction);
1497         if ( !ret && data )
1498                 result = data->get();
1499         return ret;
1500 }
1501
1502 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, Event *& result, int direction)
1503 {
1504         singleLock s(cache_lock);
1505         const eventData *data=0;
1506         RESULT ret = lookupEventTime(service, t, data, direction);
1507         if ( !ret && data )
1508                 result = new Event((uint8_t*)data->get());
1509         return ret;
1510 }
1511
1512 RESULT eEPGCache::lookupEventTime(const eServiceReference &service, time_t t, ePtr<eServiceEvent> &result, int direction)
1513 {
1514         singleLock s(cache_lock);
1515         const eventData *data=0;
1516         RESULT ret = lookupEventTime(service, t, data, direction);
1517         if ( !ret && data )
1518         {
1519                 Event ev((uint8_t*)data->get());
1520                 result = new eServiceEvent();
1521                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1522                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1523         }
1524         return ret;
1525 }
1526
1527 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eventData *&result )
1528 {
1529         singleLock s(cache_lock);
1530         uniqueEPGKey key(handleGroup(service));
1531
1532         eventCache::iterator It = eventDB.find( key );
1533         if ( It != eventDB.end() && !It->second.first.empty() ) // entrys cached?
1534         {
1535                 eventMap::iterator i( It->second.first.find( event_id ));
1536                 if ( i != It->second.first.end() )
1537                 {
1538                         result = i->second;
1539                         return 0;
1540                 }
1541                 else
1542                 {
1543                         result = 0;
1544                         eDebug("[EPGC] event %04x not found in epgcache", event_id);
1545                 }
1546         }
1547         return -1;
1548 }
1549
1550 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, const eit_event_struct *&result)
1551 {
1552         singleLock s(cache_lock);
1553         const eventData *data=0;
1554         RESULT ret = lookupEventId(service, event_id, data);
1555         if ( !ret && data )
1556                 result = data->get();
1557         return ret;
1558 }
1559
1560 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, Event *& result)
1561 {
1562         singleLock s(cache_lock);
1563         const eventData *data=0;
1564         RESULT ret = lookupEventId(service, event_id, data);
1565         if ( !ret && data )
1566                 result = new Event((uint8_t*)data->get());
1567         return ret;
1568 }
1569
1570 RESULT eEPGCache::lookupEventId(const eServiceReference &service, int event_id, ePtr<eServiceEvent> &result)
1571 {
1572         singleLock s(cache_lock);
1573         const eventData *data=0;
1574         RESULT ret = lookupEventId(service, event_id, data);
1575         if ( !ret && data )
1576         {
1577                 Event ev((uint8_t*)data->get());
1578                 result = new eServiceEvent();
1579                 const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)service;
1580                 ret = result->parseFrom(&ev, (ref.getTransportStreamID().get()<<16)|ref.getOriginalNetworkID().get());
1581         }
1582         return ret;
1583 }
1584
1585 RESULT eEPGCache::startTimeQuery(const eServiceReference &service, time_t begin, int minutes)
1586 {
1587         singleLock s(cache_lock);
1588         const eServiceReferenceDVB &ref = (const eServiceReferenceDVB&)handleGroup(service);
1589         if (begin == -1)
1590                 begin = ::time(0);
1591         eventCache::iterator It = eventDB.find(ref);
1592         if ( It != eventDB.end() && It->second.second.size() )
1593         {
1594                 m_timemap_cursor = It->second.second.lower_bound(begin);
1595                 if ( m_timemap_cursor != It->second.second.end() )
1596                 {
1597                         if ( m_timemap_cursor->first != begin )
1598                         {
1599                                 timeMap::iterator x = m_timemap_cursor;
1600                                 --x;
1601                                 if ( x != It->second.second.end() )
1602                                 {
1603                                         time_t start_time = x->first;
1604                                         if ( begin > start_time && begin < (start_time+x->second->getDuration()))
1605                                                 m_timemap_cursor = x;
1606                                 }
1607                         }
1608                 }
1609
1610                 if (minutes != -1)
1611                         m_timemap_end = It->second.second.lower_bound(begin+minutes*60);
1612                 else
1613                         m_timemap_end = It->second.second.end();
1614
1615                 currentQueryTsidOnid = (ref.getTransportStreamID().get()<<16) | ref.getOriginalNetworkID().get();
1616                 return m_timemap_cursor == m_timemap_end ? -1 : 0;
1617         }
1618         return -1;
1619 }
1620
1621 RESULT eEPGCache::getNextTimeEntry(const eventData *& result)
1622 {
1623         if ( m_timemap_cursor != m_timemap_end )
1624         {
1625                 result = m_timemap_cursor++->second;
1626                 return 0;
1627         }
1628         return -1;
1629 }
1630
1631 RESULT eEPGCache::getNextTimeEntry(const eit_event_struct *&result)
1632 {
1633         if ( m_timemap_cursor != m_timemap_end )
1634         {
1635                 result = m_timemap_cursor++->second->get();
1636                 return 0;
1637         }
1638         return -1;
1639 }
1640
1641 RESULT eEPGCache::getNextTimeEntry(Event *&result)
1642 {
1643         if ( m_timemap_cursor != m_timemap_end )
1644         {
1645                 result = new Event((uint8_t*)m_timemap_cursor++->second->get());
1646                 return 0;
1647         }
1648         return -1;
1649 }
1650
1651 RESULT eEPGCache::getNextTimeEntry(ePtr<eServiceEvent> &result)
1652 {
1653         if ( m_timemap_cursor != m_timemap_end )
1654         {
1655                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1656                 result = new eServiceEvent();
1657                 return result->parseFrom(&ev, currentQueryTsidOnid);
1658         }
1659         return -1;
1660 }
1661
1662 void fillTuple(ePyObject tuple, const char *argstring, int argcount, ePyObject service, eServiceEvent *ptr, ePyObject nowTime, ePyObject service_name )
1663 {
1664         ePyObject tmp;
1665         int spos=0, tpos=0;
1666         char c;
1667         while(spos < argcount)
1668         {
1669                 bool inc_refcount=false;
1670                 switch((c=argstring[spos++]))
1671                 {
1672                         case '0': // PyLong 0
1673                                 tmp = PyLong_FromLong(0);
1674                                 break;
1675                         case 'I': // Event Id
1676                                 tmp = ptr ? PyLong_FromLong(ptr->getEventId()) : ePyObject();
1677                                 break;
1678                         case 'B': // Event Begin Time
1679                                 tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
1680                                 break;
1681                         case 'D': // Event Duration
1682                                 tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
1683                                 break;
1684                         case 'T': // Event Title
1685                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
1686                                 break;
1687                         case 'S': // Event Short Description
1688                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
1689                                 break;
1690                         case 'E': // Event Extended Description
1691                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
1692                                 break;
1693                         case 'C': // Current Time
1694                                 tmp = nowTime;
1695                                 inc_refcount = true;
1696                                 break;
1697                         case 'R': // service reference string
1698                                 tmp = service;
1699                                 inc_refcount = true;
1700                                 break;
1701                         case 'n': // short service name
1702                         case 'N': // service name
1703                                 tmp = service_name;
1704                                 inc_refcount = true;
1705                                 break;
1706                         case 'X':
1707                                 ++argcount;
1708                                 continue;
1709                         default:  // ignore unknown
1710                                 eDebug("fillTuple unknown '%c'... insert 'None' in result", c);
1711                 }
1712                 if (!tmp)
1713                 {
1714                         tmp = Py_None;
1715                         inc_refcount = true;
1716                 }
1717                 if (inc_refcount)
1718                         Py_INCREF(tmp);
1719                 PyTuple_SET_ITEM(tuple, tpos++, tmp);
1720         }
1721 }
1722
1723 int handleEvent(eServiceEvent *ptr, ePyObject dest_list, const char* argstring, int argcount, ePyObject service, ePyObject nowTime, ePyObject service_name, ePyObject convertFunc, ePyObject convertFuncArgs)
1724 {
1725         if (convertFunc)
1726         {
1727                 fillTuple(convertFuncArgs, argstring, argcount, service, ptr, nowTime, service_name);
1728                 ePyObject result = PyObject_CallObject(convertFunc, convertFuncArgs);
1729                 if (!result)
1730                 {
1731                         if (service_name)
1732                                 Py_DECREF(service_name);
1733                         if (nowTime)
1734                                 Py_DECREF(nowTime);
1735                         Py_DECREF(convertFuncArgs);
1736                         Py_DECREF(dest_list);
1737                         PyErr_SetString(PyExc_StandardError,
1738                                 "error in convertFunc execute");
1739                         eDebug("error in convertFunc execute");
1740                         return -1;
1741                 }
1742                 PyList_Append(dest_list, result);
1743                 Py_DECREF(result);
1744         }
1745         else
1746         {
1747                 ePyObject tuple = PyTuple_New(argcount);
1748                 fillTuple(tuple, argstring, argcount, service, ptr, nowTime, service_name);
1749                 PyList_Append(dest_list, tuple);
1750                 Py_DECREF(tuple);
1751         }
1752         return 0;
1753 }
1754
1755 // here we get a python list
1756 // the first entry in the list is a python string to specify the format of the returned tuples (in a list)
1757 //   0 = PyLong(0)
1758 //   I = Event Id
1759 //   B = Event Begin Time
1760 //   D = Event Duration
1761 //   T = Event Title
1762 //   S = Event Short Description
1763 //   E = Event Extended Description
1764 //   C = Current Time
1765 //   R = Service Reference
1766 //   N = Service Name
1767 //   n = Short Service Name
1768 //   X = Return a minimum of one tuple per service in the result list... even when no event was found.
1769 //       The returned tuple is filled with all available infos... non avail is filled as None
1770 //       The position and existence of 'X' in the format string has no influence on the result tuple... its completely ignored..
1771 // then for each service follows a tuple
1772 //   first tuple entry is the servicereference (as string... use the ref.toString() function)
1773 //   the second is the type of query
1774 //     2 = event_id
1775 //    -1 = event before given start_time
1776 //     0 = event intersects given start_time
1777 //    +1 = event after given start_time
1778 //   the third
1779 //      when type is eventid it is the event_id
1780 //      when type is time then it is the start_time ( -1 for now_time )
1781 //   the fourth is the end_time .. ( optional .. for query all events in time range)
1782
1783 PyObject *eEPGCache::lookupEvent(ePyObject list, ePyObject convertFunc)
1784 {
1785         ePyObject convertFuncArgs;
1786         int argcount=0;
1787         const char *argstring=NULL;
1788         if (!PyList_Check(list))
1789         {
1790                 PyErr_SetString(PyExc_StandardError,
1791                         "type error");
1792                 eDebug("no list");
1793                 return NULL;
1794         }
1795         int listIt=0;
1796         int listSize=PyList_Size(list);
1797         if (!listSize)
1798         {
1799                 PyErr_SetString(PyExc_StandardError,
1800                         "not params given");
1801                 eDebug("not params given");
1802                 return NULL;
1803         }
1804         else 
1805         {
1806                 ePyObject argv=PyList_GET_ITEM(list, 0); // borrowed reference!
1807                 if (PyString_Check(argv))
1808                 {
1809                         argstring = PyString_AS_STRING(argv);
1810                         ++listIt;
1811                 }
1812                 else
1813                         argstring = "I"; // just event id as default
1814                 argcount = strlen(argstring);
1815 //              eDebug("have %d args('%s')", argcount, argstring);
1816         }
1817
1818         bool forceReturnOne = strchr(argstring, 'X') ? true : false;
1819         if (forceReturnOne)
1820                 --argcount;
1821
1822         if (convertFunc)
1823         {
1824                 if (!PyCallable_Check(convertFunc))
1825                 {
1826                         PyErr_SetString(PyExc_StandardError,
1827                                 "convertFunc must be callable");
1828                         eDebug("convertFunc is not callable");
1829                         return NULL;
1830                 }
1831                 convertFuncArgs = PyTuple_New(argcount);
1832         }
1833
1834         ePyObject nowTime = strchr(argstring, 'C') ?
1835                 PyLong_FromLong(::time(0)) :
1836                 ePyObject();
1837
1838         int must_get_service_name = strchr(argstring, 'N') ? 1 : strchr(argstring, 'n') ? 2 : 0;
1839
1840         // create dest list
1841         ePyObject dest_list=PyList_New(0);
1842         while(listSize > listIt)
1843         {
1844                 ePyObject item=PyList_GET_ITEM(list, listIt++); // borrowed reference!
1845                 if (PyTuple_Check(item))
1846                 {
1847                         bool service_changed=false;
1848                         int type=0;
1849                         long event_id=-1;
1850                         time_t stime=-1;
1851                         int minutes=0;
1852                         int tupleSize=PyTuple_Size(item);
1853                         int tupleIt=0;
1854                         ePyObject service;
1855                         while(tupleSize > tupleIt)  // parse query args
1856                         {
1857                                 ePyObject entry=PyTuple_GET_ITEM(item, tupleIt); // borrowed reference!
1858                                 switch(tupleIt++)
1859                                 {
1860                                         case 0:
1861                                         {
1862                                                 if (!PyString_Check(entry))
1863                                                 {
1864                                                         eDebug("tuple entry 0 is no a string");
1865                                                         goto skip_entry;
1866                                                 }
1867                                                 service = entry;
1868                                                 break;
1869                                         }
1870                                         case 1:
1871                                                 type=PyInt_AsLong(entry);
1872                                                 if (type < -1 || type > 2)
1873                                                 {
1874                                                         eDebug("unknown type %d", type);
1875                                                         goto skip_entry;
1876                                                 }
1877                                                 break;
1878                                         case 2:
1879                                                 event_id=stime=PyInt_AsLong(entry);
1880                                                 break;
1881                                         case 3:
1882                                                 minutes=PyInt_AsLong(entry);
1883                                                 break;
1884                                         default:
1885                                                 eDebug("unneeded extra argument");
1886                                                 break;
1887                                 }
1888                         }
1889
1890                         if (minutes && stime == -1)
1891                                 stime = ::time(0);
1892
1893                         eServiceReference ref(handleGroup(eServiceReference(PyString_AS_STRING(service))));
1894                         if (ref.type != eServiceReference::idDVB)
1895                         {
1896                                 eDebug("service reference for epg query is not valid");
1897                                 continue;
1898                         }
1899
1900                         // redirect subservice querys to parent service
1901                         eServiceReferenceDVB &dvb_ref = (eServiceReferenceDVB&)ref;
1902                         if (dvb_ref.getParentTransportStreamID().get()) // linkage subservice
1903                         {
1904                                 eServiceCenterPtr service_center;
1905                                 if (!eServiceCenter::getPrivInstance(service_center))
1906                                 {
1907                                         dvb_ref.setTransportStreamID( dvb_ref.getParentTransportStreamID() );
1908                                         dvb_ref.setServiceID( dvb_ref.getParentServiceID() );
1909                                         dvb_ref.setParentTransportStreamID(eTransportStreamID(0));
1910                                         dvb_ref.setParentServiceID(eServiceID(0));
1911                                         dvb_ref.name="";
1912                                         service = PyString_FromString(dvb_ref.toString().c_str());
1913                                         service_changed = true;
1914                                 }
1915                         }
1916
1917                         ePyObject service_name;
1918                         if (must_get_service_name)
1919                         {
1920                                 ePtr<iStaticServiceInformation> sptr;
1921                                 eServiceCenterPtr service_center;
1922                                 eServiceCenter::getPrivInstance(service_center);
1923                                 if (service_center)
1924                                 {
1925                                         service_center->info(ref, sptr);
1926                                         if (sptr)
1927                                         {
1928                                                 std::string name;
1929                                                 sptr->getName(ref, name);
1930
1931                                                 if (must_get_service_name == 1)
1932                                                 {
1933                                                         size_t pos;
1934                                                         // filter short name brakets
1935                                                         while((pos = name.find("\xc2\x86")) != std::string::npos)
1936                                                                 name.erase(pos,2);
1937                                                         while((pos = name.find("\xc2\x87")) != std::string::npos)
1938                                                                 name.erase(pos,2);
1939                                                 }
1940                                                 else
1941                                                         name = buildShortName(name);
1942
1943                                                 if (name.length())
1944                                                         service_name = PyString_FromString(name.c_str());
1945                                         }
1946                                 }
1947                                 if (!service_name)
1948                                         service_name = PyString_FromString("<n/a>");
1949                         }
1950                         if (minutes)
1951                         {
1952                                 singleLock s(cache_lock);
1953                                 if (!startTimeQuery(ref, stime, minutes))
1954                                 {
1955                                         while ( m_timemap_cursor != m_timemap_end )
1956                                         {
1957                                                 Event ev((uint8_t*)m_timemap_cursor++->second->get());
1958                                                 eServiceEvent evt;
1959                                                 evt.parseFrom(&ev, currentQueryTsidOnid);
1960                                                 if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1961                                                         return 0;  // error
1962                                         }
1963                                 }
1964                                 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1965                                         return 0;  // error
1966                         }
1967                         else
1968                         {
1969                                 eServiceEvent evt;
1970                                 const eventData *ev_data=0;
1971                                 if (stime)
1972                                 {
1973                                         singleLock s(cache_lock);
1974                                         if (type == 2)
1975                                                 lookupEventId(ref, event_id, ev_data);
1976                                         else
1977                                                 lookupEventTime(ref, stime, ev_data, type);
1978                                         if (ev_data)
1979                                         {
1980                                                 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
1981                                                 Event ev((uint8_t*)ev_data->get());
1982                                                 evt.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
1983                                         }
1984                                 }
1985                                 if (ev_data)
1986                                 {
1987                                         if (handleEvent(&evt, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1988                                                 return 0; // error
1989                                 }
1990                                 else if (forceReturnOne && handleEvent(0, dest_list, argstring, argcount, service, nowTime, service_name, convertFunc, convertFuncArgs))
1991                                         return 0; // error
1992                         }
1993                         if (service_changed)
1994                                 Py_DECREF(service);
1995                         if (service_name)
1996                                 Py_DECREF(service_name);
1997                 }
1998 skip_entry:
1999                 ;
2000         }
2001         if (convertFuncArgs)
2002                 Py_DECREF(convertFuncArgs);
2003         if (nowTime)
2004                 Py_DECREF(nowTime);
2005         return dest_list;
2006 }
2007
2008 void fillTuple2(ePyObject tuple, const char *argstring, int argcount, eventData *evData, eServiceEvent *ptr, ePyObject service_name, ePyObject service_reference)
2009 {
2010         ePyObject tmp;
2011         int pos=0;
2012         while(pos < argcount)
2013         {
2014                 bool inc_refcount=false;
2015                 switch(argstring[pos])
2016                 {
2017                         case '0': // PyLong 0
2018                                 tmp = PyLong_FromLong(0);
2019                                 break;
2020                         case 'I': // Event Id
2021                                 tmp = PyLong_FromLong(evData->getEventID());
2022                                 break;
2023                         case 'B': // Event Begin Time
2024                                 if (ptr)
2025                                         tmp = ptr ? PyLong_FromLong(ptr->getBeginTime()) : ePyObject();
2026                                 else
2027                                         tmp = PyLong_FromLong(evData->getStartTime());
2028                                 break;
2029                         case 'D': // Event Duration
2030                                 if (ptr)
2031                                         tmp = ptr ? PyLong_FromLong(ptr->getDuration()) : ePyObject();
2032                                 else
2033                                         tmp = PyLong_FromLong(evData->getDuration());
2034                                 break;
2035                         case 'T': // Event Title
2036                                 tmp = ptr ? PyString_FromString(ptr->getEventName().c_str()) : ePyObject();
2037                                 break;
2038                         case 'S': // Event Short Description
2039                                 tmp = ptr ? PyString_FromString(ptr->getShortDescription().c_str()) : ePyObject();
2040                                 break;
2041                         case 'E': // Event Extended Description
2042                                 tmp = ptr ? PyString_FromString(ptr->getExtendedDescription().c_str()) : ePyObject();
2043                                 break;
2044                         case 'R': // service reference string
2045                                 tmp = service_reference;
2046                                 inc_refcount = true;
2047                                 break;
2048                         case 'n': // short service name
2049                         case 'N': // service name
2050                                 tmp = service_name;
2051                                 inc_refcount = true;
2052                                 break;
2053                         default:  // ignore unknown
2054                                 eDebug("fillTuple2 unknown '%c'... insert None in Result", argstring[pos]);
2055                 }
2056                 if (!tmp)
2057                 {
2058                         tmp = Py_None;
2059                         inc_refcount = true;
2060                 }
2061                 if (inc_refcount)
2062                         Py_INCREF(tmp);
2063                 PyTuple_SET_ITEM(tuple, pos++, tmp);
2064         }
2065 }
2066
2067 // here we get a python tuple
2068 // the first entry in the tuple is a python string to specify the format of the returned tuples (in a list)
2069 //   I = Event Id
2070 //   B = Event Begin Time
2071 //   D = Event Duration
2072 //   T = Event Title
2073 //   S = Event Short Description
2074 //   E = Event Extended Description
2075 //   R = Service Reference
2076 //   N = Service Name
2077 //   n = Short Service Name
2078 //  the second tuple entry is the MAX matches value
2079 //  the third tuple entry is the type of query
2080 //     0 = search for similar broadcastings (SIMILAR_BROADCASTINGS_SEARCH)
2081 //     1 = search events with exactly title name (EXAKT_TITLE_SEARCH)
2082 //     2 = search events with text in title name (PARTIAL_TITLE_SEARCH)
2083 //  when type is 0 (SIMILAR_BROADCASTINGS_SEARCH)
2084 //   the fourth is the servicereference string
2085 //   the fifth is the eventid
2086 //  when type is 1 or 2 (EXAKT_TITLE_SEARCH or PARTIAL_TITLE_SEARCH)
2087 //   the fourth is the search text
2088 //   the fifth is
2089 //     0 = case sensitive (CASE_CHECK)
2090 //     1 = case insensitive (NO_CASECHECK)
2091
2092 PyObject *eEPGCache::search(ePyObject arg)
2093 {
2094         ePyObject ret;
2095         int descridx = -1;
2096         __u32 descr[512];
2097         int eventid = -1;
2098         const char *argstring=0;
2099         char *refstr=0;
2100         int argcount=0;
2101         int querytype=-1;
2102         bool needServiceEvent=false;
2103         int maxmatches=0;
2104         int must_get_service_name = 0;
2105         bool must_get_service_reference = false;
2106
2107         if (PyTuple_Check(arg))
2108         {
2109                 int tuplesize=PyTuple_Size(arg);
2110                 if (tuplesize > 0)
2111                 {
2112                         ePyObject obj = PyTuple_GET_ITEM(arg,0);
2113                         if (PyString_Check(obj))
2114                         {
2115 #if PY_VERSION_HEX < 0x02060000
2116                                 argcount = PyString_GET_SIZE(obj);
2117 #else
2118                                 argcount = PyString_Size(obj);
2119 #endif
2120                                 argstring = PyString_AS_STRING(obj);
2121                                 for (int i=0; i < argcount; ++i)
2122                                         switch(argstring[i])
2123                                         {
2124                                         case 'S':
2125                                         case 'E':
2126                                         case 'T':
2127                                                 needServiceEvent=true;
2128                                                 break;
2129                                         case 'N':
2130                                                 must_get_service_name = 1;
2131                                                 break;
2132                                         case 'n':
2133                                                 must_get_service_name = 2;
2134                                                 break;
2135                                         case 'R':
2136                                                 must_get_service_reference = true;
2137                                                 break;
2138                                         default:
2139                                                 break;
2140                                         }
2141                         }
2142                         else
2143                         {
2144                                 PyErr_SetString(PyExc_StandardError,
2145                                         "type error");
2146                                 eDebug("tuple arg 0 is not a string");
2147                                 return NULL;
2148                         }
2149                 }
2150                 if (tuplesize > 1)
2151                         maxmatches = PyLong_AsLong(PyTuple_GET_ITEM(arg, 1));
2152                 if (tuplesize > 2)
2153                 {
2154                         querytype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 2));
2155                         if (tuplesize > 4 && querytype == 0)
2156                         {
2157                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2158                                 if (PyString_Check(obj))
2159                                 {
2160                                         refstr = PyString_AS_STRING(obj);
2161                                         eServiceReferenceDVB ref(refstr);
2162                                         if (ref.valid())
2163                                         {
2164                                                 eventid = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2165                                                 singleLock s(cache_lock);
2166                                                 const eventData *evData = 0;
2167                                                 lookupEventId(ref, eventid, evData);
2168                                                 if (evData)
2169                                                 {
2170                                                         __u8 *data = evData->EITdata;
2171                                                         int tmp = evData->ByteSize-10;
2172                                                         __u32 *p = (__u32*)(data+10);
2173                                                                 // search short and extended event descriptors
2174                                                         while(tmp>3)
2175                                                         {
2176                                                                 __u32 crc = *p++;
2177                                                                 descriptorMap::iterator it =
2178                                                                         eventData::descriptors.find(crc);
2179                                                                 if (it != eventData::descriptors.end())
2180                                                                 {
2181                                                                         __u8 *descr_data = it->second.second;
2182                                                                         switch(descr_data[0])
2183                                                                         {
2184                                                                         case 0x4D ... 0x4E:
2185                                                                                 descr[++descridx]=crc;
2186                                                                         default:
2187                                                                                 break;
2188                                                                         }
2189                                                                 }
2190                                                                 tmp-=4;
2191                                                         }
2192                                                 }
2193                                                 if (descridx<0)
2194                                                         eDebug("event not found");
2195                                         }
2196                                         else
2197                                         {
2198                                                 PyErr_SetString(PyExc_StandardError, "type error");
2199                                                 eDebug("tuple arg 4 is not a valid service reference string");
2200                                                 return NULL;
2201                                         }
2202                                 }
2203                                 else
2204                                 {
2205                                         PyErr_SetString(PyExc_StandardError, "type error");
2206                                         eDebug("tuple arg 4 is not a string");
2207                                         return NULL;
2208                                 }
2209                         }
2210                         else if (tuplesize > 4 && (querytype == 1 || querytype == 2) )
2211                         {
2212                                 ePyObject obj = PyTuple_GET_ITEM(arg, 3);
2213                                 if (PyString_Check(obj))
2214                                 {
2215                                         int casetype = PyLong_AsLong(PyTuple_GET_ITEM(arg, 4));
2216                                         const char *str = PyString_AS_STRING(obj);
2217 #if PY_VERSION_HEX < 0x02060000
2218                                         int textlen = PyString_GET_SIZE(obj);
2219 #else
2220                                         int textlen = PyString_Size(obj);
2221 #endif
2222                                         if (querytype == 1)
2223                                                 eDebug("lookup for events with '%s' as title(%s)", str, casetype?"ignore case":"case sensitive");
2224                                         else
2225                                                 eDebug("lookup for events with '%s' in title(%s)", str, casetype?"ignore case":"case sensitive");
2226                                         singleLock s(cache_lock);
2227                                         for (descriptorMap::iterator it(eventData::descriptors.begin());
2228                                                 it != eventData::descriptors.end() && descridx < 511; ++it)
2229                                         {
2230                                                 __u8 *data = it->second.second;
2231                                                 if ( data[0] == 0x4D ) // short event descriptor
2232                                                 {
2233                                                         int title_len = data[5];
2234                                                         if ( querytype == 1 )
2235                                                         {
2236                                                                 int offs = 6;
2237                                                                 // skip DVB-Text Encoding!
2238                                                                 if (data[6] == 0x10)
2239                                                                 {
2240                                                                         offs+=3;
2241                                                                         title_len-=3;
2242                                                                 }
2243                                                                 else if(data[6] > 0 && data[6] < 0x20)
2244                                                                 {
2245                                                                         offs+=1;
2246                                                                         title_len-=1;
2247                                                                 }
2248                                                                 if (title_len != textlen)
2249                                                                         continue;
2250                                                                 if ( casetype )
2251                                                                 {
2252                                                                         if ( !strncasecmp((const char*)data+offs, str, title_len) )
2253                                                                         {
2254 //                                                                              std::string s((const char*)data+offs, title_len);
2255 //                                                                              eDebug("match1 %s %s", str, s.c_str() );
2256                                                                                 descr[++descridx] = it->first;
2257                                                                         }
2258                                                                 }
2259                                                                 else if ( !strncmp((const char*)data+offs, str, title_len) )
2260                                                                 {
2261 //                                                                      std::string s((const char*)data+offs, title_len);
2262 //                                                                      eDebug("match2 %s %s", str, s.c_str() );
2263                                                                         descr[++descridx] = it->first;
2264                                                                 }
2265                                                         }
2266                                                         else
2267                                                         {
2268                                                                 int idx=0;
2269                                                                 while((title_len-idx) >= textlen)
2270                                                                 {
2271                                                                         if (casetype)
2272                                                                         {
2273                                                                                 if (!strncasecmp((const char*)data+6+idx, str, textlen) )
2274                                                                                 {
2275                                                                                         descr[++descridx] = it->first;
2276 //                                                                                      std::string s((const char*)data+6, title_len);
2277 //                                                                                      eDebug("match 3 %s %s", str, s.c_str() );
2278                                                                                         break;
2279                                                                                 }
2280                                                                         }
2281                                                                         else if (!strncmp((const char*)data+6+idx, str, textlen) )
2282                                                                         {
2283                                                                                 descr[++descridx] = it->first;
2284 //                                                                              std::string s((const char*)data+6, title_len);
2285 //                                                                              eDebug("match 4 %s %s", str, s.c_str() );
2286                                                                                 break;
2287                                                                         }
2288                                                                         ++idx;
2289                                                                 }
2290                                                         }
2291                                                 }
2292                                         }
2293                                 }
2294                                 else
2295                                 {
2296                                         PyErr_SetString(PyExc_StandardError,
2297                                                 "type error");
2298                                         eDebug("tuple arg 4 is not a string");
2299                                         return NULL;
2300                                 }
2301                         }
2302                         else
2303                         {
2304                                 PyErr_SetString(PyExc_StandardError,
2305                                         "type error");
2306                                 eDebug("tuple arg 3(%d) is not a known querytype(0, 1, 2)", querytype);
2307                                 return NULL;
2308                         }
2309                 }
2310                 else
2311                 {
2312                         PyErr_SetString(PyExc_StandardError,
2313                                 "type error");
2314                         eDebug("not enough args in tuple");
2315                         return NULL;
2316                 }
2317         }
2318         else
2319         {
2320                 PyErr_SetString(PyExc_StandardError,
2321                         "type error");
2322                 eDebug("arg 0 is not a tuple");
2323                 return NULL;
2324         }
2325
2326         if (descridx > -1)
2327         {
2328                 int maxcount=maxmatches;
2329                 eServiceReferenceDVB ref(refstr?(const eServiceReferenceDVB&)handleGroup(eServiceReference(refstr)):eServiceReferenceDVB(""));
2330                 // ref is only valid in SIMILAR_BROADCASTING_SEARCH
2331                 // in this case we start searching with the base service
2332                 bool first = ref.valid() ? true : false;
2333                 singleLock s(cache_lock);
2334                 eventCache::iterator cit(ref.valid() ? eventDB.find(ref) : eventDB.begin());
2335                 while(cit != eventDB.end() && maxcount)
2336                 {
2337                         if ( ref.valid() && !first && cit->first == ref )
2338                         {
2339                                 // do not scan base service twice ( only in SIMILAR BROADCASTING SEARCH )
2340                                 ++cit;
2341                                 continue;
2342                         }
2343                         ePyObject service_name;
2344                         ePyObject service_reference;
2345                         timeMap &evmap = cit->second.second;
2346                         // check all events
2347                         for (timeMap::iterator evit(evmap.begin()); evit != evmap.end() && maxcount; ++evit)
2348                         {
2349                                 int evid = evit->second->getEventID();
2350                                 if ( evid == eventid)
2351                                         continue;
2352                                 __u8 *data = evit->second->EITdata;
2353                                 int tmp = evit->second->ByteSize-10;
2354                                 __u32 *p = (__u32*)(data+10);
2355                                 // check if any of our descriptor used by this event
2356                                 int cnt=-1;
2357                                 while(tmp>3)
2358                                 {
2359                                         __u32 crc32 = *p++;
2360                                         for ( int i=0; i <= descridx; ++i)
2361                                         {
2362                                                 if (descr[i] == crc32)  // found...
2363                                                         ++cnt;
2364                                         }
2365                                         tmp-=4;
2366                                 }
2367                                 if ( (querytype == 0 && cnt == descridx) ||
2368                                          ((querytype == 1 || querytype == 2) && cnt != -1) )
2369                                 {
2370                                         const uniqueEPGKey &service = cit->first;
2371                                         eServiceReference ref =
2372                                                 eDVBDB::getInstance()->searchReference(service.tsid, service.onid, service.sid);
2373                                         if (ref.valid())
2374                                         {
2375                                         // create servive event
2376                                                 eServiceEvent ptr;
2377                                                 const eventData *ev_data=0;
2378                                                 if (needServiceEvent)
2379                                                 {
2380                                                         if (lookupEventId(ref, evid, ev_data))
2381                                                                 eDebug("event not found !!!!!!!!!!!");
2382                                                         else
2383                                                         {
2384                                                                 const eServiceReferenceDVB &dref = (const eServiceReferenceDVB&)ref;
2385                                                                 Event ev((uint8_t*)ev_data->get());
2386                                                                 ptr.parseFrom(&ev, (dref.getTransportStreamID().get()<<16)|dref.getOriginalNetworkID().get());
2387                                                         }
2388                                                 }
2389                                         // create service name
2390                                                 if (must_get_service_name && !service_name)
2391                                                 {
2392                                                         ePtr<iStaticServiceInformation> sptr;
2393                                                         eServiceCenterPtr service_center;
2394                                                         eServiceCenter::getPrivInstance(service_center);
2395                                                         if (service_center)
2396                                                         {
2397                                                                 service_center->info(ref, sptr);
2398                                                                 if (sptr)
2399                                                                 {
2400                                                                         std::string name;
2401                                                                         sptr->getName(ref, name);
2402
2403                                                                         if (must_get_service_name == 1)
2404                                                                         {
2405                                                                                 size_t pos;
2406                                                                                 // filter short name brakets
2407                                                                                 while((pos = name.find("\xc2\x86")) != std::string::npos)
2408                                                                                         name.erase(pos,2);
2409                                                                                 while((pos = name.find("\xc2\x87")) != std::string::npos)
2410                                                                                         name.erase(pos,2);
2411                                                                         }
2412                                                                         else
2413                                                                                 name = buildShortName(name);
2414
2415                                                                         if (name.length())
2416                                                                                 service_name = PyString_FromString(name.c_str());
2417                                                                 }
2418                                                         }
2419                                                         if (!service_name)
2420                                                                 service_name = PyString_FromString("<n/a>");
2421                                                 }
2422                                         // create servicereference string
2423                                                 if (must_get_service_reference && !service_reference)
2424                                                         service_reference = PyString_FromString(ref.toString().c_str());
2425                                         // create list
2426                                                 if (!ret)
2427                                                         ret = PyList_New(0);
2428                                         // create tuple
2429                                                 ePyObject tuple = PyTuple_New(argcount);
2430                                         // fill tuple
2431                                                 fillTuple2(tuple, argstring, argcount, evit->second, ev_data ? &ptr : 0, service_name, service_reference);
2432                                                 PyList_Append(ret, tuple);
2433                                                 Py_DECREF(tuple);
2434                                                 --maxcount;
2435                                         }
2436                                 }
2437                         }
2438                         if (service_name)
2439                                 Py_DECREF(service_name);
2440                         if (service_reference)
2441                                 Py_DECREF(service_reference);
2442                         if (first)
2443                         {
2444                                 // now start at first service in epgcache database ( only in SIMILAR BROADCASTING SEARCH )
2445                                 first=false;
2446                                 cit=eventDB.begin();
2447                         }
2448                         else
2449                                 ++cit;
2450                 }
2451         }
2452
2453         if (!ret)
2454                 Py_RETURN_NONE;
2455
2456         return ret;
2457 }
2458
2459 #ifdef ENABLE_PRIVATE_EPG
2460 #include <dvbsi++/descriptor_tag.h>
2461 #include <dvbsi++/unknown_descriptor.h>
2462 #include <dvbsi++/private_data_specifier_descriptor.h>
2463
2464 void eEPGCache::PMTready(eDVBServicePMTHandler *pmthandler)
2465 {
2466         ePtr<eTable<ProgramMapSection> > ptr;
2467         if (!pmthandler->getPMT(ptr) && ptr)
2468         {
2469                 std::vector<ProgramMapSection*>::const_iterator i;
2470                 for (i = ptr->getSections().begin(); i != ptr->getSections().end(); ++i)
2471                 {
2472                         const ProgramMapSection &pmt = **i;
2473
2474                         ElementaryStreamInfoConstIterator es;
2475                         for (es = pmt.getEsInfo()->begin(); es != pmt.getEsInfo()->end(); ++es)
2476                         {
2477                                 int tmp=0;
2478                                 switch ((*es)->getType())
2479                                 {
2480                                 case 0x05: // private
2481                                         for (DescriptorConstIterator desc = (*es)->getDescriptors()->begin();
2482                                                 desc != (*es)->getDescriptors()->end(); ++desc)
2483                                         {
2484                                                 switch ((*desc)->getTag())
2485                                                 {
2486                                                         case PRIVATE_DATA_SPECIFIER_DESCRIPTOR:
2487                                                                 if (((PrivateDataSpecifierDescriptor*)(*desc))->getPrivateDataSpecifier() == 190)
2488                                                                         tmp |= 1;
2489                                                                 break;
2490                                                         case 0x90:
2491                                                         {
2492                                                                 UnknownDescriptor *descr = (UnknownDescriptor*)*desc;
2493                                                                 int descr_len = descr->getLength();
2494                                                                 if (descr_len == 4)
2495                                                                 {
2496                                                                         uint8_t data[descr_len+2];
2497                                                                         descr->writeToBuffer(data);
2498                                                                         if ( !data[2] && !data[3] && data[4] == 0xFF && data[5] == 0xFF )
2499                                                                                 tmp |= 2;
2500                                                                 }
2501                                                                 break;
2502                                                         }
2503                                                         default:
2504                                                                 break;
2505                                                 }
2506                                         }
2507                                 default:
2508                                         break;
2509                                 }
2510                                 if (tmp==3)
2511                                 {
2512                                         eServiceReferenceDVB ref;
2513                                         if (!pmthandler->getServiceReference(ref))
2514                                         {
2515                                                 int pid = (*es)->getPid();
2516                                                 messages.send(Message(Message::got_private_pid, ref, pid));
2517                                                 return;
2518                                         }
2519                                 }
2520                         }
2521                 }
2522         }
2523         else
2524                 eDebug("PMTready but no pmt!!");
2525 }
2526
2527 struct date_time
2528 {
2529         __u8 data[5];
2530         time_t tm;
2531         date_time( const date_time &a )
2532         {
2533                 memcpy(data, a.data, 5);
2534                 tm = a.tm;
2535         }
2536         date_time( const __u8 data[5])
2537         {
2538                 memcpy(this->data, data, 5);
2539                 tm = parseDVBtime(data[0], data[1], data[2], data[3], data[4]);
2540         }
2541         date_time()
2542         {
2543         }
2544         const __u8& operator[](int pos) const
2545         {
2546                 return data[pos];
2547         }
2548 };
2549
2550 struct less_datetime
2551 {
2552         bool operator()( const date_time &a, const date_time &b ) const
2553         {
2554                 return abs(a.tm-b.tm) < 360 ? false : a.tm < b.tm;
2555         }
2556 };
2557
2558 void eEPGCache::privateSectionRead(const uniqueEPGKey &current_service, const __u8 *data)
2559 {
2560         contentMap &content_time_table = content_time_tables[current_service];
2561         singleLock s(cache_lock);
2562         std::map< date_time, std::list<uniqueEPGKey>, less_datetime > start_times;
2563         eventMap &evMap = eventDB[current_service].first;
2564         timeMap &tmMap = eventDB[current_service].second;
2565         int ptr=8;
2566         int content_id = data[ptr++] << 24;
2567         content_id |= data[ptr++] << 16;
2568         content_id |= data[ptr++] << 8;
2569         content_id |= data[ptr++];
2570
2571         contentTimeMap &time_event_map =
2572                 content_time_table[content_id];
2573         for ( contentTimeMap::iterator it( time_event_map.begin() );
2574                 it != time_event_map.end(); ++it )
2575         {
2576                 eventMap::iterator evIt( evMap.find(it->second.second) );
2577                 if ( evIt != evMap.end() )
2578                 {
2579                         delete evIt->second;
2580                         evMap.erase(evIt);
2581                 }
2582                 tmMap.erase(it->second.first);
2583         }
2584         time_event_map.clear();
2585
2586         __u8 duration[3];
2587         memcpy(duration, data+ptr, 3);
2588         ptr+=3;
2589         int duration_sec =
2590                 fromBCD(duration[0])*3600+fromBCD(duration[1])*60+fromBCD(duration[2]);
2591
2592         const __u8 *descriptors[65];
2593         const __u8 **pdescr = descriptors;
2594
2595         int descriptors_length = (data[ptr++]&0x0F) << 8;
2596         descriptors_length |= data[ptr++];
2597         while ( descriptors_length > 1 )
2598         {
2599                 int descr_type = data[ptr];
2600                 int descr_len = data[ptr+1];
2601                 descriptors_length -= 2;
2602                 if (descriptors_length >= descr_len)
2603                 {
2604                         descriptors_length -= descr_len;
2605                         if ( descr_type == 0xf2 && descr_len > 5)
2606                         {
2607                                 ptr+=2;
2608                                 int tsid = data[ptr++] << 8;
2609                                 tsid |= data[ptr++];
2610                                 int onid = data[ptr++] << 8;
2611                                 onid |= data[ptr++];
2612                                 int sid = data[ptr++] << 8;
2613                                 sid |= data[ptr++];
2614
2615 // WORKAROUND for wrong transmitted epg data (01.10.2007)
2616                                 if ( onid == 0x85 )
2617                                 {
2618                                         switch( (tsid << 16) | sid )
2619                                         {
2620                                                 case 0x01030b: sid = 0x1b; tsid = 4; break;  // Premiere Win
2621                                                 case 0x0300f0: sid = 0xe0; tsid = 2; break;
2622                                                 case 0x0300f1: sid = 0xe1; tsid = 2; break;
2623                                                 case 0x0300f5: sid = 0xdc; break;
2624                                                 case 0x0400d2: sid = 0xe2; tsid = 0x11; break;
2625                                                 case 0x1100d3: sid = 0xe3; break;
2626                                                 case 0x0100d4: sid = 0xe4; tsid = 4; break;
2627                                         }
2628                                 }
2629 ////////////////////////////////////////////
2630
2631                                 uniqueEPGKey service( sid, onid, tsid );
2632                                 descr_len -= 6;
2633                                 while( descr_len > 2 )
2634                                 {
2635                                         __u8 datetime[5];
2636                                         datetime[0] = data[ptr++];
2637                                         datetime[1] = data[ptr++];
2638                                         int tmp_len = data[ptr++];
2639                                         descr_len -= 3;
2640                                         if (descr_len >= tmp_len)
2641                                         {
2642                                                 descr_len -= tmp_len;
2643                                                 while( tmp_len > 2 )
2644                                                 {
2645                                                         memcpy(datetime+2, data+ptr, 3);
2646                                                         ptr += 3;
2647                                                         tmp_len -= 3;
2648                                                         start_times[datetime].push_back(service);
2649                                                 }
2650                                         }
2651                                 }
2652                         }
2653                         else
2654                         {
2655                                 *pdescr++=data+ptr;
2656                                 ptr += 2;
2657                                 ptr += descr_len;
2658                         }
2659                 }
2660         }
2661         ASSERT(pdescr <= &descriptors[65])
2662         __u8 event[4098];
2663         eit_event_struct *ev_struct = (eit_event_struct*) event;
2664         ev_struct->running_status = 0;
2665         ev_struct->free_CA_mode = 1;
2666         memcpy(event+7, duration, 3);
2667         ptr = 12;
2668         const __u8 **d=descriptors;
2669         while ( d < pdescr )
2670         {
2671                 memcpy(event+ptr, *d, ((*d)[1])+2);
2672                 ptr+=(*d++)[1];
2673                 ptr+=2;
2674         }
2675         ASSERT(ptr <= 4098);
2676         for ( std::map< date_time, std::list<uniqueEPGKey> >::iterator it(start_times.begin()); it != start_times.end(); ++it )
2677         {
2678                 time_t now = ::time(0);
2679                 if ( (it->first.tm + duration_sec) < now )
2680                         continue;
2681                 memcpy(event+2, it->first.data, 5);
2682                 int bptr = ptr;
2683                 int cnt=0;
2684                 for (std::list<uniqueEPGKey>::iterator i(it->second.begin()); i != it->second.end(); ++i)
2685                 {
2686                         event[bptr++] = 0x4A;
2687                         __u8 *len = event+(bptr++);
2688                         event[bptr++] = (i->tsid & 0xFF00) >> 8;
2689                         event[bptr++] = (i->tsid & 0xFF);
2690                         event[bptr++] = (i->onid & 0xFF00) >> 8;
2691                         event[bptr++] = (i->onid & 0xFF);
2692                         event[bptr++] = (i->sid & 0xFF00) >> 8;
2693                         event[bptr++] = (i->sid & 0xFF);
2694                         event[bptr++] = 0xB0;
2695                         bptr += sprintf((char*)(event+bptr), "Option %d", ++cnt);
2696                         *len = ((event+bptr) - len)-1;
2697                 }
2698                 int llen = bptr - 12;
2699                 ev_struct->descriptors_loop_length_hi = (llen & 0xF00) >> 8;
2700                 ev_struct->descriptors_loop_length_lo = (llen & 0xFF);
2701
2702                 time_t stime = it->first.tm;
2703                 while( tmMap.find(stime) != tmMap.end() )
2704                         ++stime;
2705                 event[6] += (stime - it->first.tm);
2706                 __u16 event_id = 0;
2707                 while( evMap.find(event_id) != evMap.end() )
2708                         ++event_id;
2709                 event[0] = (event_id & 0xFF00) >> 8;
2710                 event[1] = (event_id & 0xFF);
2711                 time_event_map[it->first.tm]=std::pair<time_t, __u16>(stime, event_id);
2712                 eventData *d = new eventData( ev_struct, bptr, PRIVATE );
2713                 evMap[event_id] = d;
2714                 tmMap[stime] = d;
2715                 ASSERT(bptr <= 4098);
2716         }
2717 }
2718
2719 void eEPGCache::channel_data::startPrivateReader()
2720 {
2721         eDVBSectionFilterMask mask;
2722         memset(&mask, 0, sizeof(mask));
2723         mask.pid = m_PrivatePid;
2724         mask.flags = eDVBSectionFilterMask::rfCRC;
2725         mask.data[0] = 0xA0;
2726         mask.mask[0] = 0xFF;
2727         eDebug("[EPGC] start privatefilter for pid %04x and version %d", m_PrivatePid, m_PrevVersion);
2728         if (m_PrevVersion != -1)
2729         {
2730                 mask.data[3] = m_PrevVersion << 1;
2731                 mask.mask[3] = 0x3E;
2732                 mask.mode[3] = 0x3E;
2733         }
2734         seenPrivateSections.clear();
2735         if (!m_PrivateConn)
2736                 m_PrivateReader->connectRead(slot(*this, &eEPGCache::channel_data::readPrivateData), m_PrivateConn);
2737         m_PrivateReader->start(mask);
2738 }
2739
2740 void eEPGCache::channel_data::readPrivateData( const __u8 *data)
2741 {
2742         if ( seenPrivateSections.find(data[6]) == seenPrivateSections.end() )
2743         {
2744                 cache->privateSectionRead(m_PrivateService, data);
2745                 seenPrivateSections.insert(data[6]);
2746         }
2747         if ( seenPrivateSections.size() == (unsigned int)(data[7] + 1) )
2748         {
2749                 eDebug("[EPGC] private finished");
2750                 eDVBChannelID chid = channel->getChannelID();
2751                 int tmp = chid.original_network_id.get();
2752                 tmp |= 0x80000000; // we use highest bit as private epg indicator
2753                 chid.original_network_id = tmp;
2754                 cache->channelLastUpdated[chid] = ::time(0);
2755                 m_PrevVersion = (data[5] & 0x3E) >> 1;
2756                 startPrivateReader();
2757         }
2758 }
2759
2760 #endif // ENABLE_PRIVATE_EPG
2761
2762 #ifdef ENABLE_MHW_EPG
2763 void eEPGCache::channel_data::cleanup()
2764 {
2765         m_channels.clear();
2766         m_themes.clear();
2767         m_titles.clear();
2768         m_program_ids.clear();
2769 }
2770
2771 __u8 *eEPGCache::channel_data::delimitName( __u8 *in, __u8 *out, int len_in )
2772 {
2773         // Names in mhw structs are not strings as they are not '\0' terminated.
2774         // This function converts the mhw name into a string.
2775         // Constraint: "length of out" = "length of in" + 1.
2776         int i;
2777         for ( i=0; i < len_in; i++ )
2778                 out[i] = in[i];
2779
2780         i = len_in - 1;
2781         while ( ( i >=0 ) && ( out[i] == 0x20 ) )
2782                 i--;
2783
2784         out[i+1] = 0;
2785         return out;
2786 }
2787
2788 void eEPGCache::channel_data::timeMHW2DVB( u_char hours, u_char minutes, u_char *return_time)
2789 // For time of day
2790 {
2791         return_time[0] = toBCD( hours );
2792         return_time[1] = toBCD( minutes );
2793         return_time[2] = 0;
2794 }
2795
2796 void eEPGCache::channel_data::timeMHW2DVB( int minutes, u_char *return_time)
2797 {
2798         timeMHW2DVB( int(minutes/60), minutes%60, return_time );
2799 }
2800
2801 void eEPGCache::channel_data::timeMHW2DVB( u_char day, u_char hours, u_char minutes, u_char *return_time)
2802 // For date plus time of day
2803 {
2804         // Remove offset in mhw time.
2805         __u8 local_hours = hours;
2806         if ( hours >= 16 )
2807                 local_hours -= 4;
2808         else if ( hours >= 8 )
2809                 local_hours -= 2;
2810
2811         // As far as we know all mhw time data is sent in central Europe time zone.
2812         // So, temporarily set timezone to western europe
2813         time_t dt = ::time(0);
2814
2815         char *old_tz = getenv( "TZ" );
2816         putenv("TZ=CET-1CEST,M3.5.0/2,M10.5.0/3");
2817         tzset();
2818
2819         tm localnow;
2820         localtime_r(&dt, &localnow);
2821
2822         if (day == 7)
2823                 day = 0;
2824         if ( day + 1 < localnow.tm_wday )               // day + 1 to prevent old events to show for next week.
2825                 day += 7;
2826         if (local_hours <= 5)
2827                 day++;
2828
2829         dt += 3600*24*(day - localnow.tm_wday); // Shift dt to the recording date (local time zone).
2830         dt += 3600*(local_hours - localnow.tm_hour);  // Shift dt to the recording hour.
2831
2832         tm recdate;
2833         gmtime_r( &dt, &recdate );   // This will also take care of DST.
2834
2835         if ( old_tz == NULL )
2836                 unsetenv( "TZ" );
2837         else
2838                 putenv( old_tz );
2839         tzset();
2840
2841         // Calculate MJD according to annex in ETSI EN 300 468
2842         int l=0;
2843         if ( recdate.tm_mon <= 1 )      // Jan or Feb
2844                 l=1;
2845         int mjd = 14956 + recdate.tm_mday + int( (recdate.tm_year - l) * 365.25) +
2846                 int( (recdate.tm_mon + 2 + l * 12) * 30.6001);
2847
2848         return_time[0] = (mjd & 0xFF00)>>8;
2849         return_time[1] = mjd & 0xFF;
2850
2851         timeMHW2DVB( recdate.tm_hour, minutes, return_time+2 );
2852 }
2853
2854 void eEPGCache::channel_data::storeTitle(std::map<__u32, mhw_title_t>::iterator itTitle, std::string sumText, const __u8 *data)
2855 // data is borrowed from calling proc to save memory space.
2856 {
2857         __u8 name[34];
2858
2859         // For each title a separate EIT packet will be sent to eEPGCache::sectionRead()
2860         bool isMHW2 = itTitle->second.mhw2_mjd_hi || itTitle->second.mhw2_mjd_lo ||
2861                 itTitle->second.mhw2_duration_hi || itTitle->second.mhw2_duration_lo;
2862
2863         eit_t *packet = (eit_t *) data;
2864         packet->table_id = 0x50;
2865         packet->section_syntax_indicator = 1;
2866
2867         packet->service_id_hi = m_channels[ itTitle->second.channel_id - 1 ].channel_id_hi;
2868         packet->service_id_lo = m_channels[ itTitle->second.channel_id - 1 ].channel_id_lo;
2869         packet->version_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2870         packet->current_next_indicator = 0;
2871         packet->section_number = 0;     // eEPGCache::sectionRead() will dig this for the moment
2872         packet->last_section_number = 0;        // eEPGCache::sectionRead() will dig this for the moment
2873         packet->transport_stream_id_hi = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_hi;
2874         packet->transport_stream_id_lo = m_channels[ itTitle->second.channel_id - 1 ].transport_stream_id_lo;
2875         packet->original_network_id_hi = m_channels[ itTitle->second.channel_id - 1 ].network_id_hi;
2876         packet->original_network_id_lo = m_channels[ itTitle->second.channel_id - 1 ].network_id_lo;
2877         packet->segment_last_section_number = 0; // eEPGCache::sectionRead() will dig this for the moment
2878         packet->segment_last_table_id = 0x50;
2879
2880         __u8 *title = isMHW2 ? ((__u8*)(itTitle->second.title))-4 : (__u8*)itTitle->second.title;
2881         std::string prog_title = (char *) delimitName( title, name, isMHW2 ? 33 : 23 );
2882         int prog_title_length = prog_title.length();
2883
2884         int packet_length = EIT_SIZE + EIT_LOOP_SIZE + EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2885                 prog_title_length + 1;
2886
2887         eit_event_t *event_data = (eit_event_t *) (data + EIT_SIZE);
2888         event_data->event_id_hi = (( itTitle->first ) >> 8 ) & 0xFF;
2889         event_data->event_id_lo = ( itTitle->first ) & 0xFF;
2890
2891         if (isMHW2)
2892         {
2893                 u_char *data = (u_char*) event_data;
2894                 data[2] = itTitle->second.mhw2_mjd_hi;
2895                 data[3] = itTitle->second.mhw2_mjd_lo;
2896                 data[4] = itTitle->second.mhw2_hours;
2897                 data[5] = itTitle->second.mhw2_minutes;
2898                 data[6] = itTitle->second.mhw2_seconds;
2899                 timeMHW2DVB( HILO(itTitle->second.mhw2_duration), data+7 );
2900         }
2901         else
2902         {
2903                 timeMHW2DVB( itTitle->second.dh.day, itTitle->second.dh.hours, itTitle->second.ms.minutes,
2904                 (u_char *) event_data + 2 );
2905                 timeMHW2DVB( HILO(itTitle->second.duration), (u_char *) event_data+7 );
2906         }
2907
2908         event_data->running_status = 0;
2909         event_data->free_CA_mode = 0;
2910         int descr_ll = EIT_SHORT_EVENT_DESCRIPTOR_SIZE + 1 + prog_title_length;
2911
2912         eit_short_event_descriptor_struct *short_event_descriptor =
2913                 (eit_short_event_descriptor_struct *) ( (u_char *) event_data + EIT_LOOP_SIZE);
2914         short_event_descriptor->descriptor_tag = EIT_SHORT_EVENT_DESCRIPTOR;
2915         short_event_descriptor->descriptor_length = EIT_SHORT_EVENT_DESCRIPTOR_SIZE +
2916                 prog_title_length - 1;
2917         short_event_descriptor->language_code_1 = 'e';
2918         short_event_descriptor->language_code_2 = 'n';
2919         short_event_descriptor->language_code_3 = 'g';
2920         short_event_descriptor->event_name_length = prog_title_length;
2921         u_char *event_name = (u_char *) short_event_descriptor + EIT_SHORT_EVENT_DESCRIPTOR_SIZE;
2922         memcpy(event_name, prog_title.c_str(), prog_title_length);
2923
2924         // Set text length
2925         event_name[prog_title_length] = 0;
2926
2927         if ( sumText.length() > 0 )
2928         // There is summary info
2929         {
2930                 unsigned int sum_length = sumText.length();
2931                 if ( sum_length + short_event_descriptor->descriptor_length <= 0xff )
2932                 // Store summary in short event descriptor
2933                 {
2934                         // Increase all relevant lengths
2935                         event_name[prog_title_length] = sum_length;
2936                         short_event_descriptor->descriptor_length += sum_length;
2937                         packet_length += sum_length;
2938                         descr_ll += sum_length;
2939                         sumText.copy( (char *) event_name+prog_title_length+1, sum_length );
2940                 }
2941                 else
2942                 // Store summary in extended event descriptors
2943                 {
2944                         int remaining_sum_length = sumText.length();
2945                         int nbr_descr = int(remaining_sum_length/247) + 1;
2946                         for ( int i=0; i < nbr_descr; i++)
2947                         // Loop once per extended event descriptor
2948                         {
2949                                 eit_extended_descriptor_struct *ext_event_descriptor = (eit_extended_descriptor_struct *) (data + packet_length);
2950                                 sum_length = remaining_sum_length > 247 ? 247 : remaining_sum_length;
2951                                 remaining_sum_length -= sum_length;
2952                                 packet_length += 8 + sum_length;
2953                                 descr_ll += 8 + sum_length;
2954
2955                                 ext_event_descriptor->descriptor_tag = EIT_EXTENDED_EVENT_DESCRIPOR;
2956                                 ext_event_descriptor->descriptor_length = sum_length + 6;
2957                                 ext_event_descriptor->descriptor_number = i;
2958                                 ext_event_descriptor->last_descriptor_number = nbr_descr - 1;
2959                                 ext_event_descriptor->iso_639_2_language_code_1 = 'e';
2960                                 ext_event_descriptor->iso_639_2_language_code_2 = 'n';
2961                                 ext_event_descriptor->iso_639_2_language_code_3 = 'g';
2962                                 u_char *the_text = (u_char *) ext_event_descriptor + 8;
2963                                 the_text[-2] = 0;
2964                                 the_text[-1] = sum_length;
2965                                 sumText.copy( (char *) the_text, sum_length, sumText.length() - sum_length - remaining_sum_length );
2966                         }
2967                 }
2968         }
2969
2970         if (!isMHW2)
2971         {
2972                 // Add content descriptor
2973                 u_char *descriptor = (u_char *) data + packet_length;
2974                 packet_length += 4;
2975                 descr_ll += 4;
2976
2977                 int content_id = 0;
2978                 std::string content_descr = (char *) delimitName( m_themes[itTitle->second.theme_id].name, name, 15 );
2979                 if ( content_descr.find( "FILM" ) != std::string::npos )
2980                         content_id = 0x10;
2981                 else if ( content_descr.find( "SPORT" ) != std::string::npos )
2982                         content_id = 0x40;
2983
2984                 descriptor[0] = 0x54;
2985                 descriptor[1] = 2;
2986                 descriptor[2] = content_id;
2987                 descriptor[3] = 0;
2988         }
2989
2990         event_data->descriptors_loop_length_hi = (descr_ll & 0xf00)>>8;
2991         event_data->descriptors_loop_length_lo = (descr_ll & 0xff);
2992
2993         packet->section_length_hi =  ((packet_length - 3)&0xf00)>>8;
2994         packet->section_length_lo =  (packet_length - 3)&0xff;
2995
2996         // Feed the data to eEPGCache::sectionRead()
2997         cache->sectionRead( data, MHW, this );
2998 }
2999
3000 void eEPGCache::channel_data::startTimeout(int msec)
3001 {
3002         m_MHWTimeoutTimer->start(msec,true);
3003         m_MHWTimeoutet=false;
3004 }
3005
3006 void eEPGCache::channel_data::startMHWReader(__u16 pid, __u8 tid)
3007 {
3008         m_MHWFilterMask.pid = pid;
3009         m_MHWFilterMask.data[0] = tid;
3010         m_MHWReader->start(m_MHWFilterMask);
3011 //      eDebug("start 0x%02x 0x%02x", pid, tid);
3012 }
3013
3014 void eEPGCache::channel_data::startMHWReader2(__u16 pid, __u8 tid, int ext)
3015 {
3016         m_MHWFilterMask2.pid = pid;
3017         m_MHWFilterMask2.data[0] = tid;
3018         if (ext != -1)
3019         {
3020                 m_MHWFilterMask2.data[1] = ext;
3021                 m_MHWFilterMask2.mask[1] = 0xFF;
3022 //              eDebug("start 0x%03x 0x%02x 0x%02x", pid, tid, ext);
3023         }
3024         else
3025         {
3026                 m_MHWFilterMask2.data[1] = 0;
3027                 m_MHWFilterMask2.mask[1] = 0;
3028 //              eDebug("start 0x%02x 0x%02x", pid, tid);
3029         }
3030         m_MHWReader2->start(m_MHWFilterMask2);
3031 }
3032
3033 void eEPGCache::channel_data::readMHWData(const __u8 *data)
3034 {
3035         if ( m_MHWReader2 )
3036                 m_MHWReader2->stop();
3037
3038         if ( state > 1 || // aborted
3039                 // have si data.. so we dont read mhw data
3040                 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3041         {
3042                 eDebug("[EPGC] mhw aborted %d", state);
3043         }
3044         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x91)
3045         // Channels table
3046         {
3047                 int len = ((data[1]&0xf)<<8) + data[2] - 1;
3048                 int record_size = sizeof( mhw_channel_name_t );
3049                 int nbr_records = int (len/record_size);
3050
3051                 m_channels.resize(nbr_records);
3052                 for ( int i = 0; i < nbr_records; i++ )
3053                 {
3054                         mhw_channel_name_t *channel = (mhw_channel_name_t*) &data[4 + i*record_size];
3055                         m_channels[i]=*channel;
3056                 }
3057                 haveData |= MHW;
3058
3059                 eDebug("[EPGC] mhw %d channels found", m_channels.size());
3060
3061                 // Channels table has been read, start reading the themes table.
3062                 startMHWReader(0xD3, 0x92);
3063                 return;
3064         }
3065         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x92)
3066         // Themes table
3067         {
3068                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3069                 int record_size = sizeof( mhw_theme_name_t );
3070                 int nbr_records = int (len/record_size);
3071                 int idx_ptr = 0;
3072                 __u8 next_idx = (__u8) *(data + 3 + idx_ptr);
3073                 __u8 idx = 0;
3074                 __u8 sub_idx = 0;
3075                 for ( int i = 0; i < nbr_records; i++ )
3076                 {
3077                         mhw_theme_name_t *theme = (mhw_theme_name_t*) &data[19 + i*record_size];
3078                         if ( i >= next_idx )
3079                         {
3080                                 idx = (idx_ptr<<4);
3081                                 idx_ptr++;
3082                                 next_idx = (__u8) *(data + 3 + idx_ptr);
3083                                 sub_idx = 0;
3084                         }
3085                         else
3086                                 sub_idx++;
3087
3088                         m_themes[idx+sub_idx] = *theme;
3089                 }
3090                 eDebug("[EPGC] mhw %d themes found", m_themes.size());
3091                 // Themes table has been read, start reading the titles table.
3092                 startMHWReader(0xD2, 0x90);
3093                 startTimeout(4000);
3094                 return;
3095         }
3096         else if (m_MHWFilterMask.pid == 0xD2 && m_MHWFilterMask.data[0] == 0x90)
3097         // Titles table
3098         {
3099                 mhw_title_t *title = (mhw_title_t*) data;
3100
3101                 if ( title->channel_id == 0xFF )        // Separator
3102                         return; // Continue reading of the current table.
3103                 else
3104                 {
3105                         // Create unique key per title
3106                         __u32 title_id = ((title->channel_id)<<16)|((title->dh.day)<<13)|((title->dh.hours)<<8)|
3107                                 (title->ms.minutes);
3108                         __u32 program_id = ((title->program_id_hi)<<24)|((title->program_id_mh)<<16)|
3109                                 ((title->program_id_ml)<<8)|(title->program_id_lo);
3110
3111                         if ( m_titles.find( title_id ) == m_titles.end() )
3112                         {
3113                                 startTimeout(4000);
3114                                 title->mhw2_mjd_hi = 0;
3115                                 title->mhw2_mjd_lo = 0;
3116                                 title->mhw2_duration_hi = 0;
3117                                 title->mhw2_duration_lo = 0;
3118                                 m_titles[ title_id ] = *title;
3119                                 if ( (title->ms.summary_available) && (m_program_ids.find(program_id) == m_program_ids.end()) )
3120                                         // program_ids will be used to gather summaries.
3121                                         m_program_ids.insert(std::pair<__u32,__u32>(program_id,title_id));
3122                                 return; // Continue reading of the current table.
3123                         }
3124                         else if (!checkTimeout())
3125                                 return;
3126                 }
3127                 if ( !m_program_ids.empty())
3128                 {
3129                         // Titles table has been read, there are summaries to read.
3130                         // Start reading summaries, store corresponding titles on the fly.
3131                         startMHWReader(0xD3, 0x90);
3132                         eDebug("[EPGC] mhw %d titles(%d with summary) found",
3133                                 m_titles.size(),
3134                                 m_program_ids.size());
3135                         startTimeout(4000);
3136                         return;
3137                 }
3138         }
3139         else if (m_MHWFilterMask.pid == 0xD3 && m_MHWFilterMask.data[0] == 0x90)
3140         // Summaries table
3141         {
3142                 mhw_summary_t *summary = (mhw_summary_t*) data;
3143
3144                 // Create unique key per record
3145                 __u32 program_id = ((summary->program_id_hi)<<24)|((summary->program_id_mh)<<16)|
3146                         ((summary->program_id_ml)<<8)|(summary->program_id_lo);
3147                 int len = ((data[1]&0xf)<<8) + data[2];
3148
3149                 // ugly workaround to convert const __u8* to char*
3150                 char *tmp=0;
3151                 memcpy(&tmp, &data, sizeof(void*));
3152                 tmp[len+3] = 0; // Terminate as a string.
3153
3154                 std::multimap<__u32, __u32>::iterator itProgid( m_program_ids.find( program_id ) );
3155                 if ( itProgid == m_program_ids.end() )
3156                 { /*    This part is to prevent to looping forever if some summaries are not received yet.
3157                         There is a timeout of 4 sec. after the last successfully read summary. */
3158                         if (!m_program_ids.empty() && !checkTimeout())
3159                                 return; // Continue reading of the current table.
3160                 }
3161                 else
3162                 {
3163                         std::string the_text = (char *) (data + 11 + summary->nb_replays * 7);
3164
3165                         unsigned int pos=0;
3166                         while((pos = the_text.find("\r\n")) != std::string::npos)
3167                                 the_text.replace(pos, 2, " ");
3168
3169                         // Find corresponding title, store title and summary in epgcache.
3170                         std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgid->second ) );
3171                         if ( itTitle != m_titles.end() )
3172                         {
3173                                 startTimeout(4000);
3174                                 storeTitle( itTitle, the_text, data );
3175                                 m_titles.erase( itTitle );
3176                         }
3177                         m_program_ids.erase( itProgid );
3178                         if ( !m_program_ids.empty() )
3179                                 return; // Continue reading of the current table.
3180                 }
3181         }
3182         eDebug("[EPGC] mhw finished(%ld) %d summaries not found",
3183                 ::time(0),
3184                 m_program_ids.size());
3185         // Summaries have been read, titles that have summaries have been stored.
3186         // Now store titles that do not have summaries.
3187         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3188                 storeTitle( itTitle, "", data );
3189         isRunning &= ~MHW;
3190         m_MHWConn=0;
3191         if ( m_MHWReader )
3192                 m_MHWReader->stop();
3193         if (haveData)
3194                 finishEPG();
3195 }
3196
3197 void eEPGCache::channel_data::readMHWData2(const __u8 *data)
3198 {
3199         int dataLen = (((data[1]&0xf) << 8) | data[2]) + 3;
3200
3201         if ( m_MHWReader )
3202                 m_MHWReader->stop();
3203
3204         if ( state > 1 || // aborted
3205                 // have si data.. so we dont read mhw data
3206                 (haveData & (SCHEDULE|SCHEDULE_OTHER|VIASAT)) )
3207         {
3208                 eDebug("[EPGC] mhw2 aborted %d", state);
3209         }
3210         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3211         // Channels table
3212         {
3213                 int num_channels = data[119];
3214                 m_channels.resize(num_channels);
3215                 if(dataLen > 119)
3216                 {
3217                         int ptr = 120 + 8 * num_channels;
3218                         if( dataLen > ptr )
3219                         {
3220                                 for( int chid = 0; chid < num_channels; ++chid )
3221                                 {
3222                                         ptr += ( data[ptr] & 0x0f ) + 1;
3223                                         if( dataLen < ptr )
3224                                                 goto abort;
3225                                 }
3226                         }
3227                         else
3228                                 goto abort;
3229                 }
3230                 else
3231                         goto abort;
3232                 // data seems consistent...
3233                 const __u8 *tmp = data+120;
3234                 for (int i=0; i < num_channels; ++i)
3235                 {
3236                         mhw_channel_name_t channel;
3237                         channel.network_id_hi = *(tmp++);
3238                         channel.network_id_lo = *(tmp++);
3239                         channel.transport_stream_id_hi = *(tmp++);
3240                         channel.transport_stream_id_lo = *(tmp++);
3241                         channel.channel_id_hi = *(tmp++);
3242                         channel.channel_id_lo = *(tmp++);
3243                         m_channels[i]=channel;
3244                         tmp+=2;
3245                 }
3246                 for (int i=0; i < num_channels; ++i)
3247                 {
3248                         mhw_channel_name_t &channel = m_channels[i];
3249                         int channel_name_len=*(tmp++)&0x0f;
3250                         int x=0;
3251                         for (; x < channel_name_len; ++x)
3252                                 channel.name[x]=*(tmp++);
3253                         channel.name[x+1]=0;
3254                 }
3255                 haveData |= MHW;
3256                 eDebug("[EPGC] mhw2 %d channels found", m_channels.size());
3257         }
3258         else if (m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3259         {
3260                 // Themes table
3261                 eDebug("[EPGC] mhw2 themes nyi");
3262         }
3263         else if (m_MHWFilterMask2.pid == 0x234 && m_MHWFilterMask2.data[0] == 0xe6)
3264         // Titles table
3265         {
3266                 int pos=18;
3267                 bool valid=true;
3268                 int len = ((data[1]&0xf)<<8) + data[2] - 16;
3269                 bool finish=false;
3270                 if(data[dataLen-1] != 0xff)
3271                         return;
3272                 while( pos < dataLen )
3273                 {
3274                         valid = false;
3275                         pos += 7;
3276                         if( pos < dataLen )
3277                         {
3278                                 pos += 3;
3279                                 if( pos < dataLen )
3280                                 {
3281                                         if( data[pos] > 0xc0 )
3282                                         {
3283                                                 pos += ( data[pos] - 0xc0 );
3284                                                 pos += 4;
3285                                                 if( pos < dataLen )
3286                                                 {
3287                                                         if( data[pos] == 0xff )
3288                                                         {
3289                                                                 ++pos;
3290                                                                 valid = true;
3291                                                         }
3292                                                 }
3293                                         }
3294                                 }
3295                         }
3296                         if( !valid )
3297                         {
3298                                 if (checkTimeout())
3299                                         goto start_summary;
3300                                 return;
3301                         }
3302                 }
3303                 // data seems consistent...
3304                 mhw_title_t title;
3305                 pos = 18;
3306                 while (pos < len)
3307                 {
3308                         title.channel_id = data[pos]+1;
3309                         title.program_id_ml = data[pos+1];
3310                         title.program_id_lo = data[pos+2];
3311                         title.mhw2_mjd_hi = data[pos+3];
3312                         title.mhw2_mjd_lo = data[pos+4];
3313                         title.mhw2_hours = data[pos+5];
3314                         title.mhw2_minutes = data[pos+6];
3315                         title.mhw2_seconds = data[pos+7];
3316                         int duration = ((data[pos+8] << 8)|data[pos+9]) >> 4;
3317                         title.mhw2_duration_hi = (duration&0xFF00) >> 8;
3318                         title.mhw2_duration_lo = duration&0xFF;
3319                         __u8 slen = data[pos+10] & 0x3f;
3320                         __u8 *dest = ((__u8*)title.title)-4;
3321                         memcpy(dest, &data[pos+11], slen>33 ? 33 : slen);
3322                         memset(dest+slen, 0, 33-slen);
3323                         pos += 11 + slen;
3324 //                      not used theme id (data[7] & 0x3f) + (data[pos] & 0x3f);
3325                         __u32 summary_id = (data[pos+1] << 8) | data[pos+2];
3326
3327                         // Create unique key per title
3328                         __u32 title_id = (title.channel_id<<16) | (title.program_id_ml<<8) | title.program_id_lo;
3329
3330                         pos += 4;
3331
3332                         std::map<__u32, mhw_title_t>::iterator it = m_titles.find( title_id );
3333                         if ( it == m_titles.end() )
3334                         {
3335                                 startTimeout(5000);
3336                                 m_titles[ title_id ] = title;
3337                                 if (summary_id != 0xFFFF)
3338                                 {
3339                                         bool add=true;
3340                                         std::multimap<__u32, __u32>::iterator it(m_program_ids.lower_bound(summary_id));
3341                                         while (it != m_program_ids.end() && it->first == summary_id)
3342                                         {
3343                                                 if (it->second == title_id) {
3344                                                         add=false;
3345                                                         break;
3346                                                 }
3347                                                 ++it;
3348                                         }
3349                                         if (add)
3350                                                 m_program_ids.insert(std::pair<__u32,__u32>(summary_id,title_id));
3351                                 }
3352                         }
3353                         else
3354                         {
3355                                 if ( !checkTimeout() )
3356                                         continue;       // Continue reading of the current table.
3357                                 finish=true;
3358                                 break;
3359                         }
3360                 }
3361 start_summary:
3362                 if (finish)
3363                 {
3364                         eDebug("[EPGC] mhw2 %d titles(%d with summary) found", m_titles.size(), m_program_ids.size());
3365                         if (!m_program_ids.empty())
3366                         {
3367                                 // Titles table has been read, there are summaries to read.
3368                                 // Start reading summaries, store corresponding titles on the fly.
3369                                 startMHWReader2(0x236, 0x96);
3370                                 startTimeout(15000);
3371                                 return;
3372                         }
3373                 }
3374                 else
3375                         return;
3376         }
3377         else if (m_MHWFilterMask2.pid == 0x236 && m_MHWFilterMask2.data[0] == 0x96)
3378         // Summaries table
3379         {
3380                 if (!checkTimeout())
3381                 {
3382                         int len, loop, pos, lenline;
3383                         bool valid;
3384                         valid = true;
3385                         if( dataLen > 15 )
3386                         {
3387                                 loop = data[14];
3388                                 pos = 15 + loop;
3389                                 if( dataLen > pos )
3390                                 {
3391                                         loop = data[pos] & 0x0f;
3392                                         pos += 1;
3393                                         if( dataLen > pos )
3394                                         {
3395                                                 len = 0;
3396                                                 for( ; loop > 0; --loop )
3397                                                 {
3398                                                         if( dataLen > (pos+len) )
3399                                                         {
3400                                                                 lenline = data[pos+len];
3401                                                                 len += lenline + 1;
3402                                                         }
3403                                                         else
3404                                                                 valid=false;
3405                                                 }
3406                                         }
3407                                 }
3408                         }
3409                         else
3410                                 return;  // continue reading
3411                         if (valid)
3412                         {
3413                                 // data seems consistent...
3414                                 __u32 summary_id = (data[3]<<8)|data[4];
3415
3416                                 // ugly workaround to convert const __u8* to char*
3417                                 char *tmp=0;
3418                                 memcpy(&tmp, &data, sizeof(void*));
3419
3420                                 len = 0;
3421                                 loop = data[14];
3422                                 pos = 15 + loop;
3423                                 loop = tmp[pos] & 0x0f;
3424                                 pos += 1;
3425                                 for( ; loop > 0; loop -- )
3426                                 {
3427                                         lenline = tmp[pos+len];
3428                                         tmp[pos+len] = ' ';
3429                                         len += lenline + 1;
3430                                 }
3431                                 if( len > 0 )
3432                                     tmp[pos+len] = 0;
3433                                 else
3434                                         tmp[pos+1] = 0;
3435
3436                                 std::multimap<__u32, __u32>::iterator itProgId( m_program_ids.lower_bound(summary_id) );
3437                                 if ( itProgId == m_program_ids.end() || itProgId->first != summary_id)
3438                                 { /*    This part is to prevent to looping forever if some summaries are not received yet.
3439                                         There is a timeout of 4 sec. after the last successfully read summary. */
3440                                         if ( !m_program_ids.empty() )
3441                                                 return; // Continue reading of the current table.
3442                                 }
3443                                 else
3444                                 {
3445                                         startTimeout(15000);
3446                                         std::string the_text = (char *) (data + pos + 1);
3447
3448                                         while( itProgId != m_program_ids.end() && itProgId->first == summary_id )
3449                                         {
3450                                                 // Find corresponding title, store title and summary in epgcache.
3451                                                 std::map<__u32, mhw_title_t>::iterator itTitle( m_titles.find( itProgId->second ) );
3452                                                 if ( itTitle != m_titles.end() )
3453                                                 {
3454                                                         storeTitle( itTitle, the_text, data );
3455                                                         m_titles.erase( itTitle );
3456                                                 }
3457                                                 m_program_ids.erase( itProgId++ );
3458                                         }
3459                                         if ( !m_program_ids.empty() )
3460                                                 return; // Continue reading of the current table.
3461                                 }
3462                         }
3463                         else
3464                                 return;  // continue reading
3465                 }
3466         }
3467         if (isRunning & eEPGCache::MHW)
3468         {
3469                 if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 0)
3470                 {
3471                         // Channels table has been read, start reading the themes table.
3472                         startMHWReader2(0x231, 0xC8, 1);
3473                         return;
3474                 }
3475                 else if ( m_MHWFilterMask2.pid == 0x231 && m_MHWFilterMask2.data[0] == 0xC8 && m_MHWFilterMask2.data[1] == 1)
3476                 {
3477                         // Themes table has been read, start reading the titles table.
3478                         startMHWReader2(0x234, 0xe6);
3479                         return;
3480                 }
3481                 else
3482                 {
3483                         // Summaries have been read, titles that have summaries have been stored.
3484                         // Now store titles that do not have summaries.
3485                         for (std::map<__u32, mhw_title_t>::iterator itTitle(m_titles.begin()); itTitle != m_titles.end(); itTitle++)
3486                                 storeTitle( itTitle, "", data );
3487                         eDebug("[EPGC] mhw2 finished(%ld) %d summaries not found",
3488                                 ::time(0),
3489                                 m_program_ids.size());
3490                 }
3491         }
3492 abort:
3493         isRunning &= ~MHW;
3494         m_MHWConn2=0;
3495         if ( m_MHWReader2 )
3496                 m_MHWReader2->stop();
3497         if (haveData)
3498                 finishEPG();
3499 }
3500 #endif