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