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