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