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